mcanoglu/cwe-class-group huggingface dataset:
public void translate(ServerPlaySoundPacket packet, GeyserSession session) {
        String packetSound;
        if (packet.getSound() instanceof BuiltinSound) {
            packetSound = ((BuiltinSound) packet.getSound()).getName();
        } else if (packet.getSound() instanceof CustomSound) {
            packetSound = ((CustomSound) packet.getSound()).getName();
        } else {
            session.getConnector().getLogger().debug("Unknown sound packet, we were unable to map this. " + packet.toString());
            return;
        }

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

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

        session.sendUpstreamPacket(playSoundPacket);
    }

// Vulnerability class: CWE-287
void setConfigAttributes_shouldUpdatePasswordWhenPasswordChangedBooleanChanged() throws Exception {
        P4MaterialConfig materialConfig = p4("", "");
        materialConfig.setPassword("notSecret");
        Map<String, String> map = new HashMap<>();
        map.put(P4MaterialConfig.PASSWORD, "secret");
        map.put(P4MaterialConfig.PASSWORD_CHANGED, "1");

        materialConfig.setConfigAttributes(map);
        assertThat(ReflectionUtil.getField(materialConfig, "password")).isNull();
        assertThat(materialConfig.getPassword()).isEqualTo("secret");
        assertThat(materialConfig.getEncryptedPassword()).isEqualTo(new GoCipher().encrypt("secret"));

        //Dont change
        map.put(SvnMaterialConfig.PASSWORD, "Hehehe");
        map.put(SvnMaterialConfig.PASSWORD_CHANGED, "0");
        materialConfig.setConfigAttributes(map);

        assertThat(ReflectionUtil.getField(materialConfig, "password")).isNull();
        assertThat(materialConfig.getPassword()).isEqualTo("secret");
        assertThat(materialConfig.getEncryptedPassword()).isEqualTo(new GoCipher().encrypt("secret"));

        //Dont change
        map.put(SvnMaterialConfig.PASSWORD, "");
        map.put(SvnMaterialConfig.PASSWORD_CHANGED, "1");
        materialConfig.setConfigAttributes(map);

        assertThat(materialConfig.getPassword()).isNull();
        assertThat(materialConfig.getEncryptedPassword()).isNull();
    }

// Vulnerability class: CWE-77
public List<Modification> modificationsSince(Revision revision) {
        InMemoryStreamConsumer consumer = inMemoryConsumer();
        bombUnless(pull(consumer), "Failed to run hg pull command: " + consumer.getAllOutput());
        CommandLine hg = hg("log",
                "-r", "tip:" + revision.getRevision(),
                "-b", branch,
                "--style", templatePath());
        return new HgModificationSplitter(execute(hg)).filterOutRevision(revision);
    }

// Vulnerability class: CWE-77
final void set(CharSequence name, 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 testNotThrowWhenConvertFails() {
        final HttpHeadersBase headers = newEmptyHeaders();
        headers.set("name1", "");
        assertThat(headers.getInt("name1")).isNull();
        assertThat(headers.getInt("name1", 1)).isEqualTo(1);

        assertThat(headers.getDouble("name")).isNull();
        assertThat(headers.getDouble("name1", 1)).isEqualTo(1);

        assertThat(headers.getFloat("name")).isNull();
        assertThat(headers.getFloat("name1", Float.MAX_VALUE)).isEqualTo(Float.MAX_VALUE);

        assertThat(headers.getLong("name")).isNull();
        assertThat(headers.getLong("name1", Long.MAX_VALUE)).isEqualTo(Long.MAX_VALUE);

        assertThat(headers.getTimeMillis("name")).isNull();
        assertThat(headers.getTimeMillis("name1", Long.MAX_VALUE)).isEqualTo(Long.MAX_VALUE);
    }

// Vulnerability class: CWE-74
private static void checkCEKLength(final SecretKey cek, final EncryptionMethod enc)
		throws KeyLengthException {

		if (enc.cekBitLength() != ByteUtils.bitLength(cek.getEncoded())) {
			throw new KeyLengthException("The Content Encryption Key (CEK) length for " + enc + " must be " + enc.cekBitLength() + " bits");
		}
	}

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

        MobEffectPacket mobEffectPacket = new MobEffectPacket();
        mobEffectPacket.setEvent(MobEffectPacket.Event.REMOVE);
        mobEffectPacket.setRuntimeEntityId(entity.getGeyserId());
        mobEffectPacket.setEffectId(EntityUtils.toBedrockEffectId(packet.getEffect()));
        session.sendUpstreamPacket(mobEffectPacket);
    }

