mcanoglu/cwe-class-group huggingface dataset:
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);
    }

// Vulnerability class: CWE-287
public void canMixConvertedAndNormalValues() {
        final HttpHeadersBase headers = newEmptyHeaders();
        headers.add("name", "value");
        headers.addInt("name", 100);

        assertThat(headers.size()).isEqualTo(2);
        assertThat(headers.contains("name")).isTrue();
        assertThat(headers.contains("name", "value")).isTrue();
        assertThat(headers.containsInt("name", 100)).isTrue();
    }

// Vulnerability class: CWE-74
public void translate(ServerSpawnPaintingPacket packet, GeyserSession session) {
        Vector3f position = Vector3f.from(packet.getPosition().getX(), packet.getPosition().getY(), packet.getPosition().getZ());

        PaintingEntity entity = new PaintingEntity(packet.getEntityId(),
                session.getEntityCache().getNextEntityId().incrementAndGet(),
                position, PaintingType.getByPaintingType(packet.getPaintingType()), packet.getDirection().ordinal());

        session.getEntityCache().spawnEntity(entity);
    }

// Vulnerability class: CWE-287
final void set(CharSequence name, Iterable<String> values) {
        final AsciiString normalizedName = normalizeName(name);
        requireNonNull(values, "values");

        final int h = normalizedName.hashCode();
        final int i = index(h);

        remove0(h, i, normalizedName);
        for (String v : values) {
            requireNonNullElement(values, v);
            add0(h, i, normalizedName, v);
        }
    }

// Vulnerability class: CWE-74
public void translate(PositionTrackingDBClientRequestPacket packet, GeyserSession session) {
        PositionTrackingDBServerBroadcastPacket broadcastPacket = new PositionTrackingDBServerBroadcastPacket();
        broadcastPacket.setTrackingId(packet.getTrackingId());

        // Fetch the stored Loadstone
        LoadstoneTracker.LoadstonePos pos = LoadstoneTracker.getPos(packet.getTrackingId());

        // If we don't have data for that ID tell the client its not found
        if (pos == null) {
            broadcastPacket.setAction(PositionTrackingDBServerBroadcastPacket.Action.NOT_FOUND);
            session.sendUpstreamPacket(broadcastPacket);
            return;
        }

        broadcastPacket.setAction(PositionTrackingDBServerBroadcastPacket.Action.UPDATE);

        // Build the nbt data for the update
        NbtMapBuilder builder = NbtMap.builder();
        builder.putInt("dim", DimensionUtils.javaToBedrock(pos.getDimension()));
        builder.putString("id", String.format("%08X", packet.getTrackingId()));

        builder.putByte("version", (byte) 1); // Not sure what this is for
        builder.putByte("status", (byte) 0); // Not sure what this is for

        // Build the position for the update
        IntList posList = new IntArrayList();
        posList.add(pos.getX());
        posList.add(pos.getY());
        posList.add(pos.getZ());
        builder.putList("pos", NbtType.INT, posList);
        broadcastPacket.setTag(builder.build());

        session.sendUpstreamPacket(broadcastPacket);
    }

// Vulnerability class: CWE-287
public void existingDocumentFromUITemplateProviderSpecifiedNonTerminalOverridenFromUIToTerminal() throws Exception
    {
        // current document = xwiki:Main.WebHome
        DocumentReference documentReference = new DocumentReference("xwiki", Arrays.asList("Main"), "WebHome");
        XWikiDocument document = mock(XWikiDocument.class);
        when(document.getDocumentReference()).thenReturn(documentReference);
        when(document.isNew()).thenReturn(false);
        when(document.getLocalReferenceMaxLength()).thenReturn(255);
        context.setDoc(document);

        // Submit from the UI spaceReference=X&name=Y&templateProvider=XWiki.MyTemplateProvider
        String templateProviderFullName = "XWiki.MyTemplateProvider";
        String spaceReferenceString = "X";
        when(mockRequest.getParameter("spaceReference")).thenReturn(spaceReferenceString);
        when(mockRequest.getParameter("name")).thenReturn("Y");
        when(mockRequest.getParameter("templateprovider")).thenReturn(templateProviderFullName);
        when(mockRequest.getParameter("tocreate")).thenReturn("terminal");

        // Mock 1 existing template provider that creates terminal documents.
        mockExistingTemplateProviders(templateProviderFullName,
            new DocumentReference("xwiki", Arrays.asList("XWiki"), "MyTemplateProvider"), Collections.EMPTY_LIST,
            false);

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

        // The tests are below this line!

        // Verify null is returned (this means the response has been returned)
        assertNull(result);

        // Note: We are creating the document X.Y as terminal, even if the template provider says otherwise.
        // Also using a template, as specified in the template provider.
        verify(mockURLFactory).createURL("X", "Y", "edit", "template=XWiki.MyTemplate&parent=Main.WebHome&title=Y",
            null, "xwiki", context);
    }

