mcanoglu/cwe-class-group huggingface dataset:
public static Object instantiate(String classname, Properties info, boolean tryString,
      @Nullable String stringarg)
      throws ClassNotFoundException, SecurityException, NoSuchMethodException,
          IllegalArgumentException, InstantiationException, IllegalAccessException,
          InvocationTargetException {
    @Nullable Object[] args = {info};
    Constructor<?> ctor = null;
    Class<?> cls = Class.forName(classname);
    try {
      ctor = cls.getConstructor(Properties.class);
    } catch (NoSuchMethodException ignored) {
    }
    if (tryString && ctor == null) {
      try {
        ctor = cls.getConstructor(String.class);
        args = new String[]{stringarg};
      } catch (NoSuchMethodException ignored) {
      }
    }
    if (ctor == null) {
      ctor = cls.getConstructor();
      args = new Object[0];
    }
    return ctor.newInstance(args);
  }

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

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

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

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

        // Specifying a template provider in the URL: templateprovider=XWiki.MyTemplateProvider
        String templateProviderFullName = "XWiki.MyTemplateProvider";
        when(mockRequest.getParameter("templateprovider")).thenReturn(templateProviderFullName);

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

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

        // The tests are below this line!

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

        // Note: We are creating the document X.Y as terminal, since the template provider did not specify a "terminal"
        // property and it used the old "page" type instead. Also using a template, as specified in the template
        // provider.
        verify(mockURLFactory).createURL("X", "Y", "edit", "template=XWiki.MyTemplate&parent=Main.WebHome&title=Y",
            null, "xwiki", context);
    }

// Vulnerability class: CWE-862
public void complexExample() throws Exception {
        assertThat(ConstraintViolations.format(validator.validate(new ComplexExample())))
            .containsExactlyInAnyOrder(
                FAILED_RESULT + "1",
                FAILED_RESULT + "2",
                FAILED_RESULT + "3"
            );
        assertThat(TestLoggerFactory.getAllLoggingEvents())
            .isEmpty();
    }

// Vulnerability class: CWE-74
public void translate(ServerUnlockRecipesPacket packet, GeyserSession session) {
        if (packet.getAction() == UnlockRecipesAction.REMOVE) {
            session.getUnlockedRecipes().removeAll(Arrays.asList(packet.getRecipes()));
        } else {
            session.getUnlockedRecipes().addAll(Arrays.asList(packet.getRecipes()));
        }
    }

// Vulnerability class: CWE-287
public void existingDocumentTerminalFromUICheckEscaping() 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.Y&name=Z&tocreate=termina
        when(mockRequest.getParameter("spaceReference")).thenReturn("X.Y");
        when(mockRequest.getParameter("name")).thenReturn("Z");
        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.Z instead of X.Y.Z.WebHome because the tocreate parameter says "terminal".
        verify(mockURLFactory).createURL("X.Y", "Z", "edit", "template=&parent=Main.WebHome&title=Z", null, "xwiki",
            context);
    }

// Vulnerability class: CWE-862
protected boolean isProbablePrime(BigInteger x, int iterations)
    {
        /*
         * Primes class for FIPS 186-4 C.3 primality checking
         */
        return !Primes.hasAnySmallFactors(x) && Primes.isMRProbablePrime(x, param.getRandom(), iterations);
    }

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

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

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

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

        // The tests are below this line!

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

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

// Vulnerability class: CWE-862
public void translate(ServerSpawnPlayerPacket packet, GeyserSession session) {
        Vector3f position = Vector3f.from(packet.getX(), packet.getY(), packet.getZ());
        Vector3f rotation = Vector3f.from(packet.getYaw(), packet.getPitch(), packet.getYaw());

        PlayerEntity entity;
        if (packet.getUuid().equals(session.getPlayerEntity().getUuid())) {
            // Server is sending a fake version of the current player
            entity = new PlayerEntity(session.getPlayerEntity().getProfile(), packet.getEntityId(), session.getEntityCache().getNextEntityId().incrementAndGet(), position, Vector3f.ZERO, rotation);
        } else {
            entity = session.getEntityCache().getPlayerEntity(packet.getUuid());
            if (entity == null) {
                GeyserConnector.getInstance().getLogger().error(LanguageUtils.getLocaleStringLog("geyser.entity.player.failed_list", packet.getUuid()));
                return;
            }

            entity.setEntityId(packet.getEntityId());
            entity.setPosition(position);
            entity.setRotation(rotation);
        }
        session.getEntityCache().cacheEntity(entity);

        entity.sendPlayer(session);
        SkinManager.requestAndHandleSkinAndCape(entity, session, null);
    }