// Vulnerability class: CWE-287
public void handle(String target, HttpServletRequest request, HttpServletResponse response, boolean[] isHandled) {
        //便于Wappalyzer读取
        response.addHeader("X-ZrLog", BlogBuildInfoUtil.getVersion());
        boolean isPluginPath = false;
        for (String path : pluginHandlerPaths) {
            if (target.startsWith(path)) {
                isPluginPath = true;
            }
        }
        if (isPluginPath) {
            try {
                Map.Entry<AdminTokenVO, User> entry = adminTokenService.getAdminTokenVOUserEntry(request);
                if (entry != null) {
                    adminTokenService.setAdminToken(entry.getValue(), entry.getKey().getSessionId(), entry.getKey().getProtocol(), request, response);
                }
                if (target.startsWith("/admin/plugins/")) {
                    try {
                        adminPermission(target, request, response);
                    } catch (IOException | InstantiationException e) {
                        LOGGER.error(e);
                    }
                } else if (target.startsWith("/plugin/") || target.startsWith("/p/")) {
                    try {
                        visitorPermission(target, request, response);
                    } catch (IOException | InstantiationException e) {
                        LOGGER.error(e);
                    }
                }
            } finally {
                isHandled[0] = true;
            }
        } else {
            this.next.handle(target, request, response, isHandled);
        }
    }

// Vulnerability class: CWE-863
protected DocumentReference resolveTemplate(String template)
    {
        if (StringUtils.isNotBlank(template)) {
            DocumentReference templateReference = this.currentmixedReferenceResolver.resolve(template);

            // Make sure the current user have access to the template document before copying it
            if (this.autorization.hasAccess(Right.VIEW, templateReference)) {
                return templateReference;
            }
        }

        return null;
    }

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

        entity.updateRotation(session, packet.getYaw(), packet.getPitch(), packet.isOnGround());
    }

// Vulnerability class: CWE-287
public void translate(ServerUpdateScorePacket packet, GeyserSession session) {
        WorldCache worldCache = session.getWorldCache();
        Scoreboard scoreboard = worldCache.getScoreboard();
        int pps = worldCache.increaseAndGetScoreboardPacketsPerSecond();

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

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

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

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

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

// Vulnerability class: CWE-862
public void testContainsNameAndValue() {
        final HttpHeadersBase headers = newHttp2Headers();
        assertThat(headers.contains("name1", "value2")).isTrue();
        assertThat(headers.contains("name1", "Value2")).isFalse();
        assertThat(headers.contains("name2", "value3")).isTrue();
        assertThat(headers.contains("name2", "Value3")).isFalse();
    }

// Vulnerability class: CWE-74
public void existingDocumentFromUITemplateProviderExistingButNoneSelected() 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
        when(mockRequest.getParameter("spaceReference")).thenReturn("X");
        when(mockRequest.getParameter("name")).thenReturn("Y");

        // Mock 1 existing template provider
        mockExistingTemplateProviders("XWiki.MyTemplateProvider",
            new DocumentReference("xwiki", Arrays.asList("XWiki"), "MyTemplateProvider"), Collections.EMPTY_LIST);

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

        // 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 void newDocumentFromURL() 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);

        // 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", "edit", "template=&parent=Main.WebHome&title=Y", null, "xwiki",
            context);
    }

// Vulnerability class: CWE-862
public void annotatedSubClassExample() throws Exception {
        assertThat(ConstraintViolations.format(validator.validate(new AnnotatedSubclassExample())))
            .containsExactlyInAnyOrder(
                    FAILED_RESULT,
                    FAILED_RESULT+"subclass"
            );
        assertThat(TestLoggerFactory.getAllLoggingEvents())
            .isEmpty();
    }

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

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

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

// Vulnerability class: CWE-74
public String findFilter( String url_suffix )
    {
        if( url_suffix == null )
        {
            throw new IllegalArgumentException( "The url_suffix must not be null." );
        }
        
        CaptureType type = em.find( CaptureType.class, url_suffix );
        
        if( type != null )
        {
            return type.getCaptureFilter();
        }
        
        return null;
    }