// Vulnerability class: CWE-862
public void testClearResetsPseudoHeaderDivision() {
        final HttpHeadersBase http2Headers = newHttp2Headers();
        http2Headers.method(HttpMethod.POST);
        http2Headers.set("some", "value");
        http2Headers.clear();
        http2Headers.method(HttpMethod.GET);
        assertThat(http2Headers.names()).containsExactly(HttpHeaderNames.METHOD);
        assertThat(http2Headers.getAll(HttpHeaderNames.METHOD)).containsExactly("GET");
    }

// Vulnerability class: CWE-74
public void onTurnEnded(TurnEndedEvent event) {
		super.onTurnEnded(event);

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

		if (out.contains("access denied (java.net.SocketPermission")
				|| out.contains("access denied (\"java.net.SocketPermission\"")) {
			messagedAccessDenied = true;	
		}	
	}

// Vulnerability class: CWE-862
public void testOfAsciiString() {
        // Should produce a lower-cased AsciiString.
        final AsciiString mixedCased = AsciiString.of("Foo");
        assertThat((Object) HttpHeaderNames.of(mixedCased)).isNotSameAs(mixedCased);
        assertThat(HttpHeaderNames.of(mixedCased).toString()).isEqualTo("foo");

        // Should not produce a new instance for an AsciiString that's already lower-cased.
        final AsciiString lowerCased = AsciiString.of("foo");
        assertThat((Object) HttpHeaderNames.of(lowerCased)).isSameAs(lowerCased);

        // Should reuse known header name instances.
        assertThat((Object) HttpHeaderNames.of(AsciiString.of("date"))).isSameAs(HttpHeaderNames.DATE);
    }

// Vulnerability class: CWE-74
public void translate(TextPacket packet, GeyserSession session) {
        String message = packet.getMessage();

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

        ClientChatPacket chatPacket = new ClientChatPacket(message);
        session.sendDownstreamPacket(chatPacket);
    }

// Vulnerability class: CWE-287
public String render(String templateContent, Map<String, Object> context) {
		VelocityContext velocityContext = new VelocityContext(context);
		try (StringWriter sw = new StringWriter()) {
			Velocity.evaluate(velocityContext, sw, "velocityTemplateEngine", templateContent);
			return sw.toString();
		}
		catch (Exception ex) {
			throw new TemplateRenderException(ex);
		}
	}

// Vulnerability class: CWE-20
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();
    }
  }

// Vulnerability class: CWE-863
private SecretKey getKey() {
        try {
            if (secret==null) {
                synchronized (this) {
                    if (secret==null) {
                        byte[] payload = load();
                        if (payload==null) {
                            payload = ConfidentialStore.get().randomBytes(256);
                            store(payload);
                        }
                        // Due to the stupid US export restriction JDK only ships 128bit version.
                        secret = new SecretKeySpec(payload,0,128/8, ALGORITHM);
                    }
                }
            }
            return secret;
        } catch (IOException e) {
            throw new Error("Failed to load the key: "+getId(),e);
        }
    }

// Vulnerability class: CWE-326
void validSaveRequestImageUploadAndConflictCheck() throws Exception
    {
        when(mockDocument.getRCSVersion()).thenReturn(new Version("1.2"));
        when(mockClonedDocument.getRCSVersion()).thenReturn(new Version("1.2"));
        when(mockClonedDocument.getComment()).thenReturn("My Changes");
        when(mockClonedDocument.getLock(this.context)).thenReturn(mock(XWikiLock.class));
        when(mockForm.getTemplate()).thenReturn("");
        when(this.propertiesConf.getProperty("edit.conflictChecking.enabled")).thenReturn(true);
        when(mockRequest.getParameter("previousVersion")).thenReturn("1.1");
        context.put("ajax", true);
        when(mockRequest.getParameter("forceSave")).thenReturn("");
        when(mockRequest.getParameter("isNew")).thenReturn("true");

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

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

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

    }

// Vulnerability class: CWE-862
function findLateSubscriptionSortedByPriority() {
            if (late_subscriptions.length === 0) {
                return null;
            }
            late_subscriptions.sort(compare_subscriptions);

            // istanbul ignore next
            if (doDebug) {
                debugLog(
                    late_subscriptions
                        .map(
                            (s: Subscription) =>
                                "[ id = " +
                                s.id +
                                " prio=" +
                                s.priority +
                                " t=" +
                                s.timeToExpiration +
                                " ka=" +
                                s.timeToKeepAlive +
                                " m?=" +
                                s.hasUncollectedMonitoredItemNotifications +
                                " " + 
                                SubscriptionState[s.state] +
                                " " + s.messageSent + 
                                "]"
                        )
                        .join(" \n")
                );
            }
            return late_subscriptions[late_subscriptions.length - 1];
        }

// Vulnerability class: CWE-400
final void add(CharSequence name, String... values) {
        final AsciiString normalizedName = normalizeName(name);
        requireNonNull(values, "values");
        final int h = normalizedName.hashCode();
        final int i = index(h);
        for (String v : values) {
            requireNonNullElement(values, v);
            add0(h, i, normalizedName, v);
        }
    }

