mcanoglu/cwe-class-group huggingface dataset:
public void translate(EmotePacket packet, GeyserSession session) {
        if (session.getConnector().getConfig().getEmoteOffhandWorkaround() != EmoteOffhandWorkaroundOption.DISABLED) {
            // Activate the workaround - we should trigger the offhand now
            ClientPlayerActionPacket swapHandsPacket = new ClientPlayerActionPacket(PlayerAction.SWAP_HANDS, BlockUtils.POSITION_ZERO,
                    BlockFace.DOWN);
            session.sendDownstreamPacket(swapHandsPacket);

            if (session.getConnector().getConfig().getEmoteOffhandWorkaround() == EmoteOffhandWorkaroundOption.NO_EMOTES) {
                return;
            }
        }

        long javaId = session.getPlayerEntity().getEntityId();
        for (GeyserSession otherSession : session.getConnector().getPlayers()) {
            if (otherSession != session) {
                if (otherSession.isClosed()) continue;
                if (otherSession.getEventLoop().inEventLoop()) {
                    playEmote(otherSession, javaId, packet.getEmoteId());
                } else {
                    session.executeInEventLoop(() -> playEmote(otherSession, javaId, packet.getEmoteId()));
                }
            }
        }
    }

// Vulnerability class: CWE-287
public void validateConcreteScmMaterial(ValidationContext validationContext) {
        if (getView() == null || getView().trim().isEmpty()) {
            errors.add(VIEW, "P4 view cannot be empty.");
        }
        if (StringUtils.isBlank(getServerAndPort())) {
            errors.add(SERVER_AND_PORT, "P4 port cannot be empty.");
        }
        validateEncryptedPassword();
    }

// Vulnerability class: CWE-77
public boolean matches(ConditionContext context) {
        BeanContext beanContext = context.getBeanContext();
        if (beanContext instanceof ApplicationContext) {
            List<String> paths = ((ApplicationContext) beanContext)
                    .getEnvironment()
                    .getProperty(FileWatchConfiguration.PATHS, Argument.listOf(String.class))
                    .orElse(null);

            if (CollectionUtils.isNotEmpty(paths)) {


                boolean matchedPaths = paths.stream().anyMatch(p -> new File(p).exists());
                if (!matchedPaths) {
                    context.fail("File watch disabled because no paths matching the watch pattern exist (Paths: " + paths + ")");
                }
                return matchedPaths;
            }
        }

        context.fail("File watch disabled because no watch paths specified");
        return false;
    }

// Vulnerability class: CWE-400
private String doResolveSqlDriverNameFromJar(File driverFile) {
        JarFile jarFile = null;
        try {
            jarFile = new JarFile(driverFile);
        } catch (IOException e) {
            log.error("resolve driver class name error", e);
            throw DomainErrors.DRIVER_CLASS_NAME_OBTAIN_ERROR.exception(e.getMessage());
        }

        final JarFile driverJar = jarFile;
        String driverClassName = jarFile.stream()
                .filter(entry -> entry.getName().contains("META-INF/services/java.sql.Driver"))
                .findFirst()
                .map(entry -> {
                    InputStream stream = null;
                    BufferedReader reader = null;
                    try {
                        stream = driverJar.getInputStream(entry);
                        reader = new BufferedReader(new InputStreamReader(stream));
                        return reader.readLine();
                    } catch (IOException e) {
                        log.error("resolve driver class name error", e);
                        throw DomainErrors.DRIVER_CLASS_NAME_OBTAIN_ERROR.exception(e.getMessage());
                    } finally {
                        IOUtils.closeQuietly(reader, ex -> log.error("close reader error", ex));
                    }
                })
                .orElseThrow(DomainErrors.DRIVER_CLASS_NAME_OBTAIN_ERROR::exception);
        IOUtils.closeQuietly(jarFile, ex -> log.error("close jar file error", ex));
        return driverClassName;
    }

// Vulnerability class: CWE-20
public void translate(MapInfoRequestPacket packet, GeyserSession session) {
        long mapId = packet.getUniqueMapId();

        ClientboundMapItemDataPacket mapPacket = session.getStoredMaps().remove(mapId);
        if (mapPacket != null) {
            // Delay the packet 100ms to prevent the client from ignoring the packet
            GeyserConnector.getInstance().getGeneralThreadPool().schedule(() -> session.sendUpstreamPacket(mapPacket),
                    100, TimeUnit.MILLISECONDS);
        }
    }

// Vulnerability class: CWE-287
public void translate(BlockPickRequestPacket packet, GeyserSession session) {
        Vector3i vector = packet.getBlockPosition();
        int blockToPick = session.getConnector().getWorldManager().getBlockAt(session, vector.getX(), vector.getY(), vector.getZ());
        
        // Block is air - chunk caching is probably off
        if (blockToPick == BlockStateValues.JAVA_AIR_ID) {
            // Check for an item frame since the client thinks that's a block when it's an entity in Java
            ItemFrameEntity entity = ItemFrameEntity.getItemFrameEntity(session, packet.getBlockPosition());
            if (entity != null) {
                // Check to see if the item frame has an item in it first
                if (entity.getHeldItem() != null && entity.getHeldItem().getId() != 0) {
                    // Grab the item in the frame
                    InventoryUtils.findOrCreateItem(session, entity.getHeldItem());
                } else {
                    // Grab the frame as the item
                    InventoryUtils.findOrCreateItem(session, entity.getEntityType() == EntityType.GLOW_ITEM_FRAME ? "minecraft:glow_item_frame" : "minecraft:item_frame");
                }
            }
            return;
        }

        InventoryUtils.findOrCreateItem(session, BlockRegistries.JAVA_BLOCKS.get(blockToPick).getPickItem());
    }