// Vulnerability class: CWE-754
public void translate(ServerEntityEffectPacket packet, GeyserSession session) {
        Entity entity;
        if (packet.getEntityId() == session.getPlayerEntity().getEntityId()) {
            entity = session.getPlayerEntity();
            session.getEffectCache().setEffect(packet.getEffect(), packet.getAmplifier());
        } else {
            entity = session.getEntityCache().getEntityByJavaId(packet.getEntityId());
        }
        if (entity == null)
            return;

        MobEffectPacket mobEffectPacket = new MobEffectPacket();
        mobEffectPacket.setAmplifier(packet.getAmplifier());
        mobEffectPacket.setDuration(packet.getDuration());
        mobEffectPacket.setEvent(MobEffectPacket.Event.ADD);
        mobEffectPacket.setRuntimeEntityId(entity.getGeyserId());
        mobEffectPacket.setParticles(packet.isShowParticles());
        mobEffectPacket.setEffectId(EntityUtils.toBedrockEffectId(packet.getEffect()));
        session.sendUpstreamPacket(mobEffectPacket);
    }

// Vulnerability class: CWE-287
public void translate(ServerBossBarPacket packet, GeyserSession session) {
        BossBar bossBar = session.getEntityCache().getBossBar(packet.getUuid());
        switch (packet.getAction()) {
            case ADD:
                long entityId = session.getEntityCache().getNextEntityId().incrementAndGet();
                bossBar = new BossBar(session, entityId, packet.getTitle(), packet.getHealth(), 0, 1, 0);
                session.getEntityCache().addBossBar(packet.getUuid(), bossBar);
                break;
            case UPDATE_TITLE:
                if (bossBar != null) bossBar.updateTitle(packet.getTitle());
                break;
            case UPDATE_HEALTH:
                if (bossBar != null) bossBar.updateHealth(packet.getHealth());
                break;
            case REMOVE:
                session.getEntityCache().removeBossBar(packet.getUuid());
                break;
            case UPDATE_STYLE:
            case UPDATE_FLAGS:
                //todo
        }
    }

// Vulnerability class: CWE-287
void setup()
    {
        this.saveAction = new SaveAction();

        context = oldcore.getXWikiContext();

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

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

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

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

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

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

        context.setUserReference(USER_REFERENCE);
    }

// Vulnerability class: CWE-862
private void processExtras(Bundle extras) {
        final String downloadUuid = extras.getString(ConversationsActivity.EXTRA_DOWNLOAD_UUID);
        final String text = extras.getString(Intent.EXTRA_TEXT);
        final String nick = extras.getString(ConversationsActivity.EXTRA_NICK);
        final boolean asQuote = extras.getBoolean(ConversationsActivity.EXTRA_AS_QUOTE);
        final boolean pm = extras.getBoolean(ConversationsActivity.EXTRA_IS_PRIVATE_MESSAGE, false);
        final List<Uri> uris = extractUris(extras);
        if (uris != null && uris.size() > 0) {
            final List<Uri> cleanedUris = cleanUris(new ArrayList<>(uris));
            mediaPreviewAdapter.addMediaPreviews(Attachment.of(getActivity(), cleanedUris));
            toggleInputMethod();
            return;
        }
        if (nick != null) {
            if (pm) {
                Jid jid = conversation.getJid();
                try {
                    Jid next = Jid.of(jid.getLocal(), jid.getDomain(), nick);
                    privateMessageWith(next);
                } catch (final IllegalArgumentException ignored) {
                    //do nothing
                }
            } else {
                final MucOptions mucOptions = conversation.getMucOptions();
                if (mucOptions.participating() || conversation.getNextCounterpart() != null) {
                    highlightInConference(nick);
                }
            }
        } else {
            if (text != null && asQuote) {
                quoteText(text);
            } else {
                appendText(text);
            }
        }
        final Message message = downloadUuid == null ? null : conversation.findMessageWithFileAndUuid(downloadUuid);
        if (message != null) {
            startDownloadable(message);
        }
    }

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

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

        // Just landed on the create page or submitted with no values (no name) specified.

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

        // 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 Element handle(Element request, Map<String, Object> context) throws ServiceException {
        ZimbraSoapContext zsc = getZimbraSoapContext(context);
        Account account = getRequestedAccount(getZimbraSoapContext(context));

        if (!canAccessAccount(zsc, account))
            throw ServiceException.PERM_DENIED("can not access account");
        
        String name = request.getAttribute(AccountConstants.E_NAME);
        String typeStr = request.getAttribute(AccountConstants.A_TYPE, "account");
        GalSearchType type = GalSearchType.fromString(typeStr);

        boolean needCanExpand = request.getAttributeBool(AccountConstants.A_NEED_EXP, false);

        String galAcctId = request.getAttribute(AccountConstants.A_GAL_ACCOUNT_ID, null);
        
        GalSearchParams params = new GalSearchParams(account, zsc);
        params.setType(type);
        params.setRequest(request);
        params.setQuery(name);
        params.setLimit(account.getContactAutoCompleteMaxResults());
        params.setNeedCanExpand(needCanExpand);
        params.setResponseName(AccountConstants.AUTO_COMPLETE_GAL_RESPONSE);
        if (galAcctId != null)
            params.setGalSyncAccount(Provisioning.getInstance().getAccountById(galAcctId));
        GalSearchControl gal = new GalSearchControl(params);
        gal.autocomplete();
        return params.getResultCallback().getResponse();
    }