// Vulnerability class: CWE-74
public boolean isValid(Object value, ConstraintValidatorContext context) {
        final ViolationCollector collector = new ViolationCollector(context);
        context.disableDefaultConstraintViolation();
        for (ValidationCaller caller : methodMap.computeIfAbsent(value.getClass(), this::findMethods)) {
            caller.setValidationObject(value);
            caller.call(collector);
        }
        return !collector.hasViolationOccurred();
    }

// Vulnerability class: CWE-74
public void translate(ServerCloseWindowPacket packet, GeyserSession session) {
        // Sometimes the server can request a window close of ID 0... when the window isn't even open
        // Don't confirm in this instance
        InventoryUtils.closeInventory(session, packet.getWindowId(), (session.getOpenInventory() != null && session.getOpenInventory().getId() == packet.getWindowId()));
    }

// Vulnerability class: CWE-287
public void translate(ServerEntityPropertiesPacket packet, GeyserSession session) {
        Entity entity;
        if (packet.getEntityId() == session.getPlayerEntity().getEntityId()) {
            entity = session.getPlayerEntity();
        } else {
            entity = session.getEntityCache().getEntityByJavaId(packet.getEntityId());
        }
        if (!(entity instanceof LivingEntity)) return;

        ((LivingEntity) entity).updateBedrockAttributes(session, packet.getAttributes());
    }

// Vulnerability class: CWE-287
final void add(CharSequence name, Iterable<String> values) {
        final AsciiString normalizedName = normalizeName(name);
        requireNonNull(values, "values");
        final int h = normalizedName.hashCode();
        final int i = index(h);
        for (String v : values) {
            requireNonNullElement(values, v);
            add0(h, i, normalizedName, v);
        }
    }

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

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

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

            ClientRequestPacket javaRespawnPacket = new ClientRequestPacket(ClientRequest.RESPAWN);
            session.sendDownstreamPacket(javaRespawnPacket);
        }
    }

// Vulnerability class: CWE-287
public void translate(MobEquipmentPacket packet, GeyserSession session) {
        if (!session.isSpawned() || packet.getHotbarSlot() > 8 ||
                packet.getContainerId() != ContainerId.INVENTORY || session.getPlayerInventory().getHeldItemSlot() == packet.getHotbarSlot()) {
            // For the last condition - Don't update the slot if the slot is the same - not Java Edition behavior and messes with plugins such as Grief Prevention
            return;
        }

        // Send book update before switching hotbar slot
        session.getBookEditCache().checkForSend();

        session.getPlayerInventory().setHeldItemSlot(packet.getHotbarSlot());

        ClientPlayerChangeHeldItemPacket changeHeldItemPacket = new ClientPlayerChangeHeldItemPacket(packet.getHotbarSlot());
        session.sendDownstreamPacket(changeHeldItemPacket);

        if (session.isSneaking() && session.getPlayerInventory().getItemInHand().getJavaId() == session.getItemMappings().getStoredItems().shield().getJavaId()) {
            // Activate shield since we are already sneaking
            // (No need to send a release item packet - Java doesn't do this when swapping items)
            // Required to do it a tick later or else it doesn't register
            session.getConnector().getGeneralThreadPool().schedule(() -> session.sendDownstreamPacket(new ClientPlayerUseItemPacket(Hand.MAIN_HAND)),
                    50, TimeUnit.MILLISECONDS);
        }

        // Java sends a cooldown indicator whenever you switch an item
        CooldownUtils.sendCooldown(session);

        // Update the interactive tag, if an entity is present
        if (session.getMouseoverEntity() != null) {
            InteractiveTagManager.updateTag(session, session.getMouseoverEntity());
        }
    }

// Vulnerability class: CWE-287
private Map<String, Argument<?>> initializeTypeParameters(Argument[] genericTypes) {
        Map<String, Argument<?>> typeParameters;
        if (genericTypes != null && genericTypes.length > 0) {
            typeParameters = new LinkedHashMap<>(genericTypes.length);
            for (Argument genericType : genericTypes) {
                typeParameters.put(genericType.getName(), genericType);
            }
        } else {
            typeParameters = Collections.emptyMap();
        }
        return typeParameters;
    }

// Vulnerability class: CWE-400
public void newDocumentWebHomeTopLevelSpaceButTerminalFromURL() throws Exception
    {
        // new document = xwiki:X.WebHome
        DocumentReference documentReference = new DocumentReference("xwiki", Arrays.asList("X"), "WebHome");
        XWikiDocument document = mock(XWikiDocument.class);
        when(document.getDocumentReference()).thenReturn(documentReference);
        when(document.isNew()).thenReturn(true);
        when(document.getLocalReferenceMaxLength()).thenReturn(255);
        context.setDoc(document);

        // Pass the tocreate=terminal request parameter
        when(mockRequest.getParameter("tocreate")).thenReturn("terminal");

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

        // The tests are below this line!

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

        // Note: We can not create the "X" terminal document, since it is already at the top level of the hierarchy and
        // none was able to be deducted from the given information. The user needs to specify more info in order to
        // continue.
        // We should not get this far so no redirect should be done, just the template will be rendered.
        verify(mockURLFactory, never()).createURL(any(), any(), any(), any(), any(),
            any(), any(XWikiContext.class));
    }