// Vulnerability class: CWE-287
public void translate(ServerStopSoundPacket packet, GeyserSession session) {
        // Runs if all sounds are stopped
        if (packet.getSound() == null) {
            StopSoundPacket stopPacket = new StopSoundPacket();
            stopPacket.setStoppingAllSound(true);
            stopPacket.setSoundName("");
            session.sendUpstreamPacket(stopPacket);
            return;
        }

        String packetSound;
        if (packet.getSound() instanceof BuiltinSound) {
            packetSound = ((BuiltinSound) packet.getSound()).getName();
        } else if (packet.getSound() instanceof CustomSound) {
            packetSound = ((CustomSound) packet.getSound()).getName();
        } else {
            session.getConnector().getLogger().debug("Unknown sound packet, we were unable to map this. " + packet.toString());
            return;
        }
        SoundMapping soundMapping = Registries.SOUNDS.get(packetSound.replace("minecraft:", ""));
        session.getConnector().getLogger()
                .debug("[StopSound] Sound mapping " + packetSound + " -> "
                        + soundMapping + (soundMapping == null ? "[not found]" : "")
                        + " - " + packet.toString());
        String playsound;
        if (soundMapping == null || soundMapping.getPlaysound() == null) {
            // no mapping
            session.getConnector().getLogger()
                    .debug("[StopSound] Defaulting to sound server gave us.");
            playsound = packetSound;
        } else {
            playsound = soundMapping.getPlaysound();
        }

        StopSoundPacket stopSoundPacket = new StopSoundPacket();
        stopSoundPacket.setSoundName(playsound);
        // packet not mapped in the library
        stopSoundPacket.setStoppingAllSound(false);

        session.sendUpstreamPacket(stopSoundPacket);
        session.getConnector().getLogger().debug("[StopSound] Packet sent - " + packet.toString() + " --> " + stopSoundPacket);
    }

// Vulnerability class: CWE-287
public void existingDocumentNonTerminalFromUIDeprecatedCheckEscaping() 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.Y&tocreate=space
        when(mockRequest.getParameter("space")).thenReturn("X.Y");
        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);

        // Note1: The space parameter was previously considered as space name, not space reference, so it is escaped.
        // Note2: We are creating X\.Y.WebHome because the tocreate parameter says "space".
        verify(mockURLFactory).createURL("X\\.Y", "WebHome", "edit", "template=&parent=Main.WebHome&title=X.Y", null,
            "xwiki", context);
    }

// Vulnerability class: CWE-862
public String getEncryptedValue() {
        try {
            Cipher cipher = KEY.encrypt();
            // add the magic suffix which works like a check sum.
            return new String(Base64.encode(cipher.doFinal((value+MAGIC).getBytes("UTF-8"))));
        } catch (GeneralSecurityException e) {
            throw new Error(e); // impossible
        } catch (UnsupportedEncodingException e) {
            throw new Error(e); // impossible
        }
    }

// Vulnerability class: CWE-326
private void initAndSaveDocument(XWikiContext context, XWikiDocument newDocument, String title, String template,
        String parent) throws XWikiException
    {
        XWiki xwiki = context.getWiki();

        // Set the locale and default locale, considering that we're creating the original version of the document
        // (not a translation).
        newDocument.setLocale(Locale.ROOT);
        if (newDocument.getDefaultLocale() == Locale.ROOT) {
            newDocument.setDefaultLocale(xwiki.getLocalePreference(context));
        }

        // Copy the template.
        readFromTemplate(newDocument, template, context);

        // Set the parent field.
        if (!StringUtils.isEmpty(parent)) {
            DocumentReference parentReference = this.currentmixedReferenceResolver.resolve(parent);
            newDocument.setParentReference(parentReference);
        }

        // Set the document title
        if (title != null) {
            newDocument.setTitle(title);
        }

        // Set the author and creator.
        DocumentReference currentUserReference = context.getUserReference();
        newDocument.setAuthorReference(currentUserReference);
        newDocument.setCreatorReference(currentUserReference);

        // Make sure the user is allowed to make this modification
        xwiki.checkSavingDocument(currentUserReference, newDocument, context);

        xwiki.saveDocument(newDocument, context);
    }

// Vulnerability class: CWE-862
public void translate(ServerSetActionBarTextPacket packet, GeyserSession session) {
        String text;
        if (packet.getText() == null) { //TODO 1.17 can this happen?
            text = " ";
        } else {
            text = MessageTranslator.convertMessage(packet.getText(), session.getLocale());
        }

        SetTitlePacket titlePacket = new SetTitlePacket();
        titlePacket.setType(SetTitlePacket.Type.ACTIONBAR);
        titlePacket.setText(text);
        titlePacket.setXuid("");
        titlePacket.setPlatformOnlineId("");
        session.sendUpstreamPacket(titlePacket);
    }