// Vulnerability class: CWE-862
public void testUpdateUser() throws Exception {
    Set<JpaRole> authorities = new HashSet<JpaRole>();
    authorities.add(new JpaRole("ROLE_ASTRO_101_SPRING_2011_STUDENT", org1));

    JpaUser user = new JpaUser("user1", "pass1", org1, provider.getName(), true, authorities);
    provider.addUser(user);

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

    assertNotNull(loadUser);

    authorities.add(new JpaRole("ROLE_ASTRO_101_SPRING_2013_STUDENT", org1));
    String newPassword = "newPassword";
    JpaUser updateUser = new JpaUser(user.getUsername(), newPassword, org1, provider.getName(), true, authorities);

    User loadUpdatedUser = provider.updateUser(updateUser);
    // User loadUpdatedUser = provider.loadUser(user.getUsername());

    assertNotNull(loadUpdatedUser);
    assertEquals(user.getUsername(), loadUpdatedUser.getUsername());
    assertEquals(PasswordEncoder.encode(newPassword, user.getUsername()), loadUpdatedUser.getPassword());
    assertEquals(authorities.size(), loadUpdatedUser.getRoles().size());

    updateUser = new JpaUser("unknown", newPassword, org1, provider.getName(), true, authorities);

    try {
      provider.updateUser(updateUser);
      fail("Should throw a NotFoundException");
    } catch (NotFoundException e) {
      assertTrue("User not found.", true);
    }

  }

// Vulnerability class: CWE-327
public void translate(ServerSpawnLivingEntityPacket packet, GeyserSession session) {
        Vector3f position = Vector3f.from(packet.getX(), packet.getY(), packet.getZ());
        Vector3f motion = Vector3f.from(packet.getMotionX(), packet.getMotionY(), packet.getMotionZ());
        Vector3f rotation = Vector3f.from(packet.getYaw(), packet.getPitch(), packet.getHeadYaw());

        EntityType type = EntityUtils.toBedrockEntity(packet.getType());
        if (type == null) {
            session.getConnector().getLogger().warning(LanguageUtils.getLocaleStringLog("geyser.entity.type_null", packet.getType()));
            return;
        }

        Class<? extends Entity> entityClass = type.getEntityClass();
        try {
            Constructor<? extends Entity> entityConstructor = entityClass.getConstructor(long.class, long.class, EntityType.class,
                    Vector3f.class, Vector3f.class, Vector3f.class);

            Entity entity = entityConstructor.newInstance(packet.getEntityId(), session.getEntityCache().getNextEntityId().incrementAndGet(),
                    type, position, motion, rotation
            );
            session.getEntityCache().spawnEntity(entity);
        } catch (NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException ex) {
            ex.printStackTrace();
        }
    }

// Vulnerability class: CWE-287
public static <T> T withPassword(AuthenticationRequestType type, Properties info,
      PasswordAction<char @Nullable [], T> action) throws PSQLException, IOException {
    char[] password = null;

    String authPluginClassName = PGProperty.AUTHENTICATION_PLUGIN_CLASS_NAME.get(info);

    if (authPluginClassName == null || authPluginClassName.equals("")) {
      // Default auth plugin simply pulls password directly from connection properties
      String passwordText = PGProperty.PASSWORD.get(info);
      if (passwordText != null) {
        password = passwordText.toCharArray();
      }
    } else {
      AuthenticationPlugin authPlugin;
      try {
        authPlugin = (AuthenticationPlugin) ObjectFactory.instantiate(authPluginClassName, info,
            false, null);
      } catch (Exception ex) {
        LOGGER.log(Level.FINE, "Unable to load Authentication Plugin " + ex.toString());
        throw new PSQLException(ex.getMessage(), PSQLState.UNEXPECTED_ERROR);
      }

      password = authPlugin.getPassword(type);
    }

    try {
      return action.apply(password);
    } finally {
      if (password != null) {
        java.util.Arrays.fill(password, (char) 0);
      }
    }
  }