// Vulnerability class: CWE-287
public void translate(NetworkStackLatencyPacket packet, GeyserSession session) {
        long pingId;
        // so apparently, as of 1.16.200
        // PS4 divides the network stack latency timestamp FOR US!!!
        // WTF
        if (session.getClientData().getDeviceOs().equals(DeviceOs.PS4)) {
            pingId = packet.getTimestamp();
        } else {
            pingId = packet.getTimestamp() / 1000;
        }

        // negative timestamps are used as hack to fix the url image loading bug
        if (packet.getTimestamp() > 0) {
            if (session.getConnector().getConfig().isForwardPlayerPing()) {
                ClientKeepAlivePacket keepAlivePacket = new ClientKeepAlivePacket(pingId);
                session.sendDownstreamPacket(keepAlivePacket);
            }
            return;
        }

        // Hack to fix the url image loading bug
        UpdateAttributesPacket attributesPacket = new UpdateAttributesPacket();
        attributesPacket.setRuntimeEntityId(session.getPlayerEntity().getGeyserId());

        AttributeData attribute = session.getPlayerEntity().getAttributes().get(GeyserAttributeType.EXPERIENCE_LEVEL);
        if (attribute != null) {
            attributesPacket.setAttributes(Collections.singletonList(attribute));
        } else {
            attributesPacket.setAttributes(Collections.singletonList(GeyserAttributeType.EXPERIENCE_LEVEL.getAttribute(0)));
        }

        session.getConnector().getGeneralThreadPool().schedule(
                () -> session.sendUpstreamPacket(attributesPacket),
                500, TimeUnit.MILLISECONDS);
    }

// Vulnerability class: CWE-287
public void invalidExample() throws Exception {
        assertThat(ConstraintViolations.format(validator.validate(new InvalidExample())))
            .isEmpty();
        assertThat(TestLoggerFactory.getAllLoggingEvents())
            .containsExactlyInAnyOrder(
                    new LoggingEvent(
                            Level.ERROR, 
                            "The method {} is annotated with @SelfValidation but does not have a single parameter of type {}",
                            InvalidExample.class.getMethod("validateFailAdditionalParameters", ViolationCollector.class, int.class),
                            ViolationCollector.class
                    ),
                    new LoggingEvent(
                            Level.ERROR, 
                            "The method {} is annotated with @SelfValidation but does not return void. It is ignored",
                            InvalidExample.class.getMethod("validateFailReturn", ViolationCollector.class)
                    ),
                    new LoggingEvent(
                            Level.ERROR, 
                            "The method {} is annotated with @SelfValidation but is not public",
                            InvalidExample.class.getDeclaredMethod("validateFailPrivate", ViolationCollector.class)
                    )
            );
    }

// Vulnerability class: CWE-74
private String tryRewrite(String s) throws IOException, InvalidKeyException {
        if (s.length()<24)
            return s;   // Encrypting "" in Secret produces 24-letter characters, so this must be the minimum length
        if (!isBase64(s))
            return s;   // decode throws IOException if the input is not base64, and this is also a very quick way to filter

        byte[] in;
        try {
            in = Base64.decode(s.toCharArray());
        } catch (IOException e) {
            return s;   // not a valid base64
        }
        cipher.init(Cipher.DECRYPT_MODE, key);
        Secret sec = Secret.tryDecrypt(cipher, in);
        if(sec!=null) // matched
            return sec.getEncryptedValue(); // replace by the new encrypted value
        else // not encrypted with the legacy key. leave it unmodified
            return s;
    }

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

        // Specifying a template provider in the URL: templateprovider=XWiki.MyTemplateProvider
        String templateProviderFullName = "XWiki.MyTemplateProvider";
        when(mockRequest.getParameter("templateprovider")).thenReturn(templateProviderFullName);

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

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

        // The tests are below this line!

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

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

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

        // 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.Z.WebHome since we default to non-terminal documents.
        verify(mockURLFactory).createURL("X.Y.Z", "WebHome", "edit", "template=&parent=Main.WebHome&title=Z", null,
            "xwiki", context);
    }