// Vulnerability class: CWE-862
public File loadOrDownload(String databaseType, String driverFileUrl) {
        String filePath = driverFilePath(driverBaseDirectory, databaseType);
        Path path = Path.of(filePath);
        if (Files.exists(path)) {
            // ignore
            log.debug("{} already exists, ignore download from {}", filePath, driverFileUrl);
            return path.toFile();
        }
        return this.doDownload(driverFileUrl, filePath);
    }

// Vulnerability class: CWE-20
public void handle(final HttpServletRequest request, final HttpServletResponse response)
      throws Exception
  {
     new ContextualHttpServletRequest(request)
     {
        @Override
        public void process() throws Exception
        {
           ServletContexts.instance().setRequest(request);
           
           if (request.getQueryString() == null)
           {
              throw new ServletException("Invalid request - no component specified");
           }
                     
           Set<Component> components = new HashSet<Component>();
           Set<Type> types = new HashSet<Type>();
           
           response.setContentType("text/javascript");

           Enumeration e = request.getParameterNames();
           while (e.hasMoreElements())
           {
              String componentName = ((String) e.nextElement()).trim();
              
              Component component = Component.forName(componentName);
              if (component == null)
              {                 
                 try
                 {
                    Class c = Reflections.classForName(componentName);
                    appendClassSource(response.getOutputStream(), c, types);
                 }
                 catch (ClassNotFoundException ex)
                 {
                    log.error(String.format("Component not found: [%s]", componentName));
                    throw new ServletException("Invalid request - component not found.");
                 }
              }
              else
              {
                 components.add(component);
              }
           }
           
           generateComponentInterface(components, response.getOutputStream(), types);            
       }
     }.run();
  }

// Vulnerability class: CWE-200
public void translate(ServerEntityMetadataPacket packet, GeyserSession session) {
        Entity entity;
        if (packet.getEntityId() == session.getPlayerEntity().getEntityId()) {
            entity = session.getPlayerEntity();
        } else {
            entity = session.getEntityCache().getEntityByJavaId(packet.getEntityId());
        }
        if (entity == null) return;

        for (EntityMetadata metadata : packet.getMetadata()) {
            try {
                entity.updateBedrockMetadata(metadata, session);
            } catch (ClassCastException e) {
                // Class cast exceptions are really the only ones we're going to get in normal gameplay
                // Because some entity rewriters forget about some values
                // Any other errors are actual bugs
                session.getConnector().getLogger().warning(LanguageUtils.getLocaleStringLog("geyser.network.translator.metadata.failed", metadata, entity.getEntityType()));
                session.getConnector().getLogger().debug("Entity Java ID: " + entity.getEntityId() + ", Geyser ID: " + entity.getGeyserId());
                if (session.getConnector().getConfig().isDebugMode()) {
                    e.printStackTrace();
                }
            }
        }

        entity.updateBedrockMetadata(session);

        // Update the interactive tag, if necessary
        if (session.getMouseoverEntity() != null && session.getMouseoverEntity().getEntityId() == entity.getEntityId()) {
            InteractiveTagManager.updateTag(session, entity);
        }
    }

// Vulnerability class: CWE-287
protected void handleResponse(HttpRequest<?> request, MutableHttpResponse<?> response) {
        HttpHeaders headers = request.getHeaders();
        Optional<String> originHeader = headers.getOrigin();
        originHeader.ifPresent(requestOrigin -> {

            Optional<CorsOriginConfiguration> optionalConfig = getConfiguration(requestOrigin);

            if (optionalConfig.isPresent()) {
                CorsOriginConfiguration config = optionalConfig.get();

                if (CorsUtil.isPreflightRequest(request)) {
                    Optional<HttpMethod> result = headers.getFirst(ACCESS_CONTROL_REQUEST_METHOD, HttpMethod.class);
                    setAllowMethods(result.get(), response);
                    Optional<List> allowedHeaders = headers.get(ACCESS_CONTROL_REQUEST_HEADERS, Argument.of(List.class, String.class));
                    allowedHeaders.ifPresent(val ->
                        setAllowHeaders(val, response)
                    );

                    setMaxAge(config.getMaxAge(), response);
                }

                setOrigin(requestOrigin, response);
                setVary(response);
                setExposeHeaders(config.getExposedHeaders(), response);
                setAllowCredentials(config, response);
            }
        });
    }