// Vulnerability class: CWE-665
public void submoduleAdd(String repoUrl, String submoduleNameToPutInGitSubmodules, String folder) {
        String[] addSubmoduleWithSameNameArgs = new String[]{"submodule", "add", repoUrl, folder};
        String[] changeSubmoduleNameInGitModules = new String[]{"config", "--file", ".gitmodules", "--rename-section", "submodule." + folder, "submodule." + submoduleNameToPutInGitSubmodules};
        String[] addGitModules = new String[]{"add", ".gitmodules"};

        runOrBomb(gitWd().withArgs(addSubmoduleWithSameNameArgs));
        runOrBomb(gitWd().withArgs(changeSubmoduleNameInGitModules));
        runOrBomb(gitWd().withArgs(addGitModules));
    }

// Vulnerability class: CWE-77
private Job startCreateJob(EntityReference entityReference, EditForm editForm) throws XWikiException
    {
        if (StringUtils.isBlank(editForm.getTemplate())) {
            // No template specified, nothing more to do.
            return null;
        }

        // If a template is set in the request, then this is a create action which needs to be handled by a create job,
        // but skipping the target document, which is now already saved by the save action.

        RefactoringScriptService refactoring =
            (RefactoringScriptService) Utils.getComponent(ScriptService.class, "refactoring");

        CreateRequest request = refactoring.getRequestFactory().createCreateRequest(Arrays.asList(entityReference));
        request.setCheckAuthorRights(false);
        // Set the target document.
        request.setEntityReferences(Arrays.asList(entityReference));
        // Set the template to use.
        DocumentReferenceResolver<String> resolver =
            Utils.getComponent(DocumentReferenceResolver.TYPE_STRING, "currentmixed");
        EntityReference templateReference = resolver.resolve(editForm.getTemplate());
        request.setTemplateReference(templateReference);
        // We`ve already created and populated the fields of the target document, focus only on the remaining children
        // specified in the template.
        request.setSkippedEntities(Arrays.asList(entityReference));

        Job createJob = refactoring.create(request);
        if (createJob != null) {
            return createJob;
        } else {
            throw new XWikiException(String.format("Failed to schedule the create job for [%s]", entityReference),
                refactoring.getLastError());
        }
    }

// Vulnerability class: CWE-862
public void setShouldOverWritePreviousValue() {
        final HttpHeadersBase headers = newEmptyHeaders();
        headers.set("name", "value1");
        headers.set("name", "value2");
        assertThat(headers.size()).isEqualTo(1);
        assertThat(headers.getAll("name").size()).isEqualTo(1);
        assertThat(headers.getAll("name").get(0)).isEqualTo("value2");
        assertThat(headers.get("name")).isEqualTo("value2");
    }

// Vulnerability class: CWE-74
public int checkSessionsValidity() {
     int expired = 0;

     acquireExclusiveLock();
     try {
       final long now = System.currentTimeMillis();

       Entry<String, OHttpSession> s;
       for (Iterator<Map.Entry<String, OHttpSession>> it = sessions.entrySet().iterator(); it.hasNext();) {
         s = it.next();

         if (now - s.getValue().getUpdatedOn() > expirationTime) {
           // REMOVE THE SESSION
           it.remove();
           expired++;
         }
       }

     } finally {
       releaseExclusiveLock();
     }

     return expired;
   }

// Vulnerability class: CWE-200
public void translate(ServerUpdateTimePacket packet, GeyserSession session) {
        // Bedrock sends a GameRulesChangedPacket if there is no daylight cycle
        // Java just sends a negative long if there is no daylight cycle
        long time = packet.getTime();

        // https://minecraft.gamepedia.com/Day-night_cycle#24-hour_Minecraft_day
        SetTimePacket setTimePacket = new SetTimePacket();
        setTimePacket.setTime((int) Math.abs(time) % 24000);
        session.sendUpstreamPacket(setTimePacket);
        if (!session.isDaylightCycle() && time >= 0) {
            // Client thinks there is no daylight cycle but there is
            session.setDaylightCycle(true);
        } else if (session.isDaylightCycle() && time < 0) {
            // Client thinks there is daylight cycle but there isn't
            session.setDaylightCycle(false);
        }
    }

// Vulnerability class: CWE-287
public void translate(ServerWindowPropertyPacket packet, GeyserSession session) {
        Inventory inventory = InventoryUtils.getInventory(session, packet.getWindowId());
        if (inventory == null)
            return;

        InventoryTranslator translator = session.getInventoryTranslator();
        if (translator != null) {
            translator.updateProperty(session, inventory, packet.getRawProperty(), packet.getValue());
        }
    }

