code
stringlengths 23
2.05k
| label_name
stringlengths 6
7
| label
int64 0
37
|
---|---|---|
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);
} | CWE-287 | 4 |
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"));
} | CWE-74 | 1 |
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");
} | CWE-74 | 1 |
protected int getExpectedErrors() {
return hasJavaNetURLPermission ? 3 : 2; // Security error must be reported as an error
} | CWE-862 | 8 |
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));
} | CWE-862 | 8 |
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");
} | CWE-327 | 3 |
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));
} | CWE-862 | 8 |
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);
} | CWE-287 | 4 |
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);
}
} | CWE-345 | 22 |
public void delete(String databaseType) {
Path path = Paths.get(driverFilePath(driverBaseDirectory, databaseType));
try {
Files.deleteIfExists(path);
} catch (IOException e) {
log.error("delete driver error " + databaseType, e);
}
} | CWE-20 | 0 |
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;
} | CWE-668 | 7 |
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());
} | CWE-287 | 4 |
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;
} | CWE-74 | 1 |
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());
} | CWE-287 | 4 |
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);
} | CWE-862 | 8 |
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);
} | CWE-200 | 10 |
default Optional<MediaType> contentType() {
return getFirst(HttpHeaders.CONTENT_TYPE, MediaType.class);
} | CWE-400 | 2 |
public void subClassExample() throws Exception {
assertThat(ConstraintViolations.format(validator.validate(new SubclassExample())))
.containsExactlyInAnyOrder(
FAILED_RESULT,
FAILED_RESULT+"subclass"
);
assertThat(TestLoggerFactory.getAllLoggingEvents())
.isEmpty();
} | CWE-74 | 1 |
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);
} | CWE-287 | 4 |
protected final void populateUrlAttributeMap(final Map<String, String> urlParameters) {
urlParameters.put("pgtUrl", encodeUrl(this.proxyCallbackUrl));
} | CWE-74 | 1 |
public void highlightInMuc(Conversation conversation, String nick) {
switchToConversation(conversation, null, false, nick, false);
} | CWE-200 | 10 |
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;
} | CWE-346 | 16 |
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);
} | CWE-287 | 4 |
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();
} | CWE-77 | 14 |
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);
} | CWE-77 | 14 |
public void checkConnection(UrlArgument repositoryURL) {
execute(createCommandLine("hg").withArgs("id", "--id").withArg(repositoryURL).withNonArgSecrets(secrets).withEncoding("utf-8"), new NamedProcessTag(repositoryURL.forDisplay()));
} | CWE-77 | 14 |
public static <T> T throw0(Throwable throwable) {
if (throwable == null) throw new NullPointerException();
getUnsafe().throwException(throwable);
throw new RuntimeException();
} | CWE-200 | 10 |
public User getUser() {
return user;
} | CWE-200 | 10 |
public void iterateEmptyHeadersShouldThrow() {
final Iterator<Map.Entry<AsciiString, String>> iterator = newEmptyHeaders().iterator();
assertThat(iterator.hasNext()).isFalse();
iterator.next();
} | CWE-74 | 1 |
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);
}
} | CWE-74 | 1 |
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);
} | CWE-74 | 1 |
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");
}
} | CWE-345 | 22 |
public void emptyHeadersShouldBeEqual() {
final HttpHeadersBase headers1 = newEmptyHeaders();
final HttpHeadersBase headers2 = newEmptyHeaders();
assertThat(headers2).isEqualTo(headers1);
assertThat(headers2.hashCode()).isEqualTo(headers1.hashCode());
} | CWE-74 | 1 |
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);
} | CWE-287 | 4 |
protected void runTeardown() {
Assert.assertTrue("HTTP connection is not allowed", messagedAccessDenied);
} | CWE-862 | 8 |
public ConstraintValidatorContext getContext() {
return context;
} | CWE-74 | 1 |
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);
}
} | CWE-863 | 11 |
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;
} | CWE-862 | 8 |
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());
} | CWE-287 | 4 |
public void translate(ServerDisconnectPacket packet, GeyserSession session) {
session.disconnect(MessageTranslator.convertMessage(packet.getReason(), session.getLocale()));
} | CWE-287 | 4 |
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();
}
} | CWE-287 | 4 |
public void translate(ServerPingPacket packet, GeyserSession session) {
session.sendDownstreamPacket(new ClientPongPacket(packet.getId()));
} | CWE-287 | 4 |
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);
} | CWE-862 | 8 |
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();
} | CWE-74 | 1 |
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));
} | CWE-862 | 8 |
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);
} | CWE-862 | 8 |
public void annotatedSubClassExample() throws Exception {
assertThat(ConstraintViolations.format(validator.validate(new AnnotatedSubclassExample())))
.containsExactlyInAnyOrder(
FAILED_RESULT,
FAILED_RESULT+"subclass"
);
assertThat(TestLoggerFactory.getAllLoggingEvents())
.isEmpty();
} | CWE-74 | 1 |
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));
}
} | CWE-74 | 1 |
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;
} | CWE-754 | 31 |
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);
} | CWE-287 | 4 |
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
}
} | CWE-287 | 4 |
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);
} | CWE-862 | 8 |
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);
}
} | CWE-200 | 10 |
public void subValidateFail(ViolationCollector col) {
col.addViolation(FAILED+"subclass");
} | CWE-74 | 1 |
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();
} | CWE-74 | 1 |
public void translate(ServerStatisticsPacket packet, GeyserSession session) {
session.updateStatistics(packet.getStatistics());
if (session.isWaitingForStatistics()) {
session.setWaitingForStatistics(false);
StatisticsUtils.buildAndSendStatisticsMenu(session);
}
} | CWE-287 | 4 |
default Optional<Integer> findInt(CharSequence name) {
return get(name, Integer.class);
} | CWE-400 | 2 |
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));
} | CWE-862 | 8 |
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();
} | CWE-862 | 8 |
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);
}
} | CWE-327 | 3 |
public String compact() {
return id.replaceAll("/", "-").replaceAll("\\\\", "-");
} | CWE-74 | 1 |
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();
}
} | CWE-287 | 4 |
public synchronized MultiMap headers() {
if (headers == null) {
headers = new CaseInsensitiveHeaders();
}
return headers;
} | CWE-20 | 0 |
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);
}
}
} | CWE-665 | 32 |
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));
} | CWE-77 | 14 |
public Argument<Session> argumentType() {
return Argument.of(Session.class);
} | CWE-400 | 2 |
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());
}
} | CWE-862 | 8 |
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");
} | CWE-74 | 1 |
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;
}
| CWE-200 | 10 |
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);
}
} | CWE-287 | 4 |
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());
}
} | CWE-287 | 4 |
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;
} | CWE-20 | 0 |
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);
} | CWE-74 | 1 |
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");
} | CWE-327 | 3 |
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);
} | CWE-74 | 1 |
private DocumentReferenceResolver<String> getCurrentMixedDocumentReferenceResolver()
{
return Utils.getComponent(DocumentReferenceResolver.TYPE_STRING, CURRENT_MIXED_RESOLVER_HINT);
} | CWE-862 | 8 |
public void translate(ServerMultiBlockChangePacket packet, GeyserSession session) {
for (BlockChangeRecord record : packet.getRecords()) {
ChunkUtils.updateBlock(session, record.getBlock(), record.getPosition());
}
} | CWE-287 | 4 |
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();
}
}
| CWE-200 | 10 |
public static void endRequest() {
final List<RequestScopedItem> result = CACHE.get();
CACHE.remove();
if (result != null) {
for (final RequestScopedItem item : result) {
item.invalidate();
}
}
} | CWE-362 | 18 |
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);
} | CWE-200 | 10 |
Randoms() {
random = new Random();
Date date = new Date();
random.setSeed(date.getTime());
} | CWE-327 | 3 |
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);
} | CWE-287 | 4 |
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)));
} | CWE-345 | 22 |
public void failingExample() throws Exception {
assertThat(ConstraintViolations.format(validator.validate(new FailingExample())))
.containsExactlyInAnyOrder(FAILED_RESULT);
assertThat(TestLoggerFactory.getAllLoggingEvents())
.isEmpty();
} | CWE-74 | 1 |
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");
} | CWE-74 | 1 |
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);
} | CWE-74 | 1 |
public void add(File fileToAdd) {
String[] args = new String[]{"add", fileToAdd.getName()};
CommandLine gitAdd = gitWd().withArgs(args);
runOrBomb(gitAdd);
} | CWE-77 | 14 |
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);
} | CWE-327 | 3 |
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
} | CWE-668 | 7 |
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();
}
} | CWE-362 | 18 |
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);
} | CWE-77 | 14 |
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());
} | CWE-200 | 10 |
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));
}
} | CWE-287 | 4 |
public String invokeServletAndReturnAsString(String url)
{
return this.xwiki.invokeServletAndReturnAsString(url, getXWikiContext());
} | CWE-862 | 8 |
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);
}
} | CWE-862 | 8 |
public void translate(EmotePacket packet, GeyserSession session) {
if (session.getConnector().getConfig().getEmoteOffhandWorkaround() != EmoteOffhandWorkaroundOption.DISABLED) {
// Activate the workaround - we should trigger the offhand now
ClientPlayerActionPacket swapHandsPacket = new ClientPlayerActionPacket(PlayerAction.SWAP_HANDS, BlockUtils.POSITION_ZERO,
BlockFace.DOWN);
session.sendDownstreamPacket(swapHandsPacket);
if (session.getConnector().getConfig().getEmoteOffhandWorkaround() == EmoteOffhandWorkaroundOption.NO_EMOTES) {
return;
}
}
long javaId = session.getPlayerEntity().getEntityId();
for (GeyserSession otherSession : session.getConnector().getPlayers()) {
if (otherSession != session) {
if (otherSession.isClosed()) continue;
if (otherSession.getEventLoop().inEventLoop()) {
playEmote(otherSession, javaId, packet.getEmoteId());
} else {
session.executeInEventLoop(() -> playEmote(otherSession, javaId, packet.getEmoteId()));
}
}
}
} | CWE-287 | 4 |
public void validateConcreteScmMaterial(ValidationContext validationContext) {
if (getView() == null || getView().trim().isEmpty()) {
errors.add(VIEW, "P4 view cannot be empty.");
}
if (StringUtils.isBlank(getServerAndPort())) {
errors.add(SERVER_AND_PORT, "P4 port cannot be empty.");
}
validateEncryptedPassword();
} | CWE-77 | 14 |
public void switchToConversationAndQuote(Conversation conversation, String text) {
switchToConversation(conversation, text, true, null, false);
} | CWE-200 | 10 |
public boolean matches(ConditionContext context) {
BeanContext beanContext = context.getBeanContext();
if (beanContext instanceof ApplicationContext) {
List<String> paths = ((ApplicationContext) beanContext)
.getEnvironment()
.getProperty(FileWatchConfiguration.PATHS, Argument.listOf(String.class))
.orElse(null);
if (CollectionUtils.isNotEmpty(paths)) {
boolean matchedPaths = paths.stream().anyMatch(p -> new File(p).exists());
if (!matchedPaths) {
context.fail("File watch disabled because no paths matching the watch pattern exist (Paths: " + paths + ")");
}
return matchedPaths;
}
}
context.fail("File watch disabled because no watch paths specified");
return false;
} | CWE-400 | 2 |
private String doResolveSqlDriverNameFromJar(File driverFile) {
JarFile jarFile = null;
try {
jarFile = new JarFile(driverFile);
} catch (IOException e) {
log.error("resolve driver class name error", e);
throw DomainErrors.DRIVER_CLASS_NAME_OBTAIN_ERROR.exception(e.getMessage());
}
final JarFile driverJar = jarFile;
String driverClassName = jarFile.stream()
.filter(entry -> entry.getName().contains("META-INF/services/java.sql.Driver"))
.findFirst()
.map(entry -> {
InputStream stream = null;
BufferedReader reader = null;
try {
stream = driverJar.getInputStream(entry);
reader = new BufferedReader(new InputStreamReader(stream));
return reader.readLine();
} catch (IOException e) {
log.error("resolve driver class name error", e);
throw DomainErrors.DRIVER_CLASS_NAME_OBTAIN_ERROR.exception(e.getMessage());
} finally {
IOUtils.closeQuietly(reader, ex -> log.error("close reader error", ex));
}
})
.orElseThrow(DomainErrors.DRIVER_CLASS_NAME_OBTAIN_ERROR::exception);
IOUtils.closeQuietly(jarFile, ex -> log.error("close jar file error", ex));
return driverClassName;
} | CWE-20 | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.