// Vulnerability class: CWE-400
private void updateStatus() {
        if (config.getHIDMode() == 0) {
            config.setNetworkStatus(false);
            EditorActivity.stopNetworkSocketService(this);
            ipButton.setVisibility(View.GONE);
            ipStatusDivider.setVisibility(View.GONE);
            if (config.getUSBStatus()) {
                statusText.setText(R.string.config_status_usb_on);
                statusImage.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.ic_usb));
            } else {
                statusText.setText(R.string.config_status_usb_off);
                statusImage.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.ic_usb_off));
            }
        } else if (config.getHIDMode() == 1) {
            EditorActivity.startNetworkSocketService(this);
            ipButton.setVisibility(View.VISIBLE);
            ipStatusDivider.setVisibility(View.VISIBLE);
            if (config.getNetworkStatus()) {
                statusText.setText(R.string.config_status_net_on);
                statusImage.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.ic_net));
            } else {
                statusText.setText(R.string.config_status_net_off);
                statusImage.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.ic_net_off));
            }
            EditorActivity.updateNotification(this);
        }
    }

// Vulnerability class: CWE-327
public String render(TemplateEngineTypeEnum engineType, String templateContent, Map<String, Object> context) {
		if (StrUtil.isEmpty(templateContent)) {
			return StrUtil.EMPTY;
		}
		TemplateEngine templateEngine = templateEngineMap.get(engineType);
		Assert.notNull(templateEngine, "未找到对应的模板引擎：{}", engineType);
		return templateEngine.render(templateContent, context);
	}

// Vulnerability class: CWE-20
public boolean add(MediaPackage sourceMediaPackage, AccessControlList acl, Date now) throws SolrServerException,
          UnauthorizedException {
    try {
      SolrInputDocument episodeDocument = createEpisodeInputDocument(sourceMediaPackage, acl);
      Schema.setOcModified(episodeDocument, now);

      SolrInputDocument seriesDocument = createSeriesInputDocument(sourceMediaPackage.getSeries(), acl);
      if (seriesDocument != null)
        Schema.enrich(episodeDocument, seriesDocument);

      // If neither an episode nor a series was contained, there is no point in trying to update
      if (episodeDocument == null && seriesDocument == null) {
        logger.warn("Neither episode nor series metadata found");
        return false;
      }

      // Post everything to the search index
      if (episodeDocument != null)
        solrServer.add(episodeDocument);
      if (seriesDocument != null)
        solrServer.add(seriesDocument);
      solrServer.commit();
      return true;
    } catch (Exception e) {
      logger.error("Unable to add mediapackage {} to index", sourceMediaPackage.getIdentifier());
      throw new SolrServerException(e);
    }
  }

// Vulnerability class: CWE-863
public JWECryptoParts encrypt(final JWEHeader header, final byte[] clearText)
		throws JOSEException {

		JWEAlgorithm alg = header.getAlgorithm();

		if (! alg.equals(JWEAlgorithm.DIR)) {
			throw new JOSEException(AlgorithmSupportMessage.unsupportedJWEAlgorithm(alg, SUPPORTED_ALGORITHMS));
		}

		// Check key length matches encryption method
		EncryptionMethod enc = header.getEncryptionMethod();

		if (enc.cekBitLength() != ByteUtils.bitLength(getKey().getEncoded())) {
			throw new KeyLengthException(enc.cekBitLength(), enc);
		}

		final Base64URL encryptedKey = null; // The second JWE part

		return ContentCryptoProvider.encrypt(header, clearText, getKey(), encryptedKey, getJCAContext());
	}

// Vulnerability class: CWE-345
public void existingDocumentFromUITemplateProviderSpecifiedTerminal() throws Exception
    {
        // current document = xwiki:Main.WebHome
        DocumentReference documentReference = new DocumentReference("xwiki", Arrays.asList("Main"), "WebHome");
        XWikiDocument document = mock(XWikiDocument.class);
        when(document.getDocumentReference()).thenReturn(documentReference);
        when(document.isNew()).thenReturn(false);
        when(document.getLocalReferenceMaxLength()).thenReturn(255);
        context.setDoc(document);

        // Submit from the UI spaceReference=X&name=Y&templateProvider=XWiki.MyTemplateProvider
        String templateProviderFullName = "XWiki.MyTemplateProvider";
        String spaceReferenceString = "X";
        when(mockRequest.getParameter("spaceReference")).thenReturn(spaceReferenceString);
        when(mockRequest.getParameter("name")).thenReturn("Y");
        when(mockRequest.getParameter("templateprovider")).thenReturn(templateProviderFullName);

        // Mock 1 existing template provider that creates terminal documents.
        mockExistingTemplateProviders(templateProviderFullName,
            new DocumentReference("xwiki", Arrays.asList("XWiki"), "MyTemplateProvider"), Collections.EMPTY_LIST, true);

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

        // The tests are below this line!

        // Verify null is returned (this means the response has been returned)
        assertNull(result);

        // Note: We are creating the document X.Y as terminal and using a template, as specified in the template
        // provider.
        verify(mockURLFactory).createURL("X", "Y", "edit", "template=XWiki.MyTemplate&parent=Main.WebHome&title=Y",
            null, "xwiki", context);
    }