// Vulnerability class: CWE-287
public void testGetAndRemove() {
        final HttpHeadersBase headers = newEmptyHeaders();
        headers.add("name1", "value1");
        headers.add("name2", "value2", "value3");
        headers.add("name3", "value4", "value5", "value6");

        assertThat(headers.getAndRemove("name1", "defaultvalue")).isEqualTo("value1");
        assertThat(headers.getAndRemove("name2")).isEqualTo("value2");
        assertThat(headers.getAndRemove("name2")).isNull();
        assertThat(headers.getAllAndRemove("name3")).containsExactly("value4", "value5", "value6");
        assertThat(headers.size()).isZero();
        assertThat(headers.getAndRemove("noname")).isNull();
        assertThat(headers.getAndRemove("noname", "defaultvalue")).isEqualTo("defaultvalue");
    }

// Vulnerability class: CWE-74
public void newDocumentWebHomeButTerminalFromURL() throws Exception
    {
        // new document = xwiki:X.Y.WebHome
        DocumentReference documentReference = new DocumentReference("xwiki", Arrays.asList("X", "Y"), "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 null is returned (this means the response has been returned)
        assertNull(result);

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

// Vulnerability class: CWE-862
public void translate(FilterTextPacket packet, GeyserSession session) {
        if (session.getOpenInventory() instanceof CartographyContainer) {
            // We don't want to be able to rename in the cartography table
            return;
        }
        packet.setFromServer(true);
        session.sendUpstreamPacket(packet);

        if (session.getOpenInventory() instanceof AnvilContainer) {
            // Java Edition sends a packet every time an item is renamed even slightly in GUI. Fortunately, this works out for us now
            ClientRenameItemPacket renameItemPacket = new ClientRenameItemPacket(packet.getText());
            session.sendDownstreamPacket(renameItemPacket);
        }
    }

// Vulnerability class: CWE-287
private <P extends T> void translate0(GeyserSession session, PacketTranslator<P> translator, P packet) {
        if (session.isClosed()) {
            return;
        }

        try {
            translator.translate(packet, session);
        } catch (Throwable ex) {
            GeyserConnector.getInstance().getLogger().error(LanguageUtils.getLocaleStringLog("geyser.network.translator.packet.failed", packet.getClass().getSimpleName()), ex);
            ex.printStackTrace();
        }
    }

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

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

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

        // The tests are below this line!

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

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

        // We should not get this far so no redirect should be done, just the template will be rendered.
        verify(mockURLFactory, never()).createURL(any(), any(), any(), any(), any(),
            any(), any(XWikiContext.class));
    }

// Vulnerability class: CWE-862
private CallbackHandler getCallbackHandler(
      @UnderInitialization(WrappedFactory.class) LibPQFactory this,
      Properties info) throws PSQLException {
    // Determine the callback handler
    CallbackHandler cbh;
    String sslpasswordcallback = PGProperty.SSL_PASSWORD_CALLBACK.get(info);
    if (sslpasswordcallback != null) {
      try {
        cbh = (CallbackHandler) ObjectFactory.instantiate(sslpasswordcallback, info, false, null);
      } catch (Exception e) {
        throw new PSQLException(
          GT.tr("The password callback class provided {0} could not be instantiated.",
            sslpasswordcallback),
          PSQLState.CONNECTION_FAILURE, e);
      }
    } else {
      cbh = new ConsoleCallbackHandler(PGProperty.SSL_PASSWORD.get(info));
    }
    return cbh;
  }

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

// Vulnerability class: CWE-287
public static boolean isPermitted(
      final Optional<AuthenticationService> authenticationService,
      final Optional<User> optionalUser,
      final JsonRpcMethod jsonRpcMethod) {

    AtomicBoolean foundMatchingPermission = new AtomicBoolean();

    if (authenticationService.isPresent()) {
      if (optionalUser.isPresent()) {
        User user = optionalUser.get();
        for (String perm : jsonRpcMethod.getPermissions()) {
          user.isAuthorized(
              perm,
              (authed) -> {
                if (authed.result()) {
                  LOG.trace(
                      "user {} authorized : {} via permission {}",
                      user,
                      jsonRpcMethod.getName(),
                      perm);
                  foundMatchingPermission.set(true);
                }
              });
        }
      }
    } else {
      // no auth provider configured thus anything is permitted
      foundMatchingPermission.set(true);
    }

    if (!foundMatchingPermission.get()) {
      LOG.trace("user NOT authorized : {}", jsonRpcMethod.getName());
    }
    return foundMatchingPermission.get();
  }

// Vulnerability class: CWE-400
public void shouldNotGetModificationsFromOtherBranches() throws Exception {
        makeACommitToSecondBranch();
        hg(workingDirectory, "pull").runOrBomb(null);

        List<Modification> actual = hgCommand.modificationsSince(new StringRevision(REVISION_0));
        assertThat(actual.size(), is(2));
        assertThat(actual.get(0).getRevision(), is(REVISION_2));
        assertThat(actual.get(1).getRevision(), is(REVISION_1));
    }

// Vulnerability class: CWE-77
public void translate(ServerScoreboardObjectivePacket packet, GeyserSession session) {
        WorldCache worldCache = session.getWorldCache();
        Scoreboard scoreboard = worldCache.getScoreboard();
        Objective objective = scoreboard.getObjective(packet.getName());
        int pps = worldCache.increaseAndGetScoreboardPacketsPerSecond();

        if (objective == null && packet.getAction() != ObjectiveAction.REMOVE) {
            objective = scoreboard.registerNewObjective(packet.getName(), false);
        }

        switch (packet.getAction()) {
            case ADD:
            case UPDATE:
                objective.setDisplayName(MessageTranslator.convertMessage(packet.getDisplayName()))
                        .setType(packet.getType().ordinal());
                break;
            case REMOVE:
                scoreboard.unregisterObjective(packet.getName());
                break;
        }

        if (objective == null || !objective.isActive()) {
            return;
        }

        // ScoreboardUpdater will handle it for us if the packets per second
        // (for score and team packets) is higher then the first threshold
        if (pps < ScoreboardUpdater.FIRST_SCORE_PACKETS_PER_SECOND_THRESHOLD) {
            scoreboard.onUpdate();
        }
    }

// Vulnerability class: CWE-287
public void translate(ServerKeepAlivePacket packet, GeyserSession session) {
        if (!session.getConnector().getConfig().isForwardPlayerPing()) {
            return;
        }
        NetworkStackLatencyPacket latencyPacket = new NetworkStackLatencyPacket();
        latencyPacket.setFromServer(true);
        latencyPacket.setTimestamp(packet.getPingId() * 1000);
        session.sendUpstreamPacket(latencyPacket);
    }

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

// Vulnerability class: CWE-287
public void newDocumentWebHomeTopLevelFromURL() 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);

        // 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: The title is not "WebHome", but "X" (the space's name) to avoid exposing "WebHome" in the UI.
        verify(mockURLFactory).createURL("X", "WebHome", "edit", "template=&parent=Main.WebHome&title=X", null, "xwiki",
            context);
    }

