code
stringlengths 12
2.05k
| label_name
stringclasses 5
values | label
int64 0
4
|
---|---|---|
public EntityResolver getEntityResolver() {
return entityResolver;
} | Base | 1 |
protected void deactivateConversationContext(HttpServletRequest request) {
ConversationContext conversationContext = httpConversationContext();
if (conversationContext.isActive()) {
// Only deactivate the context if one is already active, otherwise we get Exceptions
if (conversationContext instanceof LazyHttpConversationContextImpl) {
LazyHttpConversationContextImpl lazyConversationContext = (LazyHttpConversationContextImpl) conversationContext;
if (!lazyConversationContext.isInitialized()) {
// if this lazy conversation has not been touched yet, just deactivate it
lazyConversationContext.deactivate();
return;
}
}
boolean isTransient = conversationContext.getCurrentConversation().isTransient();
if (ConversationLogger.LOG.isTraceEnabled()) {
if (isTransient) {
ConversationLogger.LOG.cleaningUpTransientConversation();
} else {
ConversationLogger.LOG.cleaningUpConversation(conversationContext.getCurrentConversation().getId());
}
}
conversationContext.invalidate();
conversationContext.deactivate();
if (isTransient) {
conversationDestroyedEvent.fire(request);
}
}
} | Class | 2 |
public void shouldNotIncludeCommitFromAnotherBranchInGetLatestModifications() throws Exception {
Modification lastCommit = hgCommand.latestOneModificationAsModifications().get(0);
makeACommitToSecondBranch();
hg(workingDirectory, "pull").runOrBomb(null);
Modification actual = hgCommand.latestOneModificationAsModifications().get(0);
assertThat(actual, is(lastCommit));
assertThat(actual.getComment(), is(lastCommit.getComment()));
} | Class | 2 |
void encodedUnicode() {
final String encodedPath = "/%ec%95%88";
final String encodedQuery = "%eb%85%95";
final PathAndQuery res = PathAndQuery.parse(encodedPath + '?' + encodedQuery);
assertThat(res).isNotNull();
assertThat(res.path()).isEqualTo(Ascii.toUpperCase(encodedPath));
assertThat(res.query()).isEqualTo(Ascii.toUpperCase(encodedQuery));
} | Base | 1 |
private boolean isFileWithinDirectory(
final File dir,
final File file
) throws IOException {
final File dir_ = dir.getAbsoluteFile();
if (dir_.isDirectory()) {
final File fl = new File(dir_, file.getPath());
if (fl.isFile()) {
if (fl.getCanonicalPath().startsWith(dir_.getCanonicalPath())) {
// Prevent accessing files outside the load-path.
// E.g.: ../../coffee
return true;
}
}
}
return false;
} | Base | 1 |
public String getShortDescription() {
if(note != null) {
return Messages.Cause_RemoteCause_ShortDescriptionWithNote(addr, note);
} else {
return Messages.Cause_RemoteCause_ShortDescription(addr);
}
} | Base | 1 |
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;
} | Base | 1 |
public SAXReader(String xmlReaderClassName) throws SAXException {
if (xmlReaderClassName != null) {
this.xmlReader = XMLReaderFactory
.createXMLReader(xmlReaderClassName);
}
} | Base | 1 |
protected String getCorsDomain(String referer, String userAgent)
{
String dom = null;
if (referer != null && referer.toLowerCase()
.matches("https?://([a-z0-9,-]+[.])*draw[.]io/.*"))
{
dom = referer.toLowerCase().substring(0,
referer.indexOf(".draw.io/") + 8);
}
else if (referer != null && referer.toLowerCase()
.matches("https?://([a-z0-9,-]+[.])*diagrams[.]net/.*"))
{
dom = referer.toLowerCase().substring(0,
referer.indexOf(".diagrams.net/") + 13);
}
else if (referer != null && referer.toLowerCase()
.matches("https?://([a-z0-9,-]+[.])*quipelements[.]com/.*"))
{
dom = referer.toLowerCase().substring(0,
referer.indexOf(".quipelements.com/") + 17);
}
// Enables Confluence/Jira proxy via referer or hardcoded user-agent (for old versions)
// UA refers to old FF on macOS so low risk and fixes requests from existing servers
else if ((referer != null
&& referer.equals("draw.io Proxy Confluence Server"))
|| (userAgent != null && userAgent.equals(
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.12; rv:50.0) Gecko/20100101 Firefox/50.0")))
{
dom = "";
}
return dom;
} | Base | 1 |
public void testPrivateKeyParsingSHA256()
throws IOException, ClassNotFoundException
{
XMSSMTParameters params = new XMSSMTParameters(20, 10, new SHA256Digest());
XMSSMT mt = new XMSSMT(params, new SecureRandom());
mt.generateKeys();
byte[] privateKey = mt.exportPrivateKey();
byte[] publicKey = mt.exportPublicKey();
mt.importState(privateKey, publicKey);
assertTrue(Arrays.areEqual(privateKey, mt.exportPrivateKey()));
} | Base | 1 |
public static boolean isTransparent(HColor back) {
if (back == TRANSPARENT) {
return true;
}
if (back instanceof HColorBackground && ((HColorBackground) back).getBack() == TRANSPARENT) {
return true;
}
if (back instanceof HColorSimple && ((HColorSimple) back).isTransparent()) {
return true;
}
return false;
} | Base | 1 |
private static void verifyPeerName(PGStream stream, Properties info, SSLSocket newConnection)
throws PSQLException {
HostnameVerifier hvn;
String sslhostnameverifier = PGProperty.SSL_HOSTNAME_VERIFIER.get(info);
if (sslhostnameverifier == null) {
hvn = PGjdbcHostnameVerifier.INSTANCE;
sslhostnameverifier = "PgjdbcHostnameVerifier";
} else {
try {
hvn = (HostnameVerifier) instantiate(sslhostnameverifier, info, false, null);
} catch (Exception e) {
throw new PSQLException(
GT.tr("The HostnameVerifier class provided {0} could not be instantiated.",
sslhostnameverifier),
PSQLState.CONNECTION_FAILURE, e);
}
}
if (hvn.verify(stream.getHostSpec().getHost(), newConnection.getSession())) {
return;
}
throw new PSQLException(
GT.tr("The hostname {0} could not be verified by hostnameverifier {1}.",
stream.getHostSpec().getHost(), sslhostnameverifier),
PSQLState.CONNECTION_FAILURE);
} | Class | 2 |
public void testSetRequestMethod() {
HttpURLConnection conn = createHttpUrlConnection(convertToUrl(TEST_URL), "", 0, "", "");
Utils.setRequestMethod(conn, Utils.RequestMethod.POST);
Assert.assertEquals(conn.getRequestMethod(), "POST");
} | Base | 1 |
public User updateUser(JpaUser user) throws NotFoundException, UnauthorizedException {
if (!UserDirectoryUtils.isCurrentUserAuthorizedHandleRoles(securityService, user.getRoles()))
throw new UnauthorizedException("The user is not allowed to set the admin role on other users");
JpaUser updateUser = UserDirectoryPersistenceUtil.findUser(user.getUsername(), user.getOrganization().getId(), emf);
if (updateUser == null) {
throw new NotFoundException("User " + user.getUsername() + " not found.");
}
logger.debug("updateUser({})", user.getUsername());
if (!UserDirectoryUtils.isCurrentUserAuthorizedHandleRoles(securityService, updateUser.getRoles()))
throw new UnauthorizedException("The user is not allowed to update an admin user");
String encodedPassword;
//only update Password if a value is set
if (StringUtils.isEmpty(user.getPassword())) {
encodedPassword = updateUser.getPassword();
} else {
// Update an JPA user with an encoded password.
encodedPassword = PasswordEncoder.encode(user.getPassword(), user.getUsername());
}
// Only save internal roles
Set<JpaRole> roles = UserDirectoryPersistenceUtil.saveRoles(filterRoles(user.getRoles()), emf);
JpaOrganization organization = UserDirectoryPersistenceUtil.saveOrganization(
(JpaOrganization) user.getOrganization(), emf);
JpaUser updatedUser = UserDirectoryPersistenceUtil.saveUser(
new JpaUser(user.getUsername(), encodedPassword, organization, user.getName(), user.getEmail(), user
.getProvider(), true, roles), emf);
cache.put(user.getUsername() + DELIMITER + organization.getId(), updatedUser);
updateGroupMembership(user);
return updatedUser;
} | Class | 2 |
protected static RootSearcher searchRootDirectory(Path fPath)
throws IOException {
RootSearcher rootSearcher = new RootSearcher();
Files.walkFileTree(fPath, rootSearcher);
return rootSearcher;
} | Base | 1 |
private void verifyRewrite(File dir) throws Exception {
File xml = new File(dir, "foo.xml");
assertEquals("<foo>" + encryptNew(TEST_KEY) + "</foo>".trim(),
FileUtils.readFileToString(xml).trim());
} | Class | 2 |
public void testClearResetsPseudoHeaderDivision() {
final HttpHeadersBase http2Headers = newHttp2Headers();
http2Headers.method(HttpMethod.POST);
http2Headers.set("some", "value");
http2Headers.clear();
http2Headers.method(HttpMethod.GET);
assertThat(http2Headers.names()).containsExactly(HttpHeaderNames.METHOD);
assertThat(http2Headers.getAll(HttpHeaderNames.METHOD)).containsExactly("GET");
} | Class | 2 |
private void checkCorsGetOrigin(final String in, final String out) throws ServletException, IOException {
prepareStandardInitialisation();
StringWriter sw = initRequestResponseMocks(
new Runnable() {
public void run() {
expect(request.getHeader("Origin")).andReturn(in);
expect(request.getRemoteHost()).andReturn("localhost");
expect(request.getRemoteAddr()).andReturn("127.0.0.1");
expect(request.getRequestURI()).andReturn("/jolokia/");
expect(request.getParameterMap()).andReturn(null);
}
},
new Runnable() {
public void run() {
response.setHeader("Access-Control-Allow-Origin", out);
response.setHeader("Access-Control-Allow-Credentials","true");
response.setCharacterEncoding("utf-8");
response.setContentType("text/plain");
response.setStatus(200);
}
}
);
expect(request.getPathInfo()).andReturn(HttpTestUtil.HEAP_MEMORY_GET_REQUEST);
expect(request.getParameter(ConfigKey.MIME_TYPE.getKeyValue())).andReturn("text/plain");
replay(request, response);
servlet.doGet(request, response);
servlet.destroy();
} | Compound | 4 |
public TList readListBegin() throws TException {
return new TList(readByte(), readI32());
} | Base | 1 |
public void create_withThreadPool() throws Exception {
final QueuedThreadPool threadPool = new QueuedThreadPool(100);
final JettyServerFactory jettyServerFactory = mock(JettyServerFactory.class);
final StaticFilesConfiguration staticFilesConfiguration = mock(StaticFilesConfiguration.class);
final Routes routes = mock(Routes.class);
when(jettyServerFactory.create(threadPool)).thenReturn(new Server(threadPool));
final EmbeddedJettyFactory embeddedJettyFactory = new EmbeddedJettyFactory(jettyServerFactory).withThreadPool(threadPool);
embeddedServer = embeddedJettyFactory.create(routes, staticFilesConfiguration, false);
embeddedServer.ignite("localhost", 8080, null, 0,0,0);
verify(jettyServerFactory, times(1)).create(threadPool);
verifyNoMoreInteractions(jettyServerFactory);
} | Base | 1 |
public void testReadBytesAndWriteBytesWithFileChannel() throws IOException {
File file = File.createTempFile("file-channel", ".tmp");
RandomAccessFile randomAccessFile = null;
try {
randomAccessFile = new RandomAccessFile(file, "rw");
FileChannel channel = randomAccessFile.getChannel();
// channelPosition should never be changed
long channelPosition = channel.position();
byte[] bytes = {'a', 'b', 'c', 'd'};
int len = bytes.length;
ByteBuf buffer = newBuffer(len);
buffer.resetReaderIndex();
buffer.resetWriterIndex();
buffer.writeBytes(bytes);
int oldReaderIndex = buffer.readerIndex();
assertEquals(len, buffer.readBytes(channel, 10, len));
assertEquals(oldReaderIndex + len, buffer.readerIndex());
assertEquals(channelPosition, channel.position());
ByteBuf buffer2 = newBuffer(len);
buffer2.resetReaderIndex();
buffer2.resetWriterIndex();
int oldWriterIndex = buffer2.writerIndex();
assertEquals(len, buffer2.writeBytes(channel, 10, len));
assertEquals(channelPosition, channel.position());
assertEquals(oldWriterIndex + len, buffer2.writerIndex());
assertEquals('a', buffer2.getByte(0));
assertEquals('b', buffer2.getByte(1));
assertEquals('c', buffer2.getByte(2));
assertEquals('d', buffer2.getByte(3));
buffer.release();
buffer2.release();
} finally {
if (randomAccessFile != null) {
randomAccessFile.close();
}
file.delete();
}
} | Base | 1 |
public static byte[] decryptWithConcatKDF(final JWEHeader header,
final SecretKey secretKey,
final Base64URL encryptedKey,
final Base64URL iv,
final Base64URL cipherText,
final Base64URL authTag,
final Provider ceProvider,
final Provider macProvider)
throws JOSEException {
byte[] epu = null;
if (header.getCustomParam("epu") instanceof String) {
epu = new Base64URL((String)header.getCustomParam("epu")).decode();
}
byte[] epv = null;
if (header.getCustomParam("epv") instanceof String) {
epv = new Base64URL((String)header.getCustomParam("epv")).decode();
}
SecretKey cekAlt = LegacyConcatKDF.generateCEK(secretKey, header.getEncryptionMethod(), epu, epv);
final byte[] plainText = AESCBC.decrypt(cekAlt, iv.decode(), cipherText.decode(), ceProvider);
SecretKey cik = LegacyConcatKDF.generateCIK(secretKey, header.getEncryptionMethod(), epu, epv);
String macInput = header.toBase64URL().toString() + "." +
encryptedKey.toString() + "." +
iv.toString() + "." +
cipherText.toString();
byte[] mac = HMAC.compute(cik, macInput.getBytes(), macProvider);
if (! ConstantTimeUtils.areEqual(authTag.decode(), mac)) {
throw new JOSEException("HMAC integrity check failed");
}
return plainText;
} | Base | 1 |
public int encryptWithAd(byte[] ad, byte[] plaintext, int plaintextOffset,
byte[] ciphertext, int ciphertextOffset, int length) throws ShortBufferException {
int space;
if (ciphertextOffset > ciphertext.length)
space = 0;
else
space = ciphertext.length - ciphertextOffset;
if (!haskey) {
// The key is not set yet - return the plaintext as-is.
if (length > space)
throw new ShortBufferException();
if (plaintext != ciphertext || plaintextOffset != ciphertextOffset)
System.arraycopy(plaintext, plaintextOffset, ciphertext, ciphertextOffset, length);
return length;
}
if (space < 16 || length > (space - 16))
throw new ShortBufferException();
setup(ad);
encrypt(plaintext, plaintextOffset, ciphertext, ciphertextOffset, length);
poly.update(ciphertext, ciphertextOffset, length);
finish(ad, length);
System.arraycopy(polyKey, 0, ciphertext, ciphertextOffset + length, 16);
return length + 16;
} | Base | 1 |
private void returnPrincipals(Subject subject, PrintWriter out) {
Map<String, Object> answer = new HashMap<String, Object>();
List<Object> principals = new ArrayList<Object>();
for (Principal principal : subject.getPrincipals()) {
Map<String, String> data = new HashMap<String, String>();
data.put("type", principal.getClass().getName());
data.put("name", principal.getName());
principals.add(data);
}
List<Object> credentials = new ArrayList<Object>();
for (Object credential : subject.getPublicCredentials()) {
Map<String, Object> data = new HashMap<String, Object>();
data.put("type", credential.getClass().getName());
data.put("credential", credential);
}
answer.put("principals", principals);
answer.put("credentials", credentials);
ServletHelpers.writeObject(converters, options, out, answer);
} | Compound | 4 |
public AuthorizationCodeRequestUrl newAuthorizationUrl() {
return new AuthorizationCodeRequestUrl(authorizationServerEncodedUrl, clientId).setScopes(
scopes);
} | Class | 2 |
private void visitorPermission(Invocation ai) {
ai.invoke();
String templateName = ai.getReturnValue();
if (templateName == null) {
return;
}
GlobalResourceHandler.printUserTime("Template before");
String templatePath = TemplateHelper.fullTemplateInfo(ai.getController(), true);
GlobalResourceHandler.printUserTime("Template after");
TemplateVO templateVO = new TemplateService().getTemplateVO(JFinal.me().getContextPath(), new File(PathKit.getWebRootPath() + templatePath));
String ext = ZrLogUtil.getViewExt(templateVO.getViewType());
if (ai.getController().getAttr("log") != null) {
ai.getController().setAttr("pageLevel", 1);
} else if (ai.getController().getAttr("data") != null) {
if ("/".equals(ai.getActionKey()) && new File(PathKit.getWebRootPath() + templatePath + "/" + templateName + ext).exists()) {
ai.getController().setAttr("pageLevel", 2);
} else {
templateName = "page";
ai.getController().setAttr("pageLevel", 1);
}
} else {
ai.getController().setAttr("pageLevel", 2);
}
fullDevData(ai.getController());
ai.getController().render(templatePath + "/" + templateName + ext);
} | Base | 1 |
public Argument<Session> argumentType() {
return Argument.of(Session.class);
} | Class | 2 |
public void testPseudoHeadersMustComeFirstWhenIterating() {
final HttpHeadersBase headers = newHttp2Headers();
verifyPseudoHeadersFirst(headers);
verifyAllPseudoHeadersPresent(headers);
} | Class | 2 |
private void handle(ServletRequestHandler pReqHandler,HttpServletRequest pReq, HttpServletResponse pResp) throws IOException {
JSONAware json = null;
try {
// Check access policy
requestHandler.checkClientIPAccess(pReq.getRemoteHost(),pReq.getRemoteAddr());
// Remember the agent URL upon the first request. Needed for discovery
updateAgentUrlIfNeeded(pReq);
// Dispatch for the proper HTTP request method
json = pReqHandler.handleRequest(pReq,pResp);
} catch (Throwable exp) {
json = requestHandler.handleThrowable(
exp instanceof RuntimeMBeanException ? ((RuntimeMBeanException) exp).getTargetException() : exp);
} finally {
setCorsHeader(pReq, pResp);
String callback = pReq.getParameter(ConfigKey.CALLBACK.getKeyValue());
String answer = json != null ?
json.toJSONString() :
requestHandler.handleThrowable(new Exception("Internal error while handling an exception")).toJSONString();
if (callback != null) {
// Send a JSONP response
sendResponse(pResp, "text/javascript", callback + "(" + answer + ");");
} else {
sendResponse(pResp, getMimeType(pReq),answer);
}
}
} | Compound | 4 |
public OHttpSession[] getSessions() {
acquireSharedLock();
try {
return (OHttpSession[]) sessions.values().toArray(new OHttpSession[sessions.size()]);
} finally {
releaseSharedLock();
}
}
| Class | 2 |
void shouldNotDecodeSlash() {
final PathAndQuery res = PathAndQuery.parse("%2F?%2F");
// Do not accept a relative path.
assertThat(res).isNull();
final PathAndQuery res1 = PathAndQuery.parse("/%2F?%2F");
assertThat(res1).isNotNull();
assertThat(res1.path()).isEqualTo("/%2F");
assertThat(res1.query()).isEqualTo("%2F");
final PathAndQuery pathOnly = PathAndQuery.parse("/foo%2F");
assertThat(pathOnly).isNotNull();
assertThat(pathOnly.path()).isEqualTo("/foo%2F");
assertThat(pathOnly.query()).isNull();
final PathAndQuery queryOnly = PathAndQuery.parse("/?%2f=%2F");
assertThat(queryOnly).isNotNull();
assertThat(queryOnly.path()).isEqualTo("/");
assertThat(queryOnly.query()).isEqualTo("%2F=%2F");
} | Base | 1 |
public void setFeature(String name, boolean value) throws SAXException {
getXMLReader().setFeature(name, value);
} | Base | 1 |
void sharp() {
final PathAndQuery res = PathAndQuery.parse("/#?a=b#1");
assertThat(res).isNotNull();
assertThat(res.path()).isEqualTo("/#");
assertThat(res.query()).isEqualTo("a=b#1");
// '%23' in a query string should never be decoded into '#'.
final PathAndQuery res2 = PathAndQuery.parse("/%23?a=b%231");
assertThat(res2).isNotNull();
assertThat(res2.path()).isEqualTo("/#");
assertThat(res2.query()).isEqualTo("a=b%231");
} | Base | 1 |
private boolean handleJid(Invite invite) {
List<Contact> contacts = xmppConnectionService.findContacts(invite.getJid(), invite.account);
if (invite.isAction(XmppUri.ACTION_JOIN)) {
Conversation muc = xmppConnectionService.findFirstMuc(invite.getJid());
if (muc != null) {
switchToConversation(muc, invite.getBody());
return true;
} else {
showJoinConferenceDialog(invite.getJid().asBareJid().toString());
return false;
}
} else if (contacts.size() == 0) {
showCreateContactDialog(invite.getJid().toString(), invite);
return false;
} else if (contacts.size() == 1) {
Contact contact = contacts.get(0);
if (!invite.isSafeSource() && invite.hasFingerprints()) {
displayVerificationWarningDialog(contact, invite);
} else {
if (invite.hasFingerprints()) {
if (xmppConnectionService.verifyFingerprints(contact, invite.getFingerprints())) {
Toast.makeText(this, R.string.verified_fingerprints, Toast.LENGTH_SHORT).show();
}
}
if (invite.account != null) {
xmppConnectionService.getShortcutService().report(contact);
}
switchToConversation(contact, invite.getBody());
}
return true;
} else {
if (mMenuSearchView != null) {
mMenuSearchView.expandActionView();
mSearchEditText.setText("");
mSearchEditText.append(invite.getJid().toString());
filter(invite.getJid().toString());
} else {
mInitialSearchValue.push(invite.getJid().toString());
}
return true;
}
} | Class | 2 |
void resetPasswordUnexistingUser() throws Exception
{
when(this.userReference.toString()).thenReturn("user:Foobar");
when(this.userManager.exists(this.userReference)).thenReturn(false);
String exceptionMessage = "User [user:Foobar] doesn't exist";
when(this.localizationManager.getTranslationPlain("xe.admin.passwordReset.error.noUser",
"user:Foobar")).thenReturn(exceptionMessage);
ResetPasswordException resetPasswordException = assertThrows(ResetPasswordException.class,
() -> this.resetPasswordManager.resetPassword(this.userReference, "some password"));
assertEquals(exceptionMessage, resetPasswordException.getMessage());
} | Base | 1 |
public static SecretKey deriveSharedKey(final JWEHeader header,
final SecretKey Z,
final ConcatKDF concatKDF)
throws JOSEException {
final int sharedKeyLength = sharedKeyLength(header.getAlgorithm(), header.getEncryptionMethod());
// Set the alg ID for the concat KDF
AlgorithmMode algMode = resolveAlgorithmMode(header.getAlgorithm());
final String algID;
if (algMode == AlgorithmMode.DIRECT) {
// algID = enc
algID = header.getEncryptionMethod().getName();
} else if (algMode == AlgorithmMode.KW) {
// algID = alg
algID = header.getAlgorithm().getName();
} else {
throw new JOSEException("Unsupported JWE ECDH algorithm mode: " + algMode);
}
return concatKDF.deriveKey(
Z,
sharedKeyLength,
ConcatKDF.encodeDataWithLength(algID.getBytes(Charset.forName("ASCII"))),
ConcatKDF.encodeDataWithLength(header.getAgreementPartyUInfo()),
ConcatKDF.encodeDataWithLength(header.getAgreementPartyVInfo()),
ConcatKDF.encodeIntData(sharedKeyLength),
ConcatKDF.encodeNoData());
} | Base | 1 |
public CsrfTokenHandler(final Form< ? > form)
{
form.add(csrfTokenField = new HiddenField<String>("csrfToken", Model.of(getCsrfSessionToken())));
} | Compound | 4 |
public void translate(ServerOpenHorseWindowPacket packet, GeyserSession session) {
Entity entity = session.getEntityCache().getEntityByJavaId(packet.getEntityId());
if (entity == null) {
return;
}
UpdateEquipPacket updateEquipPacket = new UpdateEquipPacket();
updateEquipPacket.setWindowId((short) packet.getWindowId());
updateEquipPacket.setWindowType((short) ContainerType.HORSE.getId());
updateEquipPacket.setUniqueEntityId(entity.getGeyserId());
NbtMapBuilder builder = NbtMap.builder();
List<NbtMap> slots = new ArrayList<>();
InventoryTranslator inventoryTranslator;
if (entity instanceof LlamaEntity) {
inventoryTranslator = new LlamaInventoryTranslator(packet.getNumberOfSlots());
slots.add(CARPET_SLOT);
} else if (entity instanceof ChestedHorseEntity) {
inventoryTranslator = new DonkeyInventoryTranslator(packet.getNumberOfSlots());
slots.add(SADDLE_SLOT);
} else {
inventoryTranslator = new HorseInventoryTranslator(packet.getNumberOfSlots());
slots.add(SADDLE_SLOT);
slots.add(ARMOR_SLOT);
}
// Build the NbtMap that sets the icons for Bedrock (e.g. sets the saddle outline on the saddle slot)
builder.putList("slots", NbtType.COMPOUND, slots);
updateEquipPacket.setTag(builder.build());
session.sendUpstreamPacket(updateEquipPacket);
session.setInventoryTranslator(inventoryTranslator);
InventoryUtils.openInventory(session, new Container(entity.getMetadata().getString(EntityData.NAMETAG), packet.getWindowId(), packet.getNumberOfSlots(), null, session.getPlayerInventory()));
} | Class | 2 |
ReservedChar(int rawChar, String percentEncodedChar, byte marker) {
this.rawChar = rawChar;
this.percentEncodedChar = percentEncodedChar;
this.marker = marker;
} | Base | 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");
} | Class | 2 |
public CorsChecker(Document pDoc) {
NodeList corsNodes = pDoc.getElementsByTagName("cors");
if (corsNodes.getLength() > 0) {
patterns = new ArrayList<Pattern>();
for (int i = 0; i < corsNodes.getLength(); i++) {
Node corsNode = corsNodes.item(i);
NodeList nodes = corsNode.getChildNodes();
for (int j = 0;j <nodes.getLength();j++) {
Node node = nodes.item(j);
if (node.getNodeType() != Node.ELEMENT_NODE) {
continue;
}
assertNodeName(node,"allow-origin");
String p = node.getTextContent().trim().toLowerCase();
p = Pattern.quote(p).replace("*","\\E.*\\Q");
patterns.add(Pattern.compile("^" + p + "$"));
}
}
}
} | Compound | 4 |
void checkVerificationCode() throws Exception
{
when(this.userManager.exists(this.userReference)).thenReturn(true);
InternetAddress email = new InternetAddress("[email protected]");
when(this.userProperties.getEmail()).thenReturn(email);
String verificationCode = "abcd1245";
BaseObject xObject = mock(BaseObject.class);
when(this.userDocument
.getXObject(DefaultResetPasswordManager.RESET_PASSWORD_REQUEST_CLASS_REFERENCE))
.thenReturn(xObject);
String encodedVerificationCode = "encodedVerificationCode";
when(xObject.getStringValue(DefaultResetPasswordManager.VERIFICATION_PROPERTY))
.thenReturn(encodedVerificationCode);
BaseClass baseClass = mock(BaseClass.class);
when(xObject.getXClass(context)).thenReturn(baseClass);
PasswordClass passwordClass = mock(PasswordClass.class);
when(baseClass.get(DefaultResetPasswordManager.VERIFICATION_PROPERTY)).thenReturn(passwordClass);
when(passwordClass.getEquivalentPassword(encodedVerificationCode, verificationCode))
.thenReturn(encodedVerificationCode);
String newVerificationCode = "foobartest";
when(xWiki.generateRandomString(30)).thenReturn(newVerificationCode);
String saveComment = "Save new verification code";
when(this.localizationManager
.getTranslationPlain("xe.admin.passwordReset.step2.versionComment.changeValidationKey"))
.thenReturn(saveComment);
DefaultResetPasswordRequestResponse expected =
new DefaultResetPasswordRequestResponse(this.userReference, email,
newVerificationCode);
assertEquals(expected, this.resetPasswordManager.checkVerificationCode(this.userReference, verificationCode));
verify(this.xWiki).saveDocument(this.userDocument, saveComment, true, context);
} | Base | 1 |
public void translate(ServerStopSoundPacket packet, GeyserSession session) {
// Runs if all sounds are stopped
if (packet.getSound() == null) {
StopSoundPacket stopPacket = new StopSoundPacket();
stopPacket.setStoppingAllSound(true);
stopPacket.setSoundName("");
session.sendUpstreamPacket(stopPacket);
return;
}
String packetSound;
if (packet.getSound() instanceof BuiltinSound) {
packetSound = ((BuiltinSound) packet.getSound()).getName();
} else if (packet.getSound() instanceof CustomSound) {
packetSound = ((CustomSound) packet.getSound()).getName();
} else {
session.getConnector().getLogger().debug("Unknown sound packet, we were unable to map this. " + packet.toString());
return;
}
SoundMapping soundMapping = Registries.SOUNDS.get(packetSound.replace("minecraft:", ""));
session.getConnector().getLogger()
.debug("[StopSound] Sound mapping " + packetSound + " -> "
+ soundMapping + (soundMapping == null ? "[not found]" : "")
+ " - " + packet.toString());
String playsound;
if (soundMapping == null || soundMapping.getPlaysound() == null) {
// no mapping
session.getConnector().getLogger()
.debug("[StopSound] Defaulting to sound server gave us.");
playsound = packetSound;
} else {
playsound = soundMapping.getPlaysound();
}
StopSoundPacket stopSoundPacket = new StopSoundPacket();
stopSoundPacket.setSoundName(playsound);
// packet not mapped in the library
stopSoundPacket.setStoppingAllSound(false);
session.sendUpstreamPacket(stopSoundPacket);
session.getConnector().getLogger().debug("[StopSound] Packet sent - " + packet.toString() + " --> " + stopSoundPacket);
} | Class | 2 |
public boolean isValid(String value, ConstraintValidatorContext context) {
if (StringUtils.isEmpty(value)) {
return true;
}
try {
Pattern.compile(value);
return true;
} catch (Exception ex) {
String errorMessage = String.format("URL parameter '%s' is not a valid regexp", value);
LOG.warn(errorMessage);
context.buildConstraintViolationWithTemplate(errorMessage).addConstraintViolation();
}
return false;
} | Class | 2 |
public JiffleRuntime getRuntimeInstance(Jiffle.RuntimeModel model) throws
it.geosolutions.jaiext.jiffle.JiffleException {
return createRuntimeInstance(model, getRuntimeBaseClass(model), false);
} | Base | 1 |
public boolean checkObjectExecutePermission(Class clazz, String methodName)
{
if (Class.class.isAssignableFrom(clazz) && methodName != null && this.secureClassMethods.contains(methodName)) {
return true;
} else {
return super.checkObjectExecutePermission(clazz, methodName);
}
} | Class | 2 |
public void violationMessagesAreEscaped() {
assertThat(ConstraintViolations.format(validator.validate(new InjectionExample()))).containsExactly(
" ${'value'}",
"${'property'} ${'value'}",
"${'property'}[${'key'}] ${'value'}",
"${'property'}[1] ${'value'}"
);
assertThat(TestLoggerFactory.getAllLoggingEvents()).isEmpty();
} | Class | 2 |
final void set(CharSequence name, Iterable<String> values) {
final AsciiString normalizedName = normalizeName(name);
requireNonNull(values, "values");
final int h = normalizedName.hashCode();
final int i = index(h);
remove0(h, i, normalizedName);
for (String v : values) {
requireNonNullElement(values, v);
add0(h, i, normalizedName, v);
}
} | Class | 2 |
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));
} | Class | 2 |
public Player(String title, ISkinParam skinParam, TimingRuler ruler, boolean compact) {
this.skinParam = skinParam;
this.compact = compact;
this.ruler = ruler;
this.title = Display.getWithNewlines(title);
} | Base | 1 |
public void headersWithDifferentNamesAndValuesShouldNotBeEquivalent() {
final HttpHeadersBase h1 = newEmptyHeaders();
h1.set("name1", "value1");
final HttpHeadersBase h2 = newEmptyHeaders();
h2.set("name2", "value2");
assertThat(h1).isNotEqualTo(h2);
assertThat(h2).isNotEqualTo(h1);
assertThat(h1).isEqualTo(h1);
assertThat(h2).isEqualTo(h2);
} | Class | 2 |
public void nullHeaderNameNotAllowed() {
newEmptyHeaders().add(null, "foo");
} | Class | 2 |
private static PathAndQuery splitPathAndQuery(@Nullable final String pathAndQuery) {
final Bytes path;
final Bytes query;
if (pathAndQuery == null) {
return ROOT_PATH_QUERY;
}
// Split by the first '?'.
final int queryPos = pathAndQuery.indexOf('?');
if (queryPos >= 0) {
if ((path = decodePercentsAndEncodeToUtf8(
pathAndQuery, 0, queryPos, true)) == null) {
return null;
}
if ((query = decodePercentsAndEncodeToUtf8(
pathAndQuery, queryPos + 1, pathAndQuery.length(), false)) == null) {
return null;
}
} else {
if ((path = decodePercentsAndEncodeToUtf8(
pathAndQuery, 0, pathAndQuery.length(), true)) == null) {
return null;
}
query = null;
}
if (path.data[0] != '/') {
// Do not accept a relative path.
return null;
}
// Reject the prohibited patterns.
if (pathContainsDoubleDots(path)) {
return null;
}
return new PathAndQuery(encodeToPercents(path, true),
query != null ? encodeToPercents(query, false) : null);
} | Base | 1 |
public static int sharedKeyLength(final JWEAlgorithm alg, final EncryptionMethod enc)
throws JOSEException {
if (alg.equals(JWEAlgorithm.ECDH_ES)) {
int length = enc.cekBitLength();
if (length == 0) {
throw new JOSEException("Unsupported JWE encryption method " + enc);
}
return length;
} else if (alg.equals(JWEAlgorithm.ECDH_ES_A128KW)) {
return 128;
} else if (alg.equals(JWEAlgorithm.ECDH_ES_A192KW)) {
return 192;
} else if (alg.equals(JWEAlgorithm.ECDH_ES_A256KW)) {
return 256;
} else {
throw new JOSEException(AlgorithmSupportMessage.unsupportedJWEAlgorithm(
alg, ECDHCryptoProvider.SUPPORTED_ALGORITHMS));
}
} | Base | 1 |
private XMLGregorianCalendar toXMLGregorianCalendar(ZonedDateTime instant) {
if (instant == null) {
return null;
}
return new XMLGregorianCalendarImpl(GregorianCalendar.from(instant));
} | Base | 1 |
public void translate(ServerSpawnExpOrbPacket packet, GeyserSession session) {
Vector3f position = Vector3f.from(packet.getX(), packet.getY(), packet.getZ());
Entity entity = new ExpOrbEntity(
packet.getExp(), packet.getEntityId(), session.getEntityCache().getNextEntityId().incrementAndGet(),
EntityType.EXPERIENCE_ORB, position, Vector3f.ZERO, Vector3f.ZERO
);
session.getEntityCache().spawnEntity(entity);
} | Class | 2 |
public void translate(ServerPlayerChangeHeldItemPacket packet, GeyserSession session) {
PlayerHotbarPacket hotbarPacket = new PlayerHotbarPacket();
hotbarPacket.setContainerId(0);
hotbarPacket.setSelectedHotbarSlot(packet.getSlot());
hotbarPacket.setSelectHotbarSlot(true);
session.sendUpstreamPacket(hotbarPacket);
session.getPlayerInventory().setHeldItemSlot(packet.getSlot());
} | Class | 2 |
private static boolean doesNotContainFileColon(String path) {
return !path.contains("file:");
} | Base | 1 |
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);
} | Class | 2 |
public void translate(ServerRemoveEntitiesPacket packet, GeyserSession session) {
for (int entityId : packet.getEntityIds()) {
Entity entity = session.getEntityCache().getEntityByJavaId(entityId);
if (entity != null) {
session.getEntityCache().removeEntity(entity, false);
}
}
} | Class | 2 |
final void add(CharSequence name, String value) {
final AsciiString normalizedName = normalizeName(name);
requireNonNull(value, "value");
final int h = normalizedName.hashCode();
final int i = index(h);
add0(h, i, normalizedName, value);
} | Class | 2 |
public boolean isCorsAccessAllowed(String pOrigin) {
return restrictor.isCorsAccessAllowed(pOrigin);
} | Compound | 4 |
public void multipleTestingOfSameClass() throws Exception {
assertThat(ConstraintViolations.format(validator.validate(new CorrectExample())))
.isEmpty();
assertThat(ConstraintViolations.format(validator.validate(new CorrectExample())))
.isEmpty();
assertThat(TestLoggerFactory.getAllLoggingEvents())
.isEmpty();
} | Class | 2 |
public void create_withNullThreadPool() throws Exception {
final JettyServerFactory jettyServerFactory = mock(JettyServerFactory.class);
final StaticFilesConfiguration staticFilesConfiguration = mock(StaticFilesConfiguration.class);
final Routes routes = mock(Routes.class);
when(jettyServerFactory.create(100,10,10000)).thenReturn(new Server());
final EmbeddedJettyFactory embeddedJettyFactory = new EmbeddedJettyFactory(jettyServerFactory).withThreadPool(null);
embeddedServer = embeddedJettyFactory.create(routes, staticFilesConfiguration, false);
embeddedServer.ignite("localhost", 8080, null, 100,10,10000);
verify(jettyServerFactory, times(1)).create(100,10,10000);
verifyNoMoreInteractions(jettyServerFactory);
} | Base | 1 |
public List<String> getShellCommandLine( String[] arguments )
{
List<String> commandLine = new ArrayList<String>();
if ( getShellCommand() != null )
{
commandLine.add( getShellCommand() );
}
if ( getShellArgs() != null )
{
commandLine.addAll( getShellArgsList() );
}
commandLine.addAll( getCommandLine( getExecutable(), arguments ) );
return commandLine;
} | Base | 1 |
public void translate(ServerSetTitleTextPacket packet, GeyserSession session) {
String text;
if (packet.getText() == null) { //TODO 1.17 can this happen?
text = " ";
} else {
text = MessageTranslator.convertMessage(packet.getText(), session.getLocale());
}
SetTitlePacket titlePacket = new SetTitlePacket();
titlePacket.setType(SetTitlePacket.Type.TITLE);
titlePacket.setText(text);
titlePacket.setXuid("");
titlePacket.setPlatformOnlineId("");
session.sendUpstreamPacket(titlePacket);
} | Class | 2 |
public TMap readMapBegin() throws TException {
int size = readVarint32();
byte keyAndValueType = size == 0 ? 0 : readByte();
return new TMap(
getTType((byte) (keyAndValueType >> 4)), getTType((byte) (keyAndValueType & 0xf)), size);
} | Base | 1 |
List<String> cleanForKeySlow(String key) {
key = StringUtils.trin(StringUtils.goLowerCase(key));
key = key.replaceAll("_|\\.|\\s", "");
// key = replaceSmart(key, "partition", "package");
key = replaceSmart(key, "sequenceparticipant", "participant");
key = replaceSmart(key, "sequenceactor", "actor");
key = key.replaceAll("activityarrow", "arrow");
key = key.replaceAll("objectarrow", "arrow");
key = key.replaceAll("classarrow", "arrow");
key = key.replaceAll("componentarrow", "arrow");
key = key.replaceAll("statearrow", "arrow");
key = key.replaceAll("usecasearrow", "arrow");
key = key.replaceAll("sequencearrow", "arrow");
key = key.replaceAll("align$", "alignment");
final Matcher2 mm = stereoPattern.matcher(key);
final List<String> result = new ArrayList<>();
while (mm.find()) {
final String s = mm.group(1);
result.add(key.replaceAll(stereoPatternString, "") + "<<" + s + ">>");
}
if (result.size() == 0)
result.add(key);
return Collections.unmodifiableList(result);
} | Base | 1 |
public void newDocumentFromURLTemplateProviderSpecifiedNonTerminal() throws Exception
{
// new document = xwiki:X.Y
DocumentReference documentReference = new DocumentReference("xwiki", "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);
// 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,
false);
// Run the action
String result = action.render(context);
// The tests are below this line!
// Verify null is returned (this means the response has been returned)
assertNull(result);
// Note: We are creating the document X.Y as terminal 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);
} | Class | 2 |
public String compact() {
return id.replaceAll("/", "-").replaceAll("\\\\", "-");
} | Class | 2 |
public void translate(ServerKeepAlivePacket packet, GeyserSession session) {
if (!session.getConnector().getConfig().isForwardPlayerPing()) {
return;
}
NetworkStackLatencyPacket latencyPacket = new NetworkStackLatencyPacket();
latencyPacket.setFromServer(true);
latencyPacket.setTimestamp(packet.getPingId() * 1000);
session.sendUpstreamPacket(latencyPacket);
} | Class | 2 |
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);
}
} | Class | 2 |
private JsonNode yamlPathToJson(Path path) throws IOException {
Yaml reader = new Yaml();
ObjectMapper mapper = new ObjectMapper();
Path p;
try (InputStream in = Files.newInputStream(path)) {
return mapper.valueToTree(reader.load(in));
}
} | Base | 1 |
public Claims validateToken(String token) throws AuthenticationException {
try {
RsaKeyUtil rsaKeyUtil = new RsaKeyUtil();
PublicKey publicKey = rsaKeyUtil.fromPemEncoded(keycloakPublicKey);
return (Claims) Jwts.parser().setSigningKey(publicKey).parse(token.replace("Bearer ", "")).getBody();
} catch (Exception e){
throw new AuthenticationException(String.format("Failed to check user authorization for token: %s", token), e);
}
} | Base | 1 |
public HomePageConfig loadConfigFor(Identity identity) {
String userName = identity.getName();
HomePageConfig retVal = null;
File configFile = getConfigFile(userName);
if (!configFile.exists()) {
// config file does not exist! create one, init the defaults, save it.
retVal = loadAndSaveDefaults(identity);
} else {
// file exists, load it with XStream, resolve version
try {
Object tmp = homeConfigXStream.fromXML(configFile);
if (tmp instanceof HomePageConfig) {
retVal = (HomePageConfig)tmp;
if(retVal.resolveVersionIssues()) {
saveConfigTo(identity, retVal);
}
}
} catch (Exception e) {
log.error("Error while loading homepage config from path::" + configFile.getAbsolutePath() + ", fallback to default configuration",
e);
FileUtils.deleteFile(configFile);
retVal = loadAndSaveDefaults(identity);
// show message to user
}
}
return retVal;
} | Base | 1 |
public void testSelectByType() {
JWKSelector selector = new JWKSelector(new JWKMatcher.Builder().keyType(KeyType.RSA).build());
List<JWK> keyList = new ArrayList<>();
keyList.add(new RSAKey.Builder(new Base64URL("n"), new Base64URL("e")).keyID("1").build());
keyList.add(new ECKey.Builder(ECKey.Curve.P_256, new Base64URL("x"), new Base64URL("y")).keyID("2").build());
JWKSet jwkSet = new JWKSet(keyList);
List<JWK> matches = selector.select(jwkSet);
RSAKey key1 = (RSAKey)matches.get(0);
assertEquals(KeyType.RSA, key1.getKeyType());
assertEquals("1", key1.getKeyID());
assertEquals(1, matches.size());
} | Base | 1 |
public String getOrderBy() {
return orderBy;
} | Base | 1 |
public void testSetContentFromFile() throws Exception {
TestHttpData test = new TestHttpData("test", UTF_8, 0);
try {
File tmpFile = File.createTempFile(UUID.randomUUID().toString(), ".tmp");
tmpFile.deleteOnExit();
FileOutputStream fos = new FileOutputStream(tmpFile);
byte[] bytes = new byte[4096];
PlatformDependent.threadLocalRandom().nextBytes(bytes);
try {
fos.write(bytes);
fos.flush();
} finally {
fos.close();
}
test.setContent(tmpFile);
ByteBuf buf = test.getByteBuf();
assertEquals(buf.readerIndex(), 0);
assertEquals(buf.writerIndex(), bytes.length);
assertArrayEquals(bytes, test.get());
assertArrayEquals(bytes, ByteBufUtil.getBytes(buf));
} finally {
//release the ByteBuf
test.delete();
}
} | Base | 1 |
public Optional<URL> getResource(String path) {
boolean isDirectory = isDirectory(path);
if (!isDirectory) {
URL url = classLoader.getResource(prefixPath(path));
return Optional.ofNullable(url);
}
return Optional.empty();
} | Base | 1 |
void testDecodePath() throws Exception {
// Fast path
final String pathThatDoesNotNeedDecode = "/foo_bar_baz";
assertThat(decodePath(pathThatDoesNotNeedDecode)).isSameAs(pathThatDoesNotNeedDecode);
// Slow path
assertThat(decodePath("/foo%20bar\u007fbaz")).isEqualTo("/foo bar\u007fbaz");
assertThat(decodePath("/%C2%A2")).isEqualTo("/¢"); // Valid UTF-8 sequence
assertThat(decodePath("/%20\u0080")).isEqualTo("/ �"); // Unallowed character
assertThat(decodePath("/%")).isEqualTo("/�"); // No digit
assertThat(decodePath("/%1")).isEqualTo("/�"); // Only a single digit
assertThat(decodePath("/%G0")).isEqualTo("/�"); // First digit is not hex.
assertThat(decodePath("/%0G")).isEqualTo("/�"); // Second digit is not hex.
assertThat(decodePath("/%C3%28")).isEqualTo("/�("); // Invalid UTF-8 sequence
} | Base | 1 |
public EfficiencyStatement getUserEfficiencyStatementByKey(Long key) {
String query = "select statement from effstatement as statement where statement.key=:key";
List<UserEfficiencyStatementImpl> statement = dbInstance.getCurrentEntityManager()
.createQuery(query, UserEfficiencyStatementImpl.class)
.setParameter("key", key)
.getResultList();
if(statement.isEmpty() || !StringHelper.containsNonWhitespace(statement.get(0).getStatementXml())) {
return null;
}
return (EfficiencyStatement)xstream.fromXML(statement.get(0).getStatementXml());
} | Base | 1 |
public void initWithAgentDiscoveryAndUrlCreationAfterGet() throws ServletException, IOException {
checkMulticastAvailable();
prepareStandardInitialisation(ConfigKey.DISCOVERY_ENABLED.getKeyValue(), "true");
try {
StringWriter sw = initRequestResponseMocks();
expect(request.getPathInfo()).andReturn(HttpTestUtil.HEAP_MEMORY_GET_REQUEST);
expect(request.getParameter(ConfigKey.MIME_TYPE.getKeyValue())).andReturn("text/plain");
String url = "http://pirx:9876/jolokia";
StringBuffer buf = new StringBuffer();
buf.append(url).append(HttpTestUtil.HEAP_MEMORY_GET_REQUEST);
expect(request.getRequestURL()).andReturn(buf);
expect(request.getRequestURI()).andReturn(buf.toString());
expect(request.getContextPath()).andReturn("/jolokia");
expect(request.getAuthType()).andReturn("BASIC");
replay(request, response);
servlet.doGet(request, response);
assertTrue(sw.toString().contains("used"));
JolokiaDiscovery discovery = new JolokiaDiscovery("test",LogHandler.QUIET);
List<JSONObject> in = discovery.lookupAgents();
assertTrue(in.size() > 0);
for (JSONObject json : in) {
if (json.get("url") != null && json.get("url").equals(url)) {
assertTrue((Boolean) json.get("secured"));
return;
}
}
fail("Failed, because no message had an URL");
} finally {
servlet.destroy();
}
} | Compound | 4 |
public void checkAccess(ThreadGroup g) {
if (RobocodeProperties.isSecurityOff()) {
return;
}
Thread c = Thread.currentThread();
if (isSafeThread(c)) {
return;
}
super.checkAccess(g);
final ThreadGroup cg = c.getThreadGroup();
if (cg == null) {
// What the heck is going on here? JDK 1.3 is sending me a dead thread.
// This crashes the entire jvm if I don't return here.
return;
}
// Bug fix #382 Unable to run robocode.bat -- Access Control Exception
if ("SeedGenerator Thread".equals(c.getName()) && "SeedGenerator ThreadGroup".equals(cg.getName())) {
return; // The SeedGenerator might create a thread, which needs to be silently ignored
}
IHostedThread robotProxy = threadManager.getLoadedOrLoadingRobotProxy(c);
if (robotProxy == null) {
throw new AccessControlException("Preventing " + c.getName() + " from access to " + g.getName());
}
if (cg.activeCount() > 5) {
String message = "Robots are only allowed to create up to 5 threads!";
robotProxy.punishSecurityViolation(message);
throw new AccessControlException(message);
}
} | Class | 2 |
private static AsciiString normalizeName(CharSequence name) {
checkArgument(requireNonNull(name, "name").length() > 0, "name is empty.");
return HttpHeaderNames.of(name);
} | Class | 2 |
public void testPreserveSingleQuotesOnArgument()
{
Shell sh = newShell();
sh.setWorkingDirectory( "/usr/bin" );
sh.setExecutable( "chmod" );
String[] args = { "\'some arg with spaces\'" };
List shellCommandLine = sh.getShellCommandLine( args );
String cli = StringUtils.join( shellCommandLine.iterator(), " " );
System.out.println( cli );
assertTrue( cli.endsWith( args[0] ) );
} | Base | 1 |
public void testWhitespaceBeforeTransferEncoding02() {
String requestStr = "POST / HTTP/1.1" +
" Transfer-Encoding : chunked\r\n" +
"Host: target.com" +
"Content-Length: 65\r\n\r\n" +
"0\r\n\r\n" +
"GET /maliciousRequest HTTP/1.1\r\n" +
"Host: evilServer.com\r\n" +
"Foo: x";
testInvalidHeaders0(requestStr);
} | Base | 1 |
void requestResetPassword() throws Exception
{
when(this.authorizationManager.hasAccess(Right.PROGRAM)).thenReturn(true);
UserReference userReference = mock(UserReference.class);
ResetPasswordRequestResponse requestResponse = mock(ResetPasswordRequestResponse.class);
when(this.resetPasswordManager.requestResetPassword(userReference)).thenReturn(requestResponse);
InternetAddress userEmail = new InternetAddress("[email protected]");
when(requestResponse.getUserEmail()).thenReturn(userEmail);
assertEquals(userEmail, this.scriptService.requestResetPassword(userReference));
verify(this.resetPasswordManager).sendResetPasswordEmailRequest(requestResponse);
} | Base | 1 |
private String loginUser(URI hostUri) throws Throwable {
URI usersLink = UriUtils.buildUri(hostUri, UserService.FACTORY_LINK);
// wait for factory availability
this.host.waitForReplicatedFactoryServiceAvailable(usersLink);
String basicAuth = BasicAuthenticationUtils.constructBasicAuth(adminUser, adminUser);
URI loginUri = UriUtils.buildUri(hostUri, ServiceUriPaths.CORE_AUTHN_BASIC);
AuthenticationRequest login = new AuthenticationRequest();
login.requestType = AuthenticationRequest.AuthenticationRequestType.LOGIN;
String[] authToken = new String[1];
authToken[0] = null;
Date exp = this.host.getTestExpiration();
while (new Date().before(exp)) {
Operation loginPost = Operation.createPost(loginUri)
.setBody(login)
.addRequestHeader(Operation.AUTHORIZATION_HEADER, basicAuth)
.forceRemote()
.setCompletion((op, ex) -> {
if (ex != null) {
this.host.completeIteration();
return;
}
authToken[0] = op.getResponseHeader(Operation.REQUEST_AUTH_TOKEN_HEADER);
this.host.completeIteration();
});
this.host.testStart(1);
this.host.send(loginPost);
this.host.testWait();
if (authToken[0] != null) {
break;
}
Thread.sleep(250);
}
if (new Date().after(exp)) {
throw new TimeoutException();
}
assertNotNull(authToken[0]);
return authToken[0];
} | Class | 2 |
public void translate(TextPacket packet, GeyserSession session) {
String message = packet.getMessage();
if (MessageTranslator.isTooLong(message, session)) {
return;
}
ClientChatPacket chatPacket = new ClientChatPacket(message);
session.sendDownstreamPacket(chatPacket);
} | Class | 2 |
public void write(byte[] b, int offset, int length) throws IOException {
if (b == null) {
throw new NullPointerException();
}
if (offset < 0 || offset + length > b.length) {
throw new ArrayIndexOutOfBoundsException();
}
write(fd, b, offset, length);
} | Base | 1 |
private String templatePath() {
if (templatePath == null) {
String file = HgCommand.class.getResource("/hg.template").getFile();
try {
templatePath = URLDecoder.decode(new File(file).getAbsolutePath(), "UTF-8");
} catch (UnsupportedEncodingException e) {
templatePath = URLDecoder.decode(new File(file).getAbsolutePath());
}
}
return templatePath;
} | Class | 2 |
static void setProperty(SchemaFactory schemaFactory, String propertyName) throws SAXException {
try {
schemaFactory.setProperty(propertyName, "");
} catch (SAXException e) {
if (Boolean.getBoolean(SYSTEM_PROPERTY_IGNORE_XXE_PROTECTION_FAILURES)) {
LOGGER.warning("Enabling XXE protection failed. The property " + propertyName
+ " is not supported by the SchemaFactory. The " + SYSTEM_PROPERTY_IGNORE_XXE_PROTECTION_FAILURES
+ " system property is used so the XML processing continues in the UNSECURE mode"
+ " with XXE protection disabled!!!");
} else {
LOGGER.severe("Enabling XXE protection failed. The property " + propertyName
+ " is not supported by the SchemaFactory. This usually mean an outdated XML processor"
+ " is present on the classpath (e.g. Xerces, Xalan). If you are not able to resolve the issue by"
+ " fixing the classpath, the " + SYSTEM_PROPERTY_IGNORE_XXE_PROTECTION_FAILURES
+ " system property can be used to disable XML External Entity protections."
+ " We don't recommend disabling the XXE as such the XML processor configuration is unsecure!!!", e);
throw e;
}
}
} | Base | 1 |
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());
}
});
} | Class | 2 |
public static <T> T withEncodedPassword(AuthenticationRequestType type, Properties info,
PasswordAction<byte[], T> action) throws PSQLException, IOException {
byte[] encodedPassword = withPassword(type, info, password -> {
if (password == null) {
throw new PSQLException(
GT.tr("The server requested password-based authentication, but no password was provided."),
PSQLState.CONNECTION_REJECTED);
}
ByteBuffer buf = StandardCharsets.UTF_8.encode(CharBuffer.wrap(password));
byte[] bytes = new byte[buf.limit()];
buf.get(bytes);
return bytes;
});
try {
return action.apply(encodedPassword);
} finally {
java.util.Arrays.fill(encodedPassword, (byte) 0);
}
} | Class | 2 |
error_t nicSendPacket(NetInterface *interface, const NetBuffer *buffer,
size_t offset, NetTxAncillary *ancillary)
{
error_t error;
bool_t status;
//Gather entropy
netContext.entropy += netGetSystemTickCount();
#if (TRACE_LEVEL >= TRACE_LEVEL_DEBUG)
//Retrieve the length of the packet
size_t length = netBufferGetLength(buffer) - offset;
//Debug message
TRACE_DEBUG("Sending packet (%" PRIuSIZE " bytes)...\r\n", length);
TRACE_DEBUG_NET_BUFFER(" ", buffer, offset, length);
#endif
//Check whether the interface is enabled for operation
if(interface->configured && interface->nicDriver != NULL)
{
//Loopback interface?
if(interface->nicDriver->type == NIC_TYPE_LOOPBACK)
{
//The loopback interface is always available
status = TRUE;
}
else
{
//Wait for the transmitter to be ready to send
status = osWaitForEvent(&interface->nicTxEvent, NIC_MAX_BLOCKING_TIME);
}
//Check whether the specified event is in signaled state
if(status)
{
//Disable interrupts
interface->nicDriver->disableIrq(interface);
//Send the packet
error = interface->nicDriver->sendPacket(interface, buffer, offset,
ancillary);
//Re-enable interrupts if necessary
if(interface->configured)
{
interface->nicDriver->enableIrq(interface);
}
}
else
{
//If the transmitter is busy, then drop the packet
error = NO_ERROR;
}
}
else
{
//Report an error
error = ERROR_INVALID_INTERFACE;
}
//Return status code
return error;
} | Class | 2 |
public boolean isAvailable() {
try {
GeoTools.getInitialContext();
return true;
} catch (NamingException e) {
return false;
}
} | Class | 2 |
public boolean add(MediaPackage sourceMediaPackage, AccessControlList acl, Date now) throws SolrServerException,
UnauthorizedException {
try {
SolrInputDocument episodeDocument = createEpisodeInputDocument(sourceMediaPackage, acl);
Schema.setOcModified(episodeDocument, now);
SolrInputDocument seriesDocument = createSeriesInputDocument(sourceMediaPackage.getSeries(), acl);
if (seriesDocument != null)
Schema.enrich(episodeDocument, seriesDocument);
// If neither an episode nor a series was contained, there is no point in trying to update
if (episodeDocument == null && seriesDocument == null) {
logger.warn("Neither episode nor series metadata found");
return false;
}
// Post everything to the search index
if (episodeDocument != null)
solrServer.add(episodeDocument);
if (seriesDocument != null)
solrServer.add(seriesDocument);
solrServer.commit();
return true;
} catch (Exception e) {
logger.error("Unable to add mediapackage {} to index", sourceMediaPackage.getIdentifier());
throw new SolrServerException(e);
}
} | Class | 2 |
public boolean isResetPasswordSent()
{
// If there is no form and we see an info box, then the request was sent.
return !getDriver().hasElementWithoutWaiting(By.cssSelector("#resetPasswordForm"))
&& messageBox.getText().contains("An e-mail was sent to");
} | Base | 1 |
public Process execute()
throws CommandLineException
{
// TODO: Provided only for backward compat. with <= 1.4
verifyShellState();
Process process;
//addEnvironment( "MAVEN_TEST_ENVAR", "MAVEN_TEST_ENVAR_VALUE" );
String[] environment = getEnvironmentVariables();
File workingDir = shell.getWorkingDirectory();
try
{
if ( workingDir == null )
{
process = Runtime.getRuntime().exec( getShellCommandline(), environment );
}
else
{
if ( !workingDir.exists() )
{
throw new CommandLineException( "Working directory \"" + workingDir.getPath()
+ "\" does not exist!" );
}
else if ( !workingDir.isDirectory() )
{
throw new CommandLineException( "Path \"" + workingDir.getPath()
+ "\" does not specify a directory." );
}
process = Runtime.getRuntime().exec( getShellCommandline(), environment, workingDir );
}
}
catch ( IOException ex )
{
throw new CommandLineException( "Error while executing process.", ex );
}
return process;
} | Base | 1 |
public synchronized <T extends Source> T getSource(Class<T> sourceClass) throws SQLException {
checkFreed();
ensureInitialized();
if (data == null) {
return null;
}
try {
if (sourceClass == null || DOMSource.class.equals(sourceClass)) {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
builder.setErrorHandler(new NonPrintingErrorHandler());
InputSource input = new InputSource(new StringReader(data));
return (T) new DOMSource(builder.parse(input));
} else if (SAXSource.class.equals(sourceClass)) {
InputSource is = new InputSource(new StringReader(data));
return (T) new SAXSource(is);
} else if (StreamSource.class.equals(sourceClass)) {
return (T) new StreamSource(new StringReader(data));
} else if (StAXSource.class.equals(sourceClass)) {
XMLInputFactory xif = XMLInputFactory.newInstance();
XMLStreamReader xsr = xif.createXMLStreamReader(new StringReader(data));
return (T) new StAXSource(xsr);
}
} catch (Exception e) {
throw new PSQLException(GT.tr("Unable to decode xml data."), PSQLState.DATA_ERROR, e);
}
throw new PSQLException(GT.tr("Unknown XML Source class: {0}", sourceClass),
PSQLState.INVALID_PARAMETER_TYPE);
} | Base | 1 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.