// Vulnerability class: CWE-862
public void newDocumentFromURLWhenNoType() throws Exception
    {
        // No type has been set by the user
        when(mockRequest.get("type")).thenReturn(null);

        // new document = xwiki:X.Y
        DocumentReference documentReference = new DocumentReference("xwiki", Arrays.asList("X"), "Y");
        XWikiDocument document = mock(XWikiDocument.class);
        when(document.getDocumentReference()).thenReturn(documentReference);
        when(document.isNew()).thenReturn(true);
        when(document.getLocalReferenceMaxLength()).thenReturn(255);
        context.setDoc(document);

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

        // The tests are below this line!

        // Verify null is returned (this means the response has been returned)
        assertEquals("create", result);
    }

// Vulnerability class: CWE-862
public void testEqualsInsertionOrderDifferentHeaderNames() {
        final HttpHeadersBase h1 = newEmptyHeaders();
        h1.add("a", "b");
        h1.add("c", "d");
        final HttpHeadersBase h2 = newEmptyHeaders();
        h2.add("c", "d");
        h2.add("a", "b");
        assertThat(h1).isEqualTo(h2);
    }

// Vulnerability class: CWE-74
public void headersWithSameNamesButDifferentValuesShouldNotBeEquivalent() {
        final HttpHeadersBase headers1 = newEmptyHeaders();
        headers1.add("name1", "value1");
        final HttpHeadersBase headers2 = newEmptyHeaders();
        headers1.add("name1", "value2");
        assertThat(headers1).isNotEqualTo(headers2);
    }

// Vulnerability class: CWE-74
public boolean isValid(String value, ConstraintValidatorContext context) {
      if (StringUtils.isEmpty(value)) {
        return true;
      }

      try {
        Pattern.compile(value);
        return true;
      } catch (Exception ex) {
        String errorMessage = String.format("URL parameter '%s' is not a valid regexp", value);
        LOG.warn(errorMessage);

        context.buildConstraintViolationWithTemplate(errorMessage).addConstraintViolation();
      }
      return false;
    }

// Vulnerability class: CWE-74
public void testToString() {
        HttpHeadersBase headers = newEmptyHeaders();
        headers.add("name1", "value1");
        headers.add("name1", "value2");
        headers.add("name2", "value3");
        assertThat(headers.toString()).isEqualTo("[name1=value1, name1=value2, name2=value3]");

        headers = newEmptyHeaders();
        headers.add("name1", "value1");
        headers.add("name2", "value2");
        headers.add("name3", "value3");
        assertThat(headers.toString()).isEqualTo("[name1=value1, name2=value2, name3=value3]");

        headers = newEmptyHeaders();
        headers.add("name1", "value1");
        assertThat(headers.toString()).isEqualTo("[name1=value1]");

        headers = newEmptyHeaders();
        headers.endOfStream(true);
        headers.add("name1", "value1");
        assertThat(headers.toString()).isEqualTo("[EOS, name1=value1]");

        headers = newEmptyHeaders();
        assertThat(headers.toString()).isEqualTo("[]");

        headers = newEmptyHeaders();
        headers.endOfStream(true);
        assertThat(headers.toString()).isEqualTo("[EOS]");
    }

// Vulnerability class: CWE-74
private SearchResult lookupUser(String accountName) throws NamingException {
        InitialDirContext context = initContext();

        String searchString = searchFilter.replace(":login", accountName);

        SearchControls searchControls = new SearchControls();
        String[] attributeFilter = {idAttribute, nameAttribute, mailAttribute};
        searchControls.setReturningAttributes(attributeFilter);
        searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);

        NamingEnumeration<SearchResult> results = context.search(searchBase, searchString, searchControls);

        SearchResult searchResult = null;
        if (results.hasMoreElements()) {
            searchResult = results.nextElement();
            if (results.hasMoreElements()) {
                LOGGER.warn("Matched multiple users for the accountName: " + accountName);
                return null;
            }
        }

        return searchResult;
    }

// Vulnerability class: CWE-74
public void addViolation(String propertyName, String key, String message) {
        violationOccurred = true;
        String messageTemplate = escapeEl(message);
        context.buildConstraintViolationWithTemplate(messageTemplate)
                .addPropertyNode(propertyName)
                .addBeanNode().inIterable().atKey(key)
                .addConstraintViolation();
    }

// Vulnerability class: CWE-74
static DataSource lookupDataSource(Hints hints) throws FactoryException {
        Object hint = hints.get(Hints.EPSG_DATA_SOURCE);
        if (hint instanceof DataSource) {
            return (DataSource) hint;
        } else if (hint instanceof String) {
            String name = (String) hint;
            InitialContext context;
            try {
                context = GeoTools.getInitialContext();
                // name = GeoTools.fixName( context, name );
                return (DataSource) context.lookup(name);
            } catch (Exception e) {
                throw new FactoryException("EPSG_DATA_SOURCE '" + name + "' not found:" + e, e);
            }
        }
        throw new FactoryException("EPSG_DATA_SOURCE must be provided");
    }