// Vulnerability class: CWE-862
final void setObject(CharSequence name, Object... 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
private X509HostnameVerifier createHostNameVerifier() {
    X509HostnameVerifier verifier = new X509HostnameVerifier() {

      /**
       * {@InheritDoc}
       *
       * @see org.apache.http.conn.ssl.X509HostnameVerifier#verify(java.lang.String, javax.net.ssl.SSLSocket)
       */
      public void verify(String host, SSLSocket ssl) throws IOException {
        logger.trace("Skipping SSL host name check on {}", host);
      }

      /**
       * {@InheritDoc}
       *
       * @see org.apache.http.conn.ssl.X509HostnameVerifier#verify(java.lang.String, java.security.cert.X509Certificate)
       */
      public void verify(String host, X509Certificate xc) throws SSLException {
        logger.trace("Skipping X509 certificate host name check on {}", host);
      }

      /**
       * {@InheritDoc}
       *
       * @see org.apache.http.conn.ssl.X509HostnameVerifier#verify(java.lang.String, java.lang.String[],
       *      java.lang.String[])
       */
      public void verify(String host, String[] cns, String[] subjectAlts) throws SSLException {
        logger.trace("Skipping DNS host name check on {}", host);
      }

      /**
       * {@InheritDoc}
       *
       * @see javax.net.ssl.HostnameVerifier#verify(java.lang.String, javax.net.ssl.SSLSession)
       */
      public boolean verify(String host, SSLSession ssl) {
        logger.trace("Skipping SSL session host name check on {}", host);
        return true;
      }
    };

    return verifier;
  }

// Vulnerability class: CWE-346
public void existingDocumentFromUITemplateProviderSpecifiedRestrictionExistsOnParentSpace() 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.Y.Z&name=W&templateProvider=XWiki.MyTemplateProvider
        String templateProviderFullName = "XWiki.MyTemplateProvider";
        String spaceReferenceString = "X.Y.Z";
        when(mockRequest.getParameter("spaceReference")).thenReturn(spaceReferenceString);
        when(mockRequest.getParameter("name")).thenReturn("W");
        when(mockRequest.getParameter("templateprovider")).thenReturn(templateProviderFullName);

        // Mock 1 existing template provider that allows usage in one of the target space's parents (top level in this
        // case).
        mockExistingTemplateProviders(templateProviderFullName,
            new DocumentReference("xwiki", Arrays.asList("XWiki"), "MyTemplateProvider"), Arrays.asList("X"));

        // 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: We are allowed to create anything under space X or its children, be it a terminal or a non-terminal
        // document
        // Note2: We are creating X.Y.Z.W and using the template extracted from the template provider.
        verify(mockURLFactory).createURL("X.Y.Z.W", "WebHome", "edit",
            "template=XWiki.MyTemplate&parent=Main.WebHome&title=W", null, "xwiki", context);
    }