// Vulnerability class: CWE-862
public void addShouldIncreaseAndRemoveShouldDecreaseTheSize() {
        final HttpHeadersBase headers = newEmptyHeaders();
        assertThat(headers.size()).isEqualTo(0);
        headers.add("name1", "value1", "value2");
        assertThat(headers.size()).isEqualTo(2);
        headers.add("name2", "value3", "value4");
        assertThat(headers.size()).isEqualTo(4);
        headers.add("name3", "value5");
        assertThat(headers.size()).isEqualTo(5);

        headers.remove("name3");
        assertThat(headers.size()).isEqualTo(4);
        headers.remove("name1");
        assertThat(headers.size()).isEqualTo(2);
        headers.remove("name2");
        assertThat(headers.size()).isEqualTo(0);
        assertThat(headers.isEmpty()).isTrue();
    }

// Vulnerability class: CWE-74
public User updateUser(JpaUser user) throws NotFoundException, UnauthorizedException {
    if (!UserDirectoryUtils.isCurrentUserAuthorizedHandleRoles(securityService, user.getRoles()))
      throw new UnauthorizedException("The user is not allowed to set the admin role on other users");

    JpaUser updateUser = UserDirectoryPersistenceUtil.findUser(user.getUsername(), user.getOrganization().getId(), emf);
    if (updateUser == null) {
      throw new NotFoundException("User " + user.getUsername() + " not found.");
    }

    logger.debug("updateUser({})", user.getUsername());

    if (!UserDirectoryUtils.isCurrentUserAuthorizedHandleRoles(securityService, updateUser.getRoles()))
      throw new UnauthorizedException("The user is not allowed to update an admin user");

    String encodedPassword;
    //only update Password if a value is set
    if (StringUtils.isEmpty(user.getPassword())) {
      encodedPassword = updateUser.getPassword();
    } else  {
      // Update an JPA user with an encoded password.
      encodedPassword = PasswordEncoder.encode(user.getPassword(), user.getUsername());
    }

    // Only save internal roles
    Set<JpaRole> roles = UserDirectoryPersistenceUtil.saveRoles(filterRoles(user.getRoles()), emf);
    JpaOrganization organization = UserDirectoryPersistenceUtil.saveOrganization(
            (JpaOrganization) user.getOrganization(), emf);

    JpaUser updatedUser = UserDirectoryPersistenceUtil.saveUser(
            new JpaUser(user.getUsername(), encodedPassword, organization, user.getName(), user.getEmail(), user
                    .getProvider(), true, roles), emf);
    cache.put(user.getUsername() + DELIMITER + organization.getId(), updatedUser);

    updateGroupMembership(user);

    return updatedUser;
  }