// Vulnerability class: CWE-20
public void testEqualsInsertionOrderSameHeaderName() {
        final HttpHeadersBase h1 = newEmptyHeaders();
        h1.add("a", "b");
        h1.add("a", "c");
        final HttpHeadersBase h2 = newEmptyHeaders();
        h2.add("a", "c");
        h2.add("a", "b");
        assertThat(h1).isNotEqualTo(h2);
    }

// Vulnerability class: CWE-74
public void existingDocumentFromUITemplateProviderSpecifiedTerminalOverridenFromUIToNonTerminal() throws Exception
    {
        // current document = xwiki:Main.WebHome
        DocumentReference documentReference = new DocumentReference("xwiki", Arrays.asList("Main"), "WebHome");
        XWikiDocument document = mock(XWikiDocument.class);
        when(document.getDocumentReference()).thenReturn(documentReference);
        when(document.isNew()).thenReturn(false);
        when(document.getLocalReferenceMaxLength()).thenReturn(255);
        context.setDoc(document);

        // Submit from the UI spaceReference=X&name=Y&templateProvider=XWiki.MyTemplateProvider
        String templateProviderFullName = "XWiki.MyTemplateProvider";
        String spaceReferenceString = "X";
        when(mockRequest.getParameter("spaceReference")).thenReturn(spaceReferenceString);
        when(mockRequest.getParameter("name")).thenReturn("Y");
        when(mockRequest.getParameter("templateprovider")).thenReturn(templateProviderFullName);
        when(mockRequest.getParameter("tocreate")).thenReturn("nonterminal");

        // Mock 1 existing template provider that creates terminal documents.
        mockExistingTemplateProviders(templateProviderFullName,
            new DocumentReference("xwiki", Arrays.asList("XWiki"), "MyTemplateProvider"), Collections.EMPTY_LIST, true);

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

        // The tests are below this line!

        // Verify null is returned (this means the response has been returned)
        assertNull(result);

        // Note: We are creating the document X.Y.WebHome as non-terminal, even if the template provider says otherwise.
        // Also using a template, as specified in the template provider.
        verify(mockURLFactory).createURL("X.Y", "WebHome", "edit",
            "template=XWiki.MyTemplate&parent=Main.WebHome&title=Y", null, "xwiki", context);
    }

// Vulnerability class: CWE-862
private List<GHPoint> getPointsFromRequest(HttpServletRequest httpServletRequest, String profile) {

        String url = httpServletRequest.getRequestURI();
        url = url.replaceFirst("/navigate/directions/v5/gh/" + profile + "/", "");
        url = url.replaceAll("\\?[*]", "");

        String[] pointStrings = url.split(";");

        List<GHPoint> points = new ArrayList<>(pointStrings.length);
        for (int i = 0; i < pointStrings.length; i++) {
            points.add(GHPoint.fromStringLonLat(pointStrings[i]));
        }

        return points;
    }

// Vulnerability class: CWE-400
public void translate(ServerEntityPositionPacket packet, GeyserSession session) {
        Entity entity = session.getEntityCache().getEntityByJavaId(packet.getEntityId());
        if (packet.getEntityId() == session.getPlayerEntity().getEntityId()) {
            entity = session.getPlayerEntity();
        }
        if (entity == null) return;

        entity.moveRelative(session, packet.getMoveX(), packet.getMoveY(), packet.getMoveZ(), entity.getRotation(), packet.isOnGround());
    }

// Vulnerability class: CWE-287
public void afterClearHeadersShouldBeEmpty() {
        final HttpHeadersBase headers = newEmptyHeaders();
        headers.add("name1", "value1");
        headers.add("name2", "value2");
        assertThat(headers.size()).isEqualTo(2);
        headers.clear();
        assertThat(headers.size()).isEqualTo(0);
        assertThat(headers.isEmpty()).isTrue();
        assertThat(headers.contains("name1")).isFalse();
        assertThat(headers.contains("name2")).isFalse();
    }

// Vulnerability class: CWE-74
public void existingDocumentNonTerminalFromUIDeprecated() throws Exception
    {
        // current document = xwiki:Main.WebHome
        DocumentReference documentReference = new DocumentReference("xwiki", Arrays.asList("Main"), "WebHome");
        XWikiDocument document = mock(XWikiDocument.class);
        when(document.getDocumentReference()).thenReturn(documentReference);
        when(document.isNew()).thenReturn(false);
        when(document.getLocalReferenceMaxLength()).thenReturn(255);
        context.setDoc(document);

        // Submit from the UI space=X&tocreate=space
        when(mockRequest.getParameter("space")).thenReturn("X");
        when(mockRequest.getParameter("tocreate")).thenReturn("space");

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

        // The tests are below this line!

        // Verify null is returned (this means the response has been returned)
        assertNull(result);

        // Note: We are creating X.WebHome because the tocreate parameter says "space".
        verify(mockURLFactory).createURL("X", "WebHome", "edit", "template=&parent=Main.WebHome&title=X", null, "xwiki",
            context);
    }