// Vulnerability class: CWE-862
public void update(DatabaseTypeUpdateRequest request) {
        databaseTypeDao.selectOptionalById(request.getId()).ifPresent(data -> {
            if (DatabaseTypes.has(data.getDatabaseType())) {
                throw DomainErrors.MUST_NOT_MODIFY_SYSTEM_DEFAULT_DATABASE_TYPE.exception();
            }

            DatabaseTypePojo pojo = databaseTypePojoConverter.of(request);
            try {
                databaseTypeDao.updateById(pojo);
            } catch (DuplicateKeyException e) {
                throw DomainErrors.DATABASE_TYPE_NAME_DUPLICATE.exception();
            }

            // 名称修改，下载地址修改需要删除原有的 driver
            if (!Objects.equals(request.getDatabaseType(), data.getDatabaseType())
                    || !Objects.equals(request.getJdbcDriverFileUrl(), data.getJdbcDriverFileUrl())) {
                driverResources.delete(data.getDatabaseType());
            }
        });

    }

// Vulnerability class: CWE-20
public void translate(ServerSettingsRequestPacket packet, GeyserSession session) {
        CustomForm window = SettingsUtils.buildForm(session);
        int windowId = session.getFormCache().addForm(window);

        // Fixes https://bugs.mojang.com/browse/MCPE-94012 because of the delay
        session.getConnector().getGeneralThreadPool().schedule(() -> {
            ServerSettingsResponsePacket serverSettingsResponsePacket = new ServerSettingsResponsePacket();
            serverSettingsResponsePacket.setFormData(window.getJsonData());
            serverSettingsResponsePacket.setFormId(windowId);
            session.sendUpstreamPacket(serverSettingsResponsePacket);
        }, 1, TimeUnit.SECONDS);
    }