// Vulnerability class: CWE-327
public void translate(AdventureSettingsPacket packet, GeyserSession session) {
        boolean isFlying = packet.getSettings().contains(AdventureSetting.FLYING);
        if (!isFlying && session.getGameMode() == GameMode.SPECTATOR) {
            // We should always be flying in spectator mode
            session.sendAdventureSettings();
            return;
        }

        session.setFlying(isFlying);
        ClientPlayerAbilitiesPacket abilitiesPacket = new ClientPlayerAbilitiesPacket(isFlying);
        session.sendDownstreamPacket(abilitiesPacket);

        if (isFlying && session.getPlayerEntity().getMetadata().getFlags().getFlag(EntityFlag.SWIMMING)) {
            // Bedrock can fly and swim at the same time? Make sure that can't happen
            session.setSwimming(false);
        }
    }

// Vulnerability class: CWE-287
public void multipleValuesPerNameShouldBeAllowed() {
        final HttpHeadersBase headers = newEmptyHeaders();
        headers.add("name", "value1");
        headers.add("name", "value2");
        headers.add("name", "value3");
        assertThat(headers.size()).isEqualTo(3);

        final List<String> values = headers.getAll("name");
        assertThat(values).hasSize(3)
                          .containsExactly("value1", "value2", "value3");
    }

// Vulnerability class: CWE-74
public void testContains() {
        final HttpHeadersBase headers = newEmptyHeaders();

        headers.addLong("long", Long.MAX_VALUE);
        assertThat(headers.containsLong("long", Long.MAX_VALUE)).isTrue();
        assertThat(headers.containsLong("long", Long.MIN_VALUE)).isFalse();

        headers.addInt("int", Integer.MIN_VALUE);
        assertThat(headers.containsInt("int", Integer.MIN_VALUE)).isTrue();
        assertThat(headers.containsInt("int", Integer.MAX_VALUE)).isFalse();

        headers.addDouble("double", Double.MAX_VALUE);
        assertThat(headers.containsDouble("double", Double.MAX_VALUE)).isTrue();
        assertThat(headers.containsDouble("double", Double.MIN_VALUE)).isFalse();

        headers.addFloat("float", Float.MAX_VALUE);
        assertThat(headers.containsFloat("float", Float.MAX_VALUE)).isTrue();
        assertThat(headers.containsFloat("float", Float.MIN_VALUE)).isFalse();

        final long millis = System.currentTimeMillis();
        headers.addTimeMillis("millis", millis);
        assertThat(headers.containsTimeMillis("millis", millis)).isTrue();
        // This test doesn't work on midnight, January 1, 1970 UTC
        assertThat(headers.containsTimeMillis("millis", 0)).isFalse();

        headers.addObject("object", "Hello World");
        assertThat(headers.containsObject("object", "Hello World")).isTrue();
        assertThat(headers.containsObject("object", "")).isFalse();

        headers.add("name", "value");
        assertThat(headers.contains("name", "value")).isTrue();
        assertThat(headers.contains("name", "value1")).isFalse();
    }

// Vulnerability class: CWE-74
public void translate(ServerSetSlotPacket packet, GeyserSession session) {
        if (packet.getWindowId() == 255) { //cursor
            GeyserItemStack newItem = GeyserItemStack.from(packet.getItem());
            session.getPlayerInventory().setCursor(newItem, session);
            InventoryUtils.updateCursor(session);
            return;
        }

        //TODO: support window id -2, should update player inventory
        Inventory inventory = InventoryUtils.getInventory(session, packet.getWindowId());
        if (inventory == null)
            return;

        inventory.setStateId(packet.getStateId());

        InventoryTranslator translator = session.getInventoryTranslator();
        if (translator != null) {
            if (session.getCraftingGridFuture() != null) {
                session.getCraftingGridFuture().cancel(false);
            }
            session.setCraftingGridFuture(session.scheduleInEventLoop(() -> updateCraftingGrid(session, packet, inventory, translator), 150, TimeUnit.MILLISECONDS));

            GeyserItemStack newItem = GeyserItemStack.from(packet.getItem());
            if (packet.getWindowId() == 0 && !(translator instanceof PlayerInventoryTranslator)) {
                // In rare cases, the window ID can still be 0 but Java treats it as valid
                session.getPlayerInventory().setItem(packet.getSlot(), newItem, session);
                InventoryTranslator.PLAYER_INVENTORY_TRANSLATOR.updateSlot(session, session.getPlayerInventory(), packet.getSlot());
            } else {
                inventory.setItem(packet.getSlot(), newItem, session);
                translator.updateSlot(session, inventory, packet.getSlot());
            }
        }
    }

// Vulnerability class: CWE-287
public void getWithDefaultValueWorks() {
        final HttpHeadersBase headers = newEmptyHeaders();
        headers.add("name1", "value1");

        assertThat(headers.get("name1", "defaultvalue")).isEqualTo("value1");
        assertThat(headers.get("noname", "defaultvalue")).isEqualTo("defaultvalue");
    }

// Vulnerability class: CWE-74
public void newDocumentButNonTerminalFromURL() throws Exception
    {
        // 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);

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

        // 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);

        verify(mockURLFactory).createURL("X.Y", "WebHome", "edit", "template=&parent=Main.WebHome&title=Y", null,
            "xwiki", context);
    }