// Vulnerability class: CWE-287
protected DataSource createDataSource(Map<String, ?> params, SQLDialect dialect)
            throws IOException {
        String jndiName = (String) JNDI_REFNAME.lookUp(params);
        if (jndiName == null) throw new IOException("Missing " + JNDI_REFNAME.description);

        Context ctx = null;
        DataSource ds = null;

        try {
            ctx = GeoTools.getInitialContext();
        } catch (NamingException e) {
            throw new RuntimeException(e);
        }

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

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

// Vulnerability class: CWE-20
public void iteratorShouldReturnAllNameValuePairs() {
        final HttpHeadersBase headers1 = newEmptyHeaders();
        headers1.add("name1", "value1", "value2");
        headers1.add("name2", "value3");
        headers1.add("name3", "value4", "value5", "value6");
        headers1.add("name1", "value7", "value8");
        assertThat(headers1.size()).isEqualTo(8);

        final HttpHeadersBase headers2 = newEmptyHeaders();
        for (Map.Entry<AsciiString, String> entry : headers1) {
            headers2.add(entry.getKey(), entry.getValue());
        }

        assertThat(headers2).isEqualTo(headers1);
    }

// Vulnerability class: CWE-74
protected BigInteger chooseRandomPrime(int bitlength, BigInteger e, BigInteger sqrdBound)
    {
        int iterations = getNumberOfIterations(bitlength, param.getCertainty());

        for (int i = 0; i != 5 * bitlength; i++)
        {
            BigInteger p = new BigInteger(bitlength, 1, param.getRandom());

            if (p.mod(e).equals(ONE))
            {
                continue;
            }

            if (p.multiply(p).compareTo(sqrdBound) < 0)
            {
                continue;
            }

            if (!isProbablePrime(p, iterations))
            {
                continue;
            }

            if (!e.gcd(p.subtract(ONE)).equals(ONE))
            {
                continue;
            }

            return p;
        }

        throw new IllegalStateException("unable to generate prime number for RSA key");
    }

// Vulnerability class: CWE-327
public void setAllShouldOverwriteSomeAndLeaveOthersUntouched() {
        final HttpHeadersBase h1 = newEmptyHeaders();

        h1.add("name1", "value1");
        h1.add("name2", "value2");
        h1.add("name2", "value3");
        h1.add("name3", "value4");

        final HttpHeadersBase h2 = newEmptyHeaders();
        h2.add("name1", "value5");
        h2.add("name2", "value6");
        h2.add("name1", "value7");

        final HttpHeadersBase expected = newEmptyHeaders();
        expected.add("name1", "value5");
        expected.add("name2", "value6");
        expected.add("name1", "value7");
        expected.add("name3", "value4");

        h1.set(h2);

        assertThat(h1).isEqualTo(expected);
    }

// Vulnerability class: CWE-74
public String createSession(final String iDatabaseName, final String iUserName, final String iUserPassword) {
     acquireExclusiveLock();
     try {
       final String id = "OS" + System.currentTimeMillis() + random.nextLong();
       sessions.put(id, new OHttpSession(id, iDatabaseName, iUserName, iUserPassword));
       return id;

     } finally {
       releaseExclusiveLock();
     }
   }

// Vulnerability class: CWE-200
protected void showCreateContactDialog(final String prefilledJid, final Invite invite) {
		FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
		Fragment prev = getSupportFragmentManager().findFragmentByTag(FRAGMENT_TAG_DIALOG);
		if (prev != null) {
			ft.remove(prev);
		}
		ft.addToBackStack(null);
		EnterJidDialog dialog = EnterJidDialog.newInstance(
				mActivatedAccounts,
				getString(R.string.dialog_title_create_contact),
				getString(R.string.create),
				prefilledJid,
				null,
				invite == null || !invite.hasFingerprints()
		);

		dialog.setOnEnterJidDialogPositiveListener((accountJid, contactJid) -> {
			if (!xmppConnectionServiceBound) {
				return false;
			}

			final Account account = xmppConnectionService.findAccountByJid(accountJid);
			if (account == null) {
				return true;
			}

			final Contact contact = account.getRoster().getContact(contactJid);
			if (invite != null && invite.getName() != null) {
				contact.setServerName(invite.getName());
			}
			if (contact.isSelf()) {
				switchToConversation(contact, null);
				return true;
			} else if (contact.showInRoster()) {
				throw new EnterJidDialog.JidError(getString(R.string.contact_already_exists));
			} else {
				xmppConnectionService.createContact(contact, true);
				if (invite != null && invite.hasFingerprints()) {
					xmppConnectionService.verifyFingerprints(contact, invite.getFingerprints());
				}
				switchToConversation(contact, invite == null ? null : invite.getBody());
				return true;
			}
		});
		dialog.show(ft, FRAGMENT_TAG_DIALOG);
	}

// Vulnerability class: CWE-200
public void translate(ServerVehicleMovePacket packet, GeyserSession session) {
        Entity entity = session.getRidingVehicleEntity();
        if (entity == null) return;

        entity.moveAbsolute(session, Vector3f.from(packet.getX(), packet.getY(), packet.getZ()), packet.getYaw(), packet.getPitch(), false, true);
    }

// Vulnerability class: CWE-287
public void testComputeLength() {

		byte[] aad = new byte[]{0, 1, 2, 3}; // 32 bits

		byte[] expectedBitLength = new byte[]{0, 0, 0, 0, 0, 0, 0, 32};

		assertTrue(Arrays.equals(expectedBitLength, AAD.computeLength(aad)));
	}

// Vulnerability class: CWE-345
public void testSetOrdersPseudoHeadersCorrectly() {
        final HttpHeadersBase headers = newHttp2Headers();
        final HttpHeadersBase other = newEmptyHeaders();
        other.add("name2", "value2");
        other.add("name3", "value3");
        other.add("name4", "value4");
        other.authority("foo");

        final int headersSizeBefore = headers.size();
        headers.set(other);
        verifyPseudoHeadersFirst(headers);
        verifyAllPseudoHeadersPresent(headers);
        assertThat(headers.size()).isEqualTo(headersSizeBefore + 1);
        assertThat(headers.authority()).isEqualTo("foo");
        assertThat(headers.get("name2")).isEqualTo("value2");
        assertThat(headers.get("name3")).isEqualTo("value3");
        assertThat(headers.get("name4")).isEqualTo("value4");
    }

// Vulnerability class: CWE-74
public void setHeadersShouldClearAndOverwrite() {
        final HttpHeadersBase headers1 = newEmptyHeaders();
        headers1.add("name", "value");

        final HttpHeadersBase headers2 = newEmptyHeaders();
        headers2.add("name", "newvalue");
        headers2.add("name1", "value1");

        headers1.set(headers2);
        assertThat(headers2).isEqualTo(headers1);
    }

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

    // Create a JPA user with an encoded password.
    String 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 newUser = new JpaUser(user.getUsername(), encodedPassword, organization, user.getName(), user.getEmail(),
            user.getProvider(), user.isManageable(), roles);

    // Then save the user
    EntityManager em = null;
    EntityTransaction tx = null;
    try {
      em = emf.createEntityManager();
      tx = em.getTransaction();
      tx.begin();
      em.persist(newUser);
      tx.commit();
      cache.put(user.getUsername() + DELIMITER + user.getOrganization().getId(), newUser);
    } finally {
      if (tx.isActive()) {
        tx.rollback();
      }
      if (em != null)
        em.close();
    }

    updateGroupMembership(user);

  }