// Vulnerability class: CWE-287
public void shouldGetLatestModifications() throws Exception {
        List<Modification> actual = hgCommand.latestOneModificationAsModifications();
        assertThat(actual.size(), is(1));
        final Modification modification = actual.get(0);
        assertThat(modification.getComment(), is("test"));
        assertThat(modification.getUserName(), is("cruise"));
        assertThat(modification.getModifiedFiles().size(), is(1));
    }

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

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

        // Mock 1 existing template provider
        mockExistingTemplateProviders(templateProviderFullName,
            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 null is returned (this means the response has been returned)
        assertNull(result);

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

// Vulnerability class: CWE-862
public void translate(ServerSpawnParticlePacket packet, GeyserSession session) {
        Function<Vector3f, BedrockPacket> particleCreateFunction = createParticle(session, packet.getParticle());
        if (particleCreateFunction != null) {
            if (packet.getAmount() == 0) {
                // 0 means don't apply the offset
                Vector3f position = Vector3f.from(packet.getX(), packet.getY(), packet.getZ());
                session.sendUpstreamPacket(particleCreateFunction.apply(position));
            } else {
                Random random = ThreadLocalRandom.current();
                for (int i = 0; i < packet.getAmount(); i++) {
                    double offsetX = random.nextGaussian() * (double) packet.getOffsetX();
                    double offsetY = random.nextGaussian() * (double) packet.getOffsetY();
                    double offsetZ = random.nextGaussian() * (double) packet.getOffsetZ();
                    Vector3f position = Vector3f.from(packet.getX() + offsetX, packet.getY() + offsetY, packet.getZ() + offsetZ);

                    session.sendUpstreamPacket(particleCreateFunction.apply(position));
                }
            }
        } else {
            // Null is only returned when no particle of this type is found
            session.getConnector().getLogger().debug("Unhandled particle packet: " + packet);
        }
    }

// Vulnerability class: CWE-287
public void setUp() throws Exception
    {
        context = oldcore.getXWikiContext();

        Utils.setComponentManager(oldcore.getMocker());

        QueryManager mockSecureQueryManager =
            oldcore.getMocker().registerMockComponent((Type) QueryManager.class, "secure");

        mockTemplateProvidersQuery = mock(Query.class);
        when(mockSecureQueryManager.createQuery(any(), any())).thenReturn(mockTemplateProvidersQuery);
        when(mockTemplateProvidersQuery.execute()).thenReturn(Collections.emptyList());

        when(oldcore.getMockContextualAuthorizationManager().hasAccess(any(Right.class), any(EntityReference.class)))
            .thenReturn(true);

        Provider<DocumentReference> mockDocumentReferenceProvider =
            oldcore.getMocker().registerMockComponent(DocumentReference.TYPE_PROVIDER);
        when(mockDocumentReferenceProvider.get())
            .thenReturn(new DocumentReference("xwiki", Arrays.asList("Main"), "WebHome"));

        mockURLFactory = mock(XWikiURLFactory.class);
        context.setURLFactory(mockURLFactory);

        action = new CreateAction();

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

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

        when(mockRequest.get("type")).thenReturn("plain");

        this.oldcore.getMocker().registerMockComponent(ObservationManager.class);
    }

// Vulnerability class: CWE-862
public static SSLSocketFactory getSslSocketFactory(Properties info) throws PSQLException {
    String classname = PGProperty.SSL_FACTORY.get(info);
    if (classname == null
        || "org.postgresql.ssl.jdbc4.LibPQFactory".equals(classname)
        || "org.postgresql.ssl.LibPQFactory".equals(classname)) {
      return new LibPQFactory(info);
    }
    try {
      return (SSLSocketFactory) ObjectFactory.instantiate(classname, info, true,
          PGProperty.SSL_FACTORY_ARG.get(info));
    } catch (Exception e) {
      throw new PSQLException(
          GT.tr("The SSLSocketFactory class provided {0} could not be instantiated.", classname),
          PSQLState.CONNECTION_FAILURE, e);
    }
  }

// Vulnerability class: CWE-665
public void handle(HttpServletRequest request, final 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();

    final List<PollRequest> polls = unmarshalRequests(env);

    new ContextualHttpServletRequest(request)
    {
       @Override
       public void process() throws Exception
       {        
          for (PollRequest req : polls)
          {
             req.poll();
          }
      
          // Package up the response
          marshalResponse(polls, response.getOutputStream());      
       }
    }.run();
  }

// Vulnerability class: CWE-200
public <T> List<T> search(String filter, Object[] filterArgs, Mapper<T> mapper, int maxResult) {
        List<T> results = new ArrayList<>();
        DirContext dirContext = getDirContext(ldapConfiguration, ldapConfiguration.getManagerDn(), ldapConfiguration.getPassword());

        try {
            List<SearchResult> searchResults = search(dirContext, filter, filterArgs, maxResult, false);

            for (SearchResult result : searchResults) {
                results.add(mapper.mapObject(new ResultWrapper(result.getAttributes())));
            }
        } catch (NamingException e) {
            throw new LdapException(e);
        } finally {
            closeContextSilently(dirContext);
        }

        return results;
    }

// Vulnerability class: CWE-74
public static SocketFactory getSocketFactory(Properties info) throws PSQLException {
    // Socket factory
    String socketFactoryClassName = PGProperty.SOCKET_FACTORY.get(info);
    if (socketFactoryClassName == null) {
      return SocketFactory.getDefault();
    }
    try {
      return (SocketFactory) ObjectFactory.instantiate(socketFactoryClassName, info, true,
          PGProperty.SOCKET_FACTORY_ARG.get(info));
    } catch (Exception e) {
      throw new PSQLException(
          GT.tr("The SocketFactory class provided {0} could not be instantiated.",
              socketFactoryClassName),
          PSQLState.CONNECTION_FAILURE, e);
    }
  }

// Vulnerability class: CWE-665
public DefaultArgument(Class<T> type, String name, AnnotationMetadata annotationMetadata, Argument... genericTypes) {
        this.type = type;
        this.name = name;
        this.annotationMetadata = annotationMetadata != null ? annotationMetadata : AnnotationMetadata.EMPTY_METADATA;
        this.typeParameters = initializeTypeParameters(genericTypes);
        this.typeParameterArray = genericTypes;
    }

// Vulnerability class: CWE-400
public void translate(ServerAdvancementsPacket packet, GeyserSession session) {
        AdvancementsCache advancementsCache = session.getAdvancementsCache();
        if (packet.isReset()) {
            advancementsCache.getStoredAdvancements().clear();
            advancementsCache.getStoredAdvancementProgress().clear();
        }

        // Removes removed advancements from player's stored advancements
        for (String removedAdvancement : packet.getRemovedAdvancements()) {
            advancementsCache.getStoredAdvancements().remove(removedAdvancement);
        }

        advancementsCache.getStoredAdvancementProgress().putAll(packet.getProgress());

        sendToolbarAdvancementUpdates(session, packet);

        // Adds advancements to the player's stored advancements when advancements are sent
        for (Advancement advancement : packet.getAdvancements()) {
            if (advancement.getDisplayData() != null && !advancement.getDisplayData().isHidden()) {
                GeyserAdvancement geyserAdvancement = GeyserAdvancement.from(advancement);
                advancementsCache.getStoredAdvancements().put(advancement.getId(), geyserAdvancement);
            } else {
                advancementsCache.getStoredAdvancements().remove(advancement.getId());
            }
        }
    }

// Vulnerability class: CWE-287
public void translate(ServerChatPacket packet, GeyserSession session) {
        TextPacket textPacket = new TextPacket();
        textPacket.setPlatformChatId("");
        textPacket.setSourceName("");
        textPacket.setXuid(session.getAuthData().getXboxUUID());
        switch (packet.getType()) {
            case CHAT:
                textPacket.setType(TextPacket.Type.CHAT);
                break;
            case SYSTEM:
                textPacket.setType(TextPacket.Type.SYSTEM);
                break;
            case NOTIFICATION:
                textPacket.setType(TextPacket.Type.TIP);
                break;
            default:
                textPacket.setType(TextPacket.Type.RAW);
                break;
        }

        textPacket.setNeedsTranslation(false);
        textPacket.setMessage(MessageTranslator.convertMessage(packet.getMessage(), session.getLocale()));

        session.sendUpstreamPacket(textPacket);
    }

// Vulnerability class: CWE-287
public void testHeaderNameNormalization() {
        final HttpHeadersBase headers = newHttp2Headers();
        headers.add("Foo", "bar");
        assertThat(headers.getAll("foo")).containsExactly("bar");
        assertThat(headers.getAll("fOO")).containsExactly("bar");
        assertThat(headers.names()).contains(HttpHeaderNames.of("foo"))
                                   .doesNotContain(AsciiString.of("Foo"));
    }

// Vulnerability class: CWE-74
public void testGetOperations() {
        final HttpHeadersBase headers = newEmptyHeaders();
        headers.add("Foo", "1");
        headers.add("Foo", "2");

        assertThat(headers.get("Foo")).isEqualTo("1");

        final List<String> values = headers.getAll("Foo");
        assertThat(values).containsExactly("1", "2");
    }

// Vulnerability class: CWE-74
public void notExistingDocumentFromUIButNameTooLong() 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("Main");
        when(mockRequest.getParameter("name")).thenReturn("Foo123456789");

        // 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
protected BigInteger chooseRandomPrime(int bitlength, BigInteger e, BigInteger sqrdBound)
    {
        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))
            {
                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 newDocumentFromURLTemplateProviderSpecifiedButNotAllowed() throws Exception
    {
        // new document = xwiki:X.Y
        DocumentReference documentReference =
            new DocumentReference("Y", new SpaceReference("X", new WikiReference("xwiki")));
        XWikiDocument document = mock(XWikiDocument.class);
        when(document.getDocumentReference()).thenReturn(documentReference);
        when(document.isNew()).thenReturn(true);
        when(document.getLocalReferenceMaxLength()).thenReturn(255);
        context.setDoc(document);

        // Specifying a template provider in the URL: templateprovider=XWiki.MyTemplateProvider
        String templateProviderFullName = "XWiki.MyTemplateProvider";
        when(mockRequest.getParameter("templateprovider")).thenReturn(templateProviderFullName);

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

        // 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_TEMPLATE_NOT_AVAILABLE, 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
public void translate(ServerClearTitlesPacket packet, GeyserSession session) {
        SetTitlePacket titlePacket = new SetTitlePacket();
        // TODO handle packet.isResetTimes()
        titlePacket.setType(SetTitlePacket.Type.CLEAR);
        titlePacket.setText("");
        titlePacket.setXuid("");
        titlePacket.setPlatformOnlineId("");
        session.sendUpstreamPacket(titlePacket);
    }

// Vulnerability class: CWE-287
public static SecretKey decryptCEK(final PrivateKey priv,
		                           final byte[] encryptedCEK,
		                           final int keyLength,
		                           final Provider provider)
		throws JOSEException {

		try {
			Cipher cipher = CipherHelper.getInstance("RSA/ECB/PKCS1Padding", provider);
			cipher.init(Cipher.DECRYPT_MODE, priv);
			byte[] secretKeyBytes = cipher.doFinal(encryptedCEK);

			if (ByteUtils.bitLength(secretKeyBytes) != keyLength) {
				// CEK key length mismatch
				return null;
			}

			return new SecretKeySpec(secretKeyBytes, "AES");

		} catch (Exception e) {

			// java.security.NoSuchAlgorithmException
			// java.security.InvalidKeyException
			// javax.crypto.IllegalBlockSizeException
			// javax.crypto.BadPaddingException
			throw new JOSEException("Couldn't decrypt Content Encryption Key (CEK): " + e.getMessage(), e);
		}
	}

// Vulnerability class: CWE-345
public static File createTempFile(String prefix, String suffix, File directory) throws IOException {
        if (javaVersion() >= 7) {
            if (directory == null) {
                return Files.createTempFile(prefix, suffix).toFile();
            }
            return Files.createTempFile(directory.toPath(), prefix, suffix).toFile();
        }
        if (directory == null) {
            return File.createTempFile(prefix, suffix);
        }
        File file = File.createTempFile(prefix, suffix, directory);
        // Try to adjust the perms, if this fails there is not much else we can do...
        file.setReadable(false, false);
        file.setReadable(true, true);
        return file;
    }

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

        entity.teleport(session, Vector3f.from(packet.getX(), packet.getY(), packet.getZ()), packet.getYaw(), packet.getPitch(), packet.isOnGround());
    }

// Vulnerability class: CWE-287
private static CharSequenceMap toLowercaseMap(Iterator<? extends CharSequence> valuesIter,
                                                  int arraySizeHint) {
        final CharSequenceMap result = new CharSequenceMap(arraySizeHint);

        while (valuesIter.hasNext()) {
            final AsciiString lowerCased = HttpHeaderNames.of(valuesIter.next()).toLowerCase();
            try {
                int index = lowerCased.forEachByte(FIND_COMMA);
                if (index != -1) {
                    int start = 0;
                    do {
                        result.add(lowerCased.subSequence(start, index, false).trim(), EMPTY_STRING);
                        start = index + 1;
                    } while (start < lowerCased.length() &&
                             (index = lowerCased.forEachByte(start,
                                                             lowerCased.length() - start, FIND_COMMA)) != -1);
                    result.add(lowerCased.subSequence(start, lowerCased.length(), false).trim(), EMPTY_STRING);
                } else {
                    result.add(lowerCased.trim(), EMPTY_STRING);
                }
            } catch (Exception e) {
                // This is not expect to happen because FIND_COMMA never throws but must be caught
                // because of the ByteProcessor interface.
                throw new IllegalStateException(e);
            }
        }
        return result;
    }

// Vulnerability class: CWE-74
public void translate(EntityEventPacket packet, GeyserSession session) {
        switch (packet.getType()) {
            case EATING_ITEM:
                // Resend the packet so we get the eating sounds
                session.sendUpstreamPacket(packet);
                return;
            case COMPLETE_TRADE:
                ClientSelectTradePacket selectTradePacket = new ClientSelectTradePacket(packet.getData());
                session.sendDownstreamPacket(selectTradePacket);

                session.scheduleInEventLoop(() -> {
                    Entity villager = session.getPlayerEntity();
                    Inventory openInventory = session.getOpenInventory();
                    if (openInventory instanceof MerchantContainer) {
                        MerchantContainer merchantInventory = (MerchantContainer) openInventory;
                        VillagerTrade[] trades = merchantInventory.getVillagerTrades();
                        if (trades != null && packet.getData() >= 0 && packet.getData() < trades.length) {
                            VillagerTrade trade = merchantInventory.getVillagerTrades()[packet.getData()];
                            openInventory.setItem(2, GeyserItemStack.from(trade.getOutput()), session);
                            villager.getMetadata().put(EntityData.TRADE_XP, trade.getXp() + villager.getMetadata().getInt(EntityData.TRADE_XP));
                            villager.updateBedrockMetadata(session);
                        }
                    }
                }, 100, TimeUnit.MILLISECONDS);
                return;
        }
        session.getConnector().getLogger().debug("Did not translate incoming EntityEventPacket: " + packet.toString());
    }

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

        // 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 since we default to non-terminal documents.
        verify(mockURLFactory).createURL("X.Y", "WebHome", "edit", "template=&parent=Main.WebHome&title=Y", null,
            "xwiki", context);
    }