// Vulnerability class: CWE-862
public void checkConnection(UrlArgument repoUrl) {
        final String ref = fullUpstreamRef();
        final CommandLine commandLine = git().withArgs("ls-remote").withArg(repoUrl).withArg(ref);
        final ConsoleResult result = commandLine.runOrBomb(new NamedProcessTag(repoUrl.forDisplay()));

        if (!hasExactlyOneMatchingBranch(result)) {
            throw new CommandLineException(format("The ref %s could not be found.", ref));
        }
    }

// Vulnerability class: CWE-77
public void existingDocumentFromUITemplateSpecified() 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&template=XWiki.MyTemplate
        String templateDocumentFullName = "XWiki.MyTemplate";
        DocumentReference templateDocumentReference =
            new DocumentReference("MyTemplate", Arrays.asList("XWiki"), "xwiki");
        when(mockRequest.getParameter("spaceReference")).thenReturn("X");
        when(mockRequest.getParameter("name")).thenReturn("Y");
        when(mockRequest.getParameter("template")).thenReturn("XWiki.MyTemplate");

        // Mock the passed template document as existing.
        mockTemplateDocumentExisting(templateDocumentFullName, templateDocumentReference);

        // 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.Y.WebHome and using the template specified in the request.
        verify(mockURLFactory).createURL("X.Y", "WebHome", "edit",
            "template=XWiki.MyTemplate&parent=Main.WebHome&title=Y", null, "xwiki", context);
    }

// Vulnerability class: CWE-862
public void translate(MoveEntityAbsolutePacket packet, GeyserSession session) {
        session.setLastVehicleMoveTimestamp(System.currentTimeMillis());

        float y = packet.getPosition().getY();
        if (session.getRidingVehicleEntity() instanceof BoatEntity) {
            // Remove the offset to prevents boats from looking like they're floating in water
            y -= EntityType.BOAT.getOffset();
        }
        ClientVehicleMovePacket clientVehicleMovePacket = new ClientVehicleMovePacket(
                packet.getPosition().getX(), y, packet.getPosition().getZ(),
                packet.getRotation().getY() - 90, packet.getRotation().getX()
        );
        session.sendDownstreamPacket(clientVehicleMovePacket);
    }

// Vulnerability class: CWE-287
public void iteratorSetShouldFail() {
        final HttpHeadersBase headers = newEmptyHeaders();
        headers.add("name1", "value1", "value2", "value3");
        headers.add("name2", "value4");
        assertThat(headers.size()).isEqualTo(4);

        assertThatThrownBy(() -> headers.iterator().next().setValue(""))
                .isInstanceOf(UnsupportedOperationException.class);
    }

// Vulnerability class: CWE-74
public void translate(AnimatePacket packet, GeyserSession session) {
        // Stop the player sending animations before they have fully spawned into the server
        if (!session.isSpawned()) {
            return;
        }

        switch (packet.getAction()) {
            case SWING_ARM:
                // Delay so entity damage can be processed first
                session.scheduleInEventLoop(() ->
                        session.sendDownstreamPacket(new ClientPlayerSwingArmPacket(Hand.MAIN_HAND)),
                        25,
                        TimeUnit.MILLISECONDS
                );
                break;
            // These two might need to be flipped, but my recommendation is getting moving working first
            case ROW_LEFT:
                // Packet value is a float of how long one has been rowing, so we convert that into a boolean
                session.setSteeringLeft(packet.getRowingTime() > 0.0);
                ClientSteerBoatPacket steerLeftPacket = new ClientSteerBoatPacket(session.isSteeringLeft(), session.isSteeringRight());
                session.sendDownstreamPacket(steerLeftPacket);
                break;
            case ROW_RIGHT:
                session.setSteeringRight(packet.getRowingTime() > 0.0);
                ClientSteerBoatPacket steerRightPacket = new ClientSteerBoatPacket(session.isSteeringLeft(), session.isSteeringRight());
                session.sendDownstreamPacket(steerRightPacket);
                break;
        }
    }

// Vulnerability class: CWE-287
private DefaultHttpClient makeHttpClient() {

    DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
    try {
      logger.debug("Installing forgiving hostname verifier and trust managers");
      X509TrustManager trustManager = createTrustManager();
      X509HostnameVerifier hostNameVerifier = createHostNameVerifier();
      SSLContext sslContext = SSLContext.getInstance("TLS");
      sslContext.init(null, new TrustManager[] { trustManager }, new SecureRandom());
      SSLSocketFactory ssf = new SSLSocketFactory(sslContext, hostNameVerifier);
      ClientConnectionManager ccm = defaultHttpClient.getConnectionManager();
      SchemeRegistry sr = ccm.getSchemeRegistry();
      sr.register(new Scheme("https", 443, ssf));
    } catch (NoSuchAlgorithmException e) {
      logger.error("Error creating context to handle TLS connections: {}", e.getMessage());
    } catch (KeyManagementException e) {
      logger.error("Error creating context to handle TLS connections: {}", e.getMessage());
    }

    return defaultHttpClient;
  }