// Vulnerability class: CWE-327
public SecureIntrospector(String[] badClasses, String[] badPackages, Logger log)
    {
        super(badClasses, badPackages, log);

        this.secureClassMethods.add("getname");
        this.secureClassMethods.add("getName");
        this.secureClassMethods.add("getsimpleName");
        this.secureClassMethods.add("getSimpleName");

        this.secureClassMethods.add("isarray");
        this.secureClassMethods.add("isArray");
        this.secureClassMethods.add("isassignablefrom");
        this.secureClassMethods.add("isAssignableFrom");
        this.secureClassMethods.add("isenum");
        this.secureClassMethods.add("isEnum");
        this.secureClassMethods.add("isinstance");
        this.secureClassMethods.add("isInstance");
        this.secureClassMethods.add("isinterface");
        this.secureClassMethods.add("isInterface");
        this.secureClassMethods.add("islocalClass");
        this.secureClassMethods.add("isLocalClass");
        this.secureClassMethods.add("ismemberclass");
        this.secureClassMethods.add("isMemberClass");
        this.secureClassMethods.add("isprimitive");
        this.secureClassMethods.add("isPrimitive");
        this.secureClassMethods.add("issynthetic");
        this.secureClassMethods.add("isSynthetic");
        this.secureClassMethods.add("getEnumConstants");

        // TODO: add more when needed
    }