// Vulnerability class: CWE-862
public void testAddAndGetUser() throws Exception {
    JpaUser user = createUserWithRoles(org1, "user1", "ROLE_ASTRO_101_SPRING_2011_STUDENT");
    provider.addUser(user);

    User loadUser = provider.loadUser("user1");
    assertNotNull(loadUser);

    assertEquals(user.getUsername(), loadUser.getUsername());
    assertEquals(PasswordEncoder.encode(user.getPassword(), user.getUsername()), loadUser.getPassword());
    assertEquals(user.getOrganization(), loadUser.getOrganization());
    assertEquals(user.getRoles(), loadUser.getRoles());

    assertNull("Loading 'does not exist' should return null", provider.loadUser("does not exist"));
    assertNull("Loading 'does not exist' should return null", provider.loadUser("user1", org2.getId()));

    loadUser = provider.loadUser("user1", org1.getId());
    assertNotNull(loadUser);

    assertEquals(user.getUsername(), loadUser.getUsername());
    assertEquals(PasswordEncoder.encode(user.getPassword(), user.getUsername()), loadUser.getPassword());
    assertEquals(user.getOrganization(), loadUser.getOrganization());
    assertEquals(user.getRoles(), loadUser.getRoles());
  }

// Vulnerability class: CWE-327
protected OHttpSessionManager() {
     expirationTime = OGlobalConfiguration.NETWORK_HTTP_SESSION_EXPIRE_TIMEOUT.getValueAsInteger() * 1000;

     Orient.instance().scheduleTask(new TimerTask() {
       @Override
       public void run() {
         final int expired = checkSessionsValidity();
         if (expired > 0)
           OLogManager.instance().debug(this, "Removed %d session because expired", expired);
       }
     }, expirationTime, expirationTime);
   }

// Vulnerability class: CWE-200
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;
        }
    }

// Vulnerability class: CWE-20
private String templatePath() {
        if (templatePath == null) {
            String file = HgCommand.class.getResource("/hg.template").getFile();
            try {
                templatePath = URLDecoder.decode(new File(file).getAbsolutePath(), "UTF-8");
            } catch (UnsupportedEncodingException e) {
                templatePath = URLDecoder.decode(new File(file).getAbsolutePath());
            }
        }
        return templatePath;
    }

// Vulnerability class: CWE-77
default Argument<?> getErrorType(MediaType mediaType) {
        if (mediaType.equals(MediaType.APPLICATION_JSON_TYPE)) {
            return Argument.of(JsonError.class);
        } else if (mediaType.equals(MediaType.APPLICATION_VND_ERROR_TYPE)) {
            return Argument.of(VndError.class);
        } else {
            return Argument.of(String.class);
        }
    }

// Vulnerability class: CWE-400
public void translate(ServerPluginMessagePacket packet, GeyserSession session) {
        // The only plugin messages it has to listen for are Floodgate plugin messages
        if (session.getRemoteAuthType() != AuthType.FLOODGATE) {
            return;
        }

        String channel = packet.getChannel();

        if (channel.equals("floodgate:form")) {
            byte[] data = packet.getData();

            // receive: first byte is form type, second and third are the id, remaining is the form data
            // respond: first and second byte id, remaining is form response data

            FormType type = FormType.getByOrdinal(data[0]);
            if (type == null) {
                throw new NullPointerException(
                        "Got type " + data[0] + " which isn't a valid form type!");
            }

            String dataString = new String(data, 3, data.length - 3, Charsets.UTF_8);

            Form form = Forms.fromJson(dataString, type);
            form.setResponseHandler(response -> {
                byte[] raw = response.getBytes(StandardCharsets.UTF_8);
                byte[] finalData = new byte[raw.length + 2];

                finalData[0] = data[1];
                finalData[1] = data[2];
                System.arraycopy(raw, 0, finalData, 2, raw.length);

                session.sendDownstreamPacket(new ClientPluginMessagePacket(channel, finalData));
            });
            session.sendForm(form);
        }
    }

// Vulnerability class: CWE-287
private boolean isAdmin(String accountName) {
        if (this.adminFilter != null) {
            try {
                InitialDirContext context = initContext();
                String searchString = adminFilter.replace(":login", accountName);
                SearchControls searchControls = new SearchControls();
                searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
                NamingEnumeration<SearchResult> results = context.search(searchBase, searchString, searchControls);
                if (results.hasMoreElements()) {
                    results.nextElement();
                    if (results.hasMoreElements()) {
                        LOGGER.warn("Matched multiple users for the accountName: " + accountName);
                        return false;
                    }
                    return true;
                }
            } catch (NamingException e) {
                return false;
            }
        }
        return false;
    }

// Vulnerability class: CWE-74