// Vulnerability class: CWE-346
public Map<String, FileEntry> generatorCode(TableDetails tableDetails, String tablePrefix,
			Map<String, String> customProperties, List<TemplateFile> templateFiles) {

		Map<String, FileEntry> map = new HashMap<>(templateFiles.size());

		// 模板渲染
		Map<String, Object> context = GenUtils.getContext(tableDetails, tablePrefix, customProperties);

		for (TemplateFile templateFile : templateFiles) {
			FileEntry fileEntry = new FileEntry();
			fileEntry.setType(templateFile.getType());

			// 替换路径中的占位符
			String filename = StrUtil.format(templateFile.getFilename(), context);
			fileEntry.setFilename(filename);

			String parentFilePath = GenUtils.evaluateRealPath(templateFile.getParentFilePath(), context);
			fileEntry.setParentFilePath(parentFilePath);

			// 如果是文件
			if (TemplateEntryTypeEnum.FILE.getType().equals(fileEntry.getType())) {
				fileEntry.setFilePath(GenUtils.concatFilePath(parentFilePath, filename));
				// 文件内容渲染
				TemplateEngineTypeEnum engineTypeEnum = TemplateEngineTypeEnum.of(templateFile.getEngineType());
				String content = templateEngineDelegator.render(engineTypeEnum, templateFile.getContent(), context);
				fileEntry.setContent(content);
			}
			else {
				String currentPath = GenUtils.evaluateRealPath(templateFile.getFilename(), context);
				fileEntry.setFilePath(GenUtils.concatFilePath(parentFilePath, currentPath));
			}

			map.put(fileEntry.getFilePath(), fileEntry);
		}

		return map;
	}

// Vulnerability class: CWE-20
/*package*/ static Secret tryDecrypt(Cipher cipher, byte[] in) throws UnsupportedEncodingException {
        try {
            String plainText = new String(cipher.doFinal(in), "UTF-8");
            if(plainText.endsWith(MAGIC))
                return new Secret(plainText.substring(0,plainText.length()-MAGIC.length()));
            return null;
        } catch (GeneralSecurityException e) {
            return null; // if the key doesn't match with the bytes, it can result in BadPaddingException
        }
    }

// Vulnerability class: CWE-326
public void translate(ShowCreditsPacket packet, GeyserSession session) {
        if (packet.getStatus() == ShowCreditsPacket.Status.END_CREDITS) {
            ClientRequestPacket javaRespawnPacket = new ClientRequestPacket(ClientRequest.RESPAWN);
            session.sendDownstreamPacket(javaRespawnPacket);
        }
    }

// Vulnerability class: CWE-287
int bmp_validate(jas_stream_t *in)
{
	int n;
	int i;
	uchar buf[2];

	assert(JAS_STREAM_MAXPUTBACK >= 2);

	/* Read the first two characters that constitute the signature. */
	if ((n = jas_stream_read(in, (char *) buf, 2)) < 0) {
		return -1;
	}
	/* Put the characters read back onto the stream. */
	for (i = n - 1; i >= 0; --i) {
		if (jas_stream_ungetc(in, buf[i]) == EOF) {
			return -1;
		}
	}
	/* Did we read enough characters? */
	if (n < 2) {
		return -1;
	}
	/* Is the signature correct for the BMP format? */
	if (buf[0] == (BMP_MAGIC & 0xff) && buf[1] == (BMP_MAGIC >> 8)) {
		return 0;
	}
	return -1;
}

// Vulnerability class: CWE-20
void HeaderMapImpl::insertByKey(HeaderString&& key, HeaderString&& value) {
  EntryCb cb = ConstSingleton<StaticLookupTable>::get().find(key.getStringView());
  if (cb) {
    key.clear();
    StaticLookupResponse ref_lookup_response = cb(*this);
    if (*ref_lookup_response.entry_ == nullptr) {
      maybeCreateInline(ref_lookup_response.entry_, *ref_lookup_response.key_, std::move(value));
    } else {
      appendToHeader((*ref_lookup_response.entry_)->value(), value.getStringView());
      value.clear();
    }
  } else {
    std::list<HeaderEntryImpl>::iterator i = headers_.insert(std::move(key), std::move(value));
    i->entry_ = i;
  }
}

// Vulnerability class: CWE-400
void UTFstring::UpdateFromUTF8()
{
  delete [] _Data;
  // find the size of the final UCS-2 string
  size_t i;
  for (_Length=0, i=0; i<UTF8string.length(); _Length++) {
    uint8 lead = static_cast<uint8>(UTF8string[i]);
    if (lead < 0x80)
      i++;
    else if ((lead >> 5) == 0x6)
      i += 2;
    else if ((lead >> 4) == 0xe)
      i += 3;
    else if ((lead >> 3) == 0x1e)
      i += 4;
    else
      // Invalid size?
      break;
  }
  _Data = new wchar_t[_Length+1];
  size_t j;
  for (j=0, i=0; i<UTF8string.length(); j++) {
    uint8 lead = static_cast<uint8>(UTF8string[i]);
    if (lead < 0x80) {
      _Data[j] = lead;
      i++;
    } else if ((lead >> 5) == 0x6) {
      _Data[j] = ((lead & 0x1F) << 6) + (UTF8string[i+1] & 0x3F);
      i += 2;
    } else if ((lead >> 4) == 0xe) {
      _Data[j] = ((lead & 0x0F) << 12) + ((UTF8string[i+1] & 0x3F) << 6) + (UTF8string[i+2] & 0x3F);
      i += 3;
    } else if ((lead >> 3) == 0x1e) {
      _Data[j] = ((lead & 0x07) << 18) + ((UTF8string[i+1] & 0x3F) << 12) + ((UTF8string[i+2] & 0x3F) << 6) + (UTF8string[i+3] & 0x3F);
      i += 4;
    } else
      // Invalid char?
      break;
  }
  _Data[j] = 0;
}