// Vulnerability class: CWE-862
public void appendText(String text) {
        if (text == null) {
            return;
        }
        String previous = this.binding.textinput.getText().toString();
        if (UIHelper.isLastLineQuote(previous)) {
            text = '\n' + text;
        } else if (previous.length() != 0 && !Character.isWhitespace(previous.charAt(previous.length() - 1))) {
            text = " " + text;
        }
        this.binding.textinput.append(text);
    }

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

// Vulnerability class: CWE-74
public void translate(ServerOpenWindowPacket packet, GeyserSession session) {
        if (packet.getWindowId() == 0) {
            return;
        }

        InventoryTranslator newTranslator = InventoryTranslator.INVENTORY_TRANSLATORS.get(packet.getType());
        Inventory openInventory = session.getOpenInventory();
        //No translator exists for this window type. Close all windows and return.
        if (newTranslator == null) {
            if (openInventory != null) {
                InventoryUtils.closeInventory(session, openInventory.getId(), true);
            }
            ClientCloseWindowPacket closeWindowPacket = new ClientCloseWindowPacket(packet.getWindowId());
            session.sendDownstreamPacket(closeWindowPacket);
            return;
        }

        String name = MessageTranslator.convertMessageLenient(packet.getName(), session.getLocale());
        name = LocaleUtils.getLocaleString(name, session.getLocale());

        Inventory newInventory = newTranslator.createInventory(name, packet.getWindowId(), packet.getType(), session.getPlayerInventory());
        if (openInventory != null) {
            // If the window type is the same, don't close.
            // In rare cases, inventories can do funny things where it keeps the same window type up but change the contents.
            if (openInventory.getWindowType() != packet.getType()) {
                // Sometimes the server can double-open an inventory with the same ID - don't confirm in that instance.
                InventoryUtils.closeInventory(session, openInventory.getId(), openInventory.getId() != packet.getWindowId());
            }
        }

        session.setInventoryTranslator(newTranslator);
        InventoryUtils.openInventory(session, newInventory);
    }

// Vulnerability class: CWE-287
private X509TrustManager createTrustManager() {
    X509TrustManager trustManager = new X509TrustManager() {

      /**
       * {@InheritDoc}
       *
       * @see javax.net.ssl.X509TrustManager#checkClientTrusted(java.security.cert.X509Certificate[], java.lang.String)
       */
      public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException {
        logger.trace("Skipping trust check on client certificate {}", string);
      }

      /**
       * {@InheritDoc}
       *
       * @see javax.net.ssl.X509TrustManager#checkServerTrusted(java.security.cert.X509Certificate[], java.lang.String)
       */
      public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException {
        logger.trace("Skipping trust check on server certificate {}", string);
      }

      /**
       * {@InheritDoc}
       *
       * @see javax.net.ssl.X509TrustManager#getAcceptedIssuers()
       */
      public X509Certificate[] getAcceptedIssuers() {
        logger.trace("Returning empty list of accepted issuers");
        return null;
      }

    };

    return trustManager;
  }

// Vulnerability class: CWE-346