// Vulnerability class: CWE-668
protected void afterFeaturesReceived() throws SecurityRequiredException, NotConnectedException {
        StartTls startTlsFeature = getFeature(StartTls.ELEMENT, StartTls.NAMESPACE);
        if (startTlsFeature != null) {
            if (startTlsFeature.required() && config.getSecurityMode() == SecurityMode.disabled) {
                notifyConnectionError(new SecurityRequiredByServerException());
                return;
            }

            if (config.getSecurityMode() != ConnectionConfiguration.SecurityMode.disabled) {
                send(new StartTls());
            }
        }
        // If TLS is required but the server doesn't offer it, disconnect
        // from the server and throw an error. First check if we've already negotiated TLS
        // and are secure, however (features get parsed a second time after TLS is established).
        if (!isSecureConnection() && startTlsFeature == null
                        && getConfiguration().getSecurityMode() == SecurityMode.required) {
            throw new SecurityRequiredByClientException();
        }

        if (getSASLAuthentication().authenticationSuccessful()) {
            // If we have received features after the SASL has been successfully completed, then we
            // have also *maybe* received, as it is an optional feature, the compression feature
            // from the server.
            maybeCompressFeaturesReceived.reportSuccess();
        }
    }

// Vulnerability class: CWE-362
public int clone(ConsoleOutputStreamConsumer outputStreamConsumer, UrlArgument repositoryUrl) {
        CommandLine hg = createCommandLine("hg").withArgs("clone").withArg("-b").withArg(branch).withArg(repositoryUrl)
                .withArg(workingDir.getAbsolutePath()).withNonArgSecrets(secrets).withEncoding("utf-8");
        return execute(hg, outputStreamConsumer);
    }

// Vulnerability class: CWE-77
public void handle(HttpServletRequest request, HttpServletResponse response)
      throws Exception
  {
    // We're sending an XML response, so set the response content type to text/xml
    response.setContentType("text/xml");

    // Parse the incoming request as XML
    SAXReader xmlReader = new SAXReader();
    Document doc = xmlReader.read(request.getInputStream());
    Element env = doc.getRootElement();

    Element body = env.element("body");

    // First handle any new subscriptions
    List<SubscriptionRequest> requests = new ArrayList<SubscriptionRequest>();

    List<Element> elements = body.elements("subscribe");
    for (Element e : elements)
    {
      requests.add(new SubscriptionRequest(e.attributeValue("topic")));
    }

    ServletLifecycle.beginRequest(request);
    try
    {
      ServletContexts.instance().setRequest(request);

      Manager.instance().initializeTemporaryConversation();
      ServletLifecycle.resumeConversation(request);

      for (SubscriptionRequest req : requests)
      {
        req.subscribe();
      }

      // Then handle any unsubscriptions
      List<String> unsubscribeTokens = new ArrayList<String>();

      elements = body.elements("unsubscribe");
      for (Element e : elements) 
      {
        unsubscribeTokens.add(e.attributeValue("token"));
      }

      for (String token : unsubscribeTokens) 
      {
        RemoteSubscriber subscriber = SubscriptionRegistry.instance().
                                      getSubscription(token);
        if (subscriber != null)
        {
          subscriber.unsubscribe();
        }
      }
    }
    finally
    {
      Lifecycle.endRequest();
    }

    // Package up the response
    marshalResponse(requests, response.getOutputStream());
  }

// Vulnerability class: CWE-200
public void translate(ServerUpdateViewPositionPacket packet, GeyserSession session) {
        if (!session.isSpawned() && session.getLastChunkPosition() == null) {
            ChunkUtils.updateChunkPosition(session, Vector3i.from(packet.getChunkX() << 4, 64, packet.getChunkZ() << 4));
        }
    }

// Vulnerability class: CWE-287
public void checkAccess(Thread t) {
		if (RobocodeProperties.isSecurityOff()) {
			return;
		}

		Thread c = Thread.currentThread();

		if (isSafeThread(c)) {
			return;
		}
		super.checkAccess(t);

		// Threads belonging to other thread groups is not allowed to access threads belonging to other thread groups
		// Bug fix [3021140] Possible for robot to kill other robot threads.
		// In the following the thread group of the current thread must be in the thread group hierarchy of the
		// attacker thread; otherwise an AccessControlException must be thrown.

		boolean found = false;
		
		ThreadGroup cg = c.getThreadGroup();
		ThreadGroup tg = t.getThreadGroup();

		while (tg != null) {
			if (tg == cg) {
				found = true;
				break;
			}
			try {
				tg = tg.getParent();
			} catch (AccessControlException e) {
				// We expect an AccessControlException due to missing RuntimePermission modifyThreadGroup
				break;
			}
		}
		if (!found) {
			String message = "Preventing " + c.getName() + " from access to " + t.getName();
			IHostedThread robotProxy = threadManager.getLoadedOrLoadingRobotProxy(c);

			if (robotProxy != null) {
				robotProxy.punishSecurityViolation(message);
			}
			throw new AccessControlException(message);
		}
	}

// Vulnerability class: CWE-862