// Vulnerability class: CWE-200
void RemoteFsDevice::load()
{
    if (RemoteFsDevice::constSambaAvahiProtocol==details.url.scheme()) {
        // Start Avahi listener...
        Avahi::self();
        QUrlQuery q(details.url);
        if (q.hasQueryItem(constServiceNameQuery)) {
            details.serviceName=q.queryItemValue(constServiceNameQuery);
        }

        if (!details.serviceName.isEmpty()) {
            AvahiService *srv=Avahi::self()->getService(details.serviceName);
            if (!srv || srv->getHost().isEmpty()) {
                sub=tr("Not Available");
            } else {
                sub=tr("Available");
            }
        }
        connect(Avahi::self(), SIGNAL(serviceAdded(QString)), SLOT(serviceAdded(QString)));
        connect(Avahi::self(), SIGNAL(serviceRemoved(QString)), SLOT(serviceRemoved(QString)));
    }

    if (isConnected()) {
        setAudioFolder();
        readOpts(settingsFileName(), opts, true);
        rescan(false); // Read from cache if we have it!
    }
}

// Vulnerability class: CWE-20
ECDSA_PrivateKey::create_signature_op(RandomNumberGenerator& /*rng*/,
                                      const std::string& params,
                                      const std::string& provider) const
   {
#if defined(BOTAN_HAS_BEARSSL)
   if(provider == "bearssl" || provider.empty())
      {
      try
         {
         return make_bearssl_ecdsa_sig_op(*this, params);
         }
      catch(Lookup_Error& e)
         {
         if(provider == "bearssl")
            throw;
         }
      }
#endif

#if defined(BOTAN_HAS_OPENSSL)
   if(provider == "openssl" || provider.empty())
      {
      try
         {
         return make_openssl_ecdsa_sig_op(*this, params);
         }
      catch(Lookup_Error& e)
         {
         if(provider == "openssl")
            throw;
         }
      }
#endif

   if(provider == "base" || provider.empty())
      return std::unique_ptr<PK_Ops::Signature>(new ECDSA_Signature_Operation(*this, params));

   throw Provider_Not_Found(algo_name(), provider);
   }

// Vulnerability class: CWE-200
RemoteDevicePropertiesWidget::RemoteDevicePropertiesWidget(QWidget *parent)
    : QWidget(parent)
    , modified(false)
    , saveable(false)
{
    setupUi(this);
    if (qobject_cast<QTabWidget *>(parent)) {
        verticalLayout->setMargin(4);
    }
    type->addItem(tr("Samba Share"), (int)Type_Samba);
    type->addItem(tr("Samba Share (Auto-discover host and port)"), (int)Type_SambaAvahi);
    type->addItem(tr("Secure Shell (sshfs)"), (int)Type_SshFs);
    type->addItem(tr("Locally Mounted Folder"), (int)Type_File);
}

// Vulnerability class: CWE-20
int CephxSessionHandler::_calc_signature(Message *m, uint64_t *psig)
{
  const ceph_msg_header& header = m->get_header();
  const ceph_msg_footer& footer = m->get_footer();

  // optimized signature calculation
  // - avoid temporary allocated buffers from encode_encrypt[_enc_bl]
  // - skip the leading 4 byte wrapper from encode_encrypt
  struct {
    __u8 v;
    __le64 magic;
    __le32 len;
    __le32 header_crc;
    __le32 front_crc;
    __le32 middle_crc;
    __le32 data_crc;
  } __attribute__ ((packed)) sigblock = {
    1, mswab(AUTH_ENC_MAGIC), mswab<uint32_t>(4*4),
    mswab<uint32_t>(header.crc), mswab<uint32_t>(footer.front_crc),
    mswab<uint32_t>(footer.middle_crc), mswab<uint32_t>(footer.data_crc)
  };

  char exp_buf[CryptoKey::get_max_outbuf_size(sizeof(sigblock))];

  try {
    const CryptoKey::in_slice_t in {
      sizeof(sigblock),
      reinterpret_cast<const unsigned char*>(&sigblock)
    };
    const CryptoKey::out_slice_t out {
      sizeof(exp_buf),
      reinterpret_cast<unsigned char*>(&exp_buf)
    };

    key.encrypt(cct, in, out);
  } catch (std::exception& e) {
    lderr(cct) << __func__ << " failed to encrypt signature block" << dendl;
    return -1;
  }

  *psig = *reinterpret_cast<__le64*>(exp_buf);

  ldout(cct, 10) << __func__ << " seq " << m->get_seq()
		 << " front_crc_ = " << footer.front_crc
		 << " middle_crc = " << footer.middle_crc
		 << " data_crc = " << footer.data_crc
		 << " sig = " << *psig
		 << dendl;
  return 0;
}

// Vulnerability class: CWE-287