code
stringlengths 12
2.05k
| label_name
stringclasses 5
values | label
int64 0
4
|
---|---|---|
public void existingDocumentNonTerminalFromUIDeprecated() 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&tocreate=space
when(mockRequest.getParameter("space")).thenReturn("X");
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 because the tocreate parameter says "space".
verify(mockURLFactory).createURL("X", "WebHome", "edit", "template=&parent=Main.WebHome&title=X", null, "xwiki",
context);
} | Class | 2 |
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);
} | Class | 2 |
public void afterClearHeadersShouldBeEmpty() {
final HttpHeadersBase headers = newEmptyHeaders();
headers.add("name1", "value1");
headers.add("name2", "value2");
assertThat(headers.size()).isEqualTo(2);
headers.clear();
assertThat(headers.size()).isEqualTo(0);
assertThat(headers.isEmpty()).isTrue();
assertThat(headers.contains("name1")).isFalse();
assertThat(headers.contains("name2")).isFalse();
} | Class | 2 |
public int decryptWithAd(byte[] ad, byte[] ciphertext,
int ciphertextOffset, byte[] plaintext, int plaintextOffset,
int length) throws ShortBufferException, BadPaddingException {
int space;
if (ciphertextOffset > ciphertext.length)
space = 0;
else
space = ciphertext.length - ciphertextOffset;
if (length > space)
throw new ShortBufferException();
if (plaintextOffset > plaintext.length)
space = 0;
else
space = plaintext.length - plaintextOffset;
if (keySpec == null) {
// The key is not set yet - return the ciphertext as-is.
if (length > space)
throw new ShortBufferException();
if (plaintext != ciphertext || plaintextOffset != ciphertextOffset)
System.arraycopy(ciphertext, ciphertextOffset, plaintext, plaintextOffset, length);
return length;
}
if (length < 16)
Noise.throwBadTagException();
int dataLen = length - 16;
if (dataLen > space)
throw new ShortBufferException();
try {
setup(ad);
} catch (InvalidKeyException e) {
// Shouldn't happen.
throw new IllegalStateException(e);
} catch (InvalidAlgorithmParameterException e) {
// Shouldn't happen.
throw new IllegalStateException(e);
}
ghash.update(ciphertext, ciphertextOffset, dataLen);
ghash.pad(ad != null ? ad.length : 0, dataLen);
ghash.finish(iv, 0, 16);
int temp = 0;
for (int index = 0; index < 16; ++index)
temp |= (hashKey[index] ^ iv[index] ^ ciphertext[ciphertextOffset + dataLen + index]);
if ((temp & 0xFF) != 0)
Noise.throwBadTagException();
try {
int result = cipher.update(ciphertext, ciphertextOffset, dataLen, plaintext, plaintextOffset);
cipher.doFinal(plaintext, plaintextOffset + result);
} catch (IllegalBlockSizeException e) {
// Shouldn't happen.
throw new IllegalStateException(e);
} catch (BadPaddingException e) {
// Shouldn't happen.
throw new IllegalStateException(e);
}
return dataLen;
} | Base | 1 |
public BCXMSSPrivateKey(PrivateKeyInfo keyInfo)
throws IOException
{
XMSSKeyParams keyParams = XMSSKeyParams.getInstance(keyInfo.getPrivateKeyAlgorithm().getParameters());
this.treeDigest = keyParams.getTreeDigest().getAlgorithm();
XMSSPrivateKey xmssPrivateKey = XMSSPrivateKey.getInstance(keyInfo.parsePrivateKey());
try
{
XMSSPrivateKeyParameters.Builder keyBuilder = new XMSSPrivateKeyParameters
.Builder(new XMSSParameters(keyParams.getHeight(), DigestUtil.getDigest(treeDigest)))
.withIndex(xmssPrivateKey.getIndex())
.withSecretKeySeed(xmssPrivateKey.getSecretKeySeed())
.withSecretKeyPRF(xmssPrivateKey.getSecretKeyPRF())
.withPublicSeed(xmssPrivateKey.getPublicSeed())
.withRoot(xmssPrivateKey.getRoot());
if (xmssPrivateKey.getBdsState() != null)
{
keyBuilder.withBDSState((BDS)XMSSUtil.deserialize(xmssPrivateKey.getBdsState()));
}
this.keyParams = keyBuilder.build();
}
catch (ClassNotFoundException e)
{
throw new IOException("ClassNotFoundException processing BDS state: " + e.getMessage());
}
} | Base | 1 |
public static Object deserialize(final String s) {
ObjectInputStream ois = null;
try {
ois = new ObjectInputStream(new ByteArrayInputStream(s.getBytes("8859_1")));
return ois.readObject();
} catch (Exception e) {
logger.error("Cannot deserialize payload using " + (s == null ? -1 : s.length()) + " bytes", e);
throw new IllegalArgumentException("Cannot deserialize payload");
} finally {
if (ois != null) {
try {
ois.close();
} catch (IOException ignore) {
// empty catch block
}
}
}
} | Base | 1 |
public void drawU(UGraphic ug) {
ug = ug.apply(backColor.bg()).apply(borderColor);
final URectangle rect = new URectangle(dim.getWidth(), dim.getHeight()).rounded(rounded);
rect.setDeltaShadow(shadowing);
ug.apply(stroke).draw(rect);
final double yLine = titleHeight + attributeHeight;
ug = ug.apply(imgBackcolor.bg());
final double thickness = stroke.getThickness();
final URectangle inner = new URectangle(dim.getWidth() - 4 * thickness,
dim.getHeight() - titleHeight - 4 * thickness - attributeHeight).rounded(rounded);
ug.apply(imgBackcolor).apply(new UTranslate(2 * thickness, yLine + 2 * thickness)).draw(inner);
if (titleHeight > 0) {
ug.apply(stroke).apply(UTranslate.dy(yLine)).draw(ULine.hline(dim.getWidth()));
}
if (attributeHeight > 0) {
ug.apply(stroke).apply(UTranslate.dy(yLine - attributeHeight)).draw(ULine.hline(dim.getWidth()));
}
} | Base | 1 |
public XssHttpServletRequestWrapper(HttpServletRequest request) {
super(request);
} | Base | 1 |
public DefaultFileSystemResourceLoader(Path path) {
this.baseDirPath = Optional.of(path);
} | Base | 1 |
final protected CommandExecutionResult executeArg(TimingDiagram diagram, LineLocation location, RegexResult arg) {
final String compact = arg.get("COMPACT", 0);
final String code = arg.get("CODE", 0);
final String full = arg.get("FULL", 0);
return diagram.createBinary(code, full, compact != null);
} | Base | 1 |
public void translate(ServerPlayerHealthPacket packet, GeyserSession session) {
SessionPlayerEntity entity = session.getPlayerEntity();
int health = (int) Math.ceil(packet.getHealth());
SetHealthPacket setHealthPacket = new SetHealthPacket();
setHealthPacket.setHealth(health);
session.sendUpstreamPacket(setHealthPacket);
entity.setHealth(packet.getHealth());
UpdateAttributesPacket attributesPacket = new UpdateAttributesPacket();
List<AttributeData> attributes = attributesPacket.getAttributes();
AttributeData healthAttribute = entity.createHealthAttribute();
entity.getAttributes().put(GeyserAttributeType.HEALTH, healthAttribute);
attributes.add(healthAttribute);
AttributeData hungerAttribute = GeyserAttributeType.HUNGER.getAttribute(packet.getFood());
entity.getAttributes().put(GeyserAttributeType.HUNGER, hungerAttribute);
attributes.add(hungerAttribute);
AttributeData saturationAttribute = GeyserAttributeType.SATURATION.getAttribute(packet.getSaturation());
entity.getAttributes().put(GeyserAttributeType.SATURATION, saturationAttribute);
attributes.add(saturationAttribute);
attributesPacket.setRuntimeEntityId(entity.getGeyserId());
session.sendUpstreamPacket(attributesPacket);
} | Class | 2 |
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());
} | Class | 2 |
protected Response attachToPost(Long messageKey, String filename, InputStream file, HttpServletRequest request) {
//load message
Message mess = fom.loadMessage(messageKey);
if(mess == null) {
return Response.serverError().status(Status.NOT_FOUND).build();
}
if(!forum.equalsByPersistableKey(mess.getForum())) {
return Response.serverError().status(Status.CONFLICT).build();
}
return attachToPost(mess, filename, file, request);
} | Base | 1 |
callback: (request: PublishRequest, response: PublishResponse) => void; | Class | 2 |
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 |
public void addViolation(String propertyName, String message) {
violationOccurred = true;
String messageTemplate = escapeEl(message);
context.buildConstraintViolationWithTemplate(messageTemplate)
.addPropertyNode(propertyName)
.addConstraintViolation();
} | Class | 2 |
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;
} | Class | 2 |
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;
} | Class | 2 |
public SecretKey deriveKey(final SecretKey sharedSecret,
final int keyLengthBits,
final byte[] otherInfo)
throws JOSEException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
final MessageDigest md = getMessageDigest();
for (int i=1; i <= computeDigestCycles(ByteUtils.bitLength(md.getDigestLength()), keyLengthBits); i++) {
byte[] counterBytes = IntegerUtils.toBytes(i);
md.update(counterBytes);
md.update(sharedSecret.getEncoded());
if (otherInfo != null) {
md.update(otherInfo);
}
try {
baos.write(md.digest());
} catch (IOException e) {
throw new JOSEException("Couldn't write derived key: " + e.getMessage(), e);
}
}
byte[] derivedKeyMaterial = baos.toByteArray();
final int keyLengthBytes = ByteUtils.byteLength(keyLengthBits);
if (derivedKeyMaterial.length == keyLengthBytes) {
// Return immediately
return new SecretKeySpec(derivedKeyMaterial, "AES");
}
return new SecretKeySpec(ByteUtils.subArray(derivedKeyMaterial, 0, keyLengthBytes), "AES");
} | Class | 2 |
public void testGetBytesAndSetBytesWithFileChannel() 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.getBytes(oldReaderIndex, channel, 10, len));
assertEquals(oldReaderIndex, buffer.readerIndex());
assertEquals(channelPosition, channel.position());
ByteBuf buffer2 = newBuffer(len);
buffer2.resetReaderIndex();
buffer2.resetWriterIndex();
int oldWriterIndex = buffer2.writerIndex();
assertEquals(buffer2.setBytes(oldWriterIndex, channel, 10, len), len);
assertEquals(channelPosition, channel.position());
assertEquals(oldWriterIndex, buffer2.writerIndex());
assertEquals('a', buffer2.getByte(oldWriterIndex));
assertEquals('b', buffer2.getByte(oldWriterIndex + 1));
assertEquals('c', buffer2.getByte(oldWriterIndex + 2));
assertEquals('d', buffer2.getByte(oldWriterIndex + 3));
buffer.release();
buffer2.release();
} finally {
if (randomAccessFile != null) {
randomAccessFile.close();
}
file.delete();
}
} | Base | 1 |
public void translate(ServerPlayerActionAckPacket packet, GeyserSession session) {
ChunkUtils.updateBlock(session, packet.getNewState(), packet.getPosition());
if (packet.getAction() == PlayerAction.START_DIGGING && !packet.isSuccessful()) {
LevelEventPacket stopBreak = new LevelEventPacket();
stopBreak.setType(LevelEventType.BLOCK_STOP_BREAK);
stopBreak.setPosition(Vector3f.from(packet.getPosition().getX(), packet.getPosition().getY(), packet.getPosition().getZ()));
stopBreak.setData(0);
session.setBreakingBlock(BlockStateValues.JAVA_AIR_ID);
session.sendUpstreamPacket(stopBreak);
}
} | Class | 2 |
public boolean archiveNodeData(Locale locale, ICourse course, ArchiveOptions options,
ZipOutputStream exportStream, String archivePath, String charset) {
String filename = "checklist_"
+ StringHelper.transformDisplayNameToFileSystemName(getShortName())
+ "_" + Formatter.formatDatetimeFilesystemSave(new Date(System.currentTimeMillis()));
filename = ZipUtil.concat(archivePath, filename);
Checklist checklist = loadOrCreateChecklist(course.getCourseEnvironment().getCoursePropertyManager());
String exportContent = XStreamHelper.createXStreamInstance().toXML(checklist);
try {
exportStream.putNextEntry(new ZipEntry(filename));
IOUtils.write(exportContent, exportStream, "UTF-8");
exportStream.closeEntry();
} catch (IOException e) {
log.error("", e);
}
return true;
} | Base | 1 |
public static String serializeToString(final Object payload) throws IOException {
final ByteArrayOutputStream bos = new ByteArrayOutputStream();
serializeToStream(bos, payload);
String agentData = null;
try {
agentData = bos.toString("8859_1");
} catch (UnsupportedEncodingException e) {
logger.warn("Should always support 8859_1", e);
agentData = bos.toString();
}
return agentData;
} | Base | 1 |
protected boolean evaluate(InputSource inputSource)
{
try
{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder dbuilder = factory.newDocumentBuilder();
Document doc = dbuilder.parse(inputSource);
//An XPath expression could return a true or false value instead of a node.
//eval() is a better way to determine the boolean value of the exp.
//For compliance with legacy behavior where selecting an empty node returns true,
//selectNodeIterator is attempted in case of a failure.
CachedXPathAPI cachedXPathAPI = new CachedXPathAPI();
XObject result = cachedXPathAPI.eval(doc, xpath);
if (result.bool())
return true;
else
{
NodeIterator iterator = cachedXPathAPI.selectNodeIterator(doc, xpath);
return (iterator.nextNode() != null);
}
}
catch (Throwable e)
{
return false;
}
} | Base | 1 |
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
throws IOException {
String filename = file.getFileName().toString();
Path normalizedPath = file.normalize();
if(!normalizedPath.startsWith(destDir)) {
throw new IOException("Invalid ZIP");
}
if(filename.endsWith(WikiManager.WIKI_PROPERTIES_SUFFIX)) {
String f = convertAlternativeFilename(file.toString());
final Path destFile = Paths.get(wikiDir.toString(), f);
resetAndCopyProperties(file, destFile);
} else if (filename.endsWith(WIKI_FILE_SUFFIX)) {
String f = convertAlternativeFilename(file.toString());
final Path destFile = Paths.get(wikiDir.toString(), f);
Files.copy(file, destFile, StandardCopyOption.REPLACE_EXISTING);
} else if (!filename.contains(WIKI_FILE_SUFFIX + "-")
&& !filename.contains(WIKI_PROPERTIES_SUFFIX + "-")) {
final Path destFile = Paths.get(mediaDir.toString(), file.toString());
Files.copy(file, destFile, StandardCopyOption.REPLACE_EXISTING);
}
return FileVisitResult.CONTINUE;
} | Base | 1 |
public static OHttpSessionManager getInstance() {
return instance;
}
| Class | 2 |
public void testMatchUseNotSpecifiedOrSignature() {
JWKMatcher matcher = new JWKMatcher.Builder().keyUses(KeyUse.SIGNATURE, null).build();
assertTrue(matcher.matches(new RSAKey.Builder(new Base64URL("n"), new Base64URL("e")).keyID("1").keyUse(KeyUse.SIGNATURE).build()));
assertTrue(matcher.matches(new ECKey.Builder(ECKey.Curve.P_256, new Base64URL("x"), new Base64URL("y")).keyID("2").build()));
assertFalse(matcher.matches(new ECKey.Builder(ECKey.Curve.P_256, new Base64URL("x"), new Base64URL("y")).keyID("3").keyUse(KeyUse.ENCRYPTION).build()));
assertEquals("use=[sig, null]", matcher.toString());
} | Base | 1 |
void rawUnicode() {
// 2- and 3-byte UTF-8
final PathAndQuery res1 = PathAndQuery.parse("/\u00A2?\u20AC"); // ¢ and €
assertThat(res1).isNotNull();
assertThat(res1.path()).isEqualTo("/%C2%A2");
assertThat(res1.query()).isEqualTo("%E2%82%AC");
// 4-byte UTF-8
final PathAndQuery res2 = PathAndQuery.parse("/\uD800\uDF48"); // 𐍈
assertThat(res2).isNotNull();
assertThat(res2.path()).isEqualTo("/%F0%90%8D%88");
assertThat(res2.query()).isNull();
// 5- and 6-byte forms are only theoretically possible, so we won't test them here.
} | Base | 1 |
public void setIgnoreComments(boolean ignoreComments) {
this.ignoreComments = ignoreComments;
} | Base | 1 |
public void translate(ServerSpawnParticlePacket packet, GeyserSession session) {
Function<Vector3f, BedrockPacket> particleCreateFunction = createParticle(session, packet.getParticle());
if (particleCreateFunction != null) {
if (packet.getAmount() == 0) {
// 0 means don't apply the offset
Vector3f position = Vector3f.from(packet.getX(), packet.getY(), packet.getZ());
session.sendUpstreamPacket(particleCreateFunction.apply(position));
} else {
Random random = ThreadLocalRandom.current();
for (int i = 0; i < packet.getAmount(); i++) {
double offsetX = random.nextGaussian() * (double) packet.getOffsetX();
double offsetY = random.nextGaussian() * (double) packet.getOffsetY();
double offsetZ = random.nextGaussian() * (double) packet.getOffsetZ();
Vector3f position = Vector3f.from(packet.getX() + offsetX, packet.getY() + offsetY, packet.getZ() + offsetZ);
session.sendUpstreamPacket(particleCreateFunction.apply(position));
}
}
} else {
// Null is only returned when no particle of this type is found
session.getConnector().getLogger().debug("Unhandled particle packet: " + packet);
}
} | Class | 2 |
public static Document parseText(String text) throws DocumentException {
SAXReader reader = new SAXReader();
try {
reader.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
reader.setFeature("http://xml.org/sax/features/external-general-entities", false);
reader.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
} catch (SAXException e) {
//Parse with external resources downloading allowed.
}
String encoding = getEncoding(text);
InputSource source = new InputSource(new StringReader(text));
source.setEncoding(encoding);
Document result = reader.read(source);
// if the XML parser doesn't provide a way to retrieve the encoding,
// specify it manually
if (result.getXMLEncoding() == null) {
result.setXMLEncoding(encoding);
}
return result;
} | Base | 1 |
private X509HostnameVerifier createHostNameVerifier() {
X509HostnameVerifier verifier = new X509HostnameVerifier() {
/**
* {@InheritDoc}
*
* @see org.apache.http.conn.ssl.X509HostnameVerifier#verify(java.lang.String, javax.net.ssl.SSLSocket)
*/
public void verify(String host, SSLSocket ssl) throws IOException {
logger.trace("Skipping SSL host name check on {}", host);
}
/**
* {@InheritDoc}
*
* @see org.apache.http.conn.ssl.X509HostnameVerifier#verify(java.lang.String, java.security.cert.X509Certificate)
*/
public void verify(String host, X509Certificate xc) throws SSLException {
logger.trace("Skipping X509 certificate host name check on {}", host);
}
/**
* {@InheritDoc}
*
* @see org.apache.http.conn.ssl.X509HostnameVerifier#verify(java.lang.String, java.lang.String[],
* java.lang.String[])
*/
public void verify(String host, String[] cns, String[] subjectAlts) throws SSLException {
logger.trace("Skipping DNS host name check on {}", host);
}
/**
* {@InheritDoc}
*
* @see javax.net.ssl.HostnameVerifier#verify(java.lang.String, javax.net.ssl.SSLSession)
*/
public boolean verify(String host, SSLSession ssl) {
logger.trace("Skipping SSL session host name check on {}", host);
return true;
}
};
return verifier;
} | Class | 2 |
public static void execute(String url, String proxyHost, int proxyPort, String proxyUsername, String proxyPassword,
String accessToken, String orgName, String moduleName, String version, Path baloPath) {
initializeSsl();
HttpURLConnection conn = createHttpUrlConnection(convertToUrl(url), proxyHost, proxyPort, proxyUsername,
proxyPassword);
conn.setInstanceFollowRedirects(false);
setRequestMethod(conn, Utils.RequestMethod.POST);
// Set headers
conn.setRequestProperty(HttpHeaders.AUTHORIZATION, "Bearer " + accessToken);
conn.setRequestProperty(PUSH_ORGANIZATION, orgName);
conn.setRequestProperty(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_OCTET_STREAM);
conn.setDoOutput(true);
conn.setChunkedStreamingMode(BUFFER_SIZE);
try (DataOutputStream outputStream = new DataOutputStream(conn.getOutputStream())) {
// Send balo content by 1 kb chunks
byte[] buffer = new byte[BUFFER_SIZE];
int count;
try (ProgressBar progressBar = new ProgressBar(
orgName + "/" + moduleName + ":" + version + " [project repo -> central]",
getTotalFileSizeInKB(baloPath), 1000, outStream, ProgressBarStyle.ASCII, " KB", 1);
FileInputStream fis = new FileInputStream(baloPath.toFile())) {
while ((count = fis.read(buffer)) > 0) {
outputStream.write(buffer, 0, count);
outputStream.flush();
progressBar.stepBy((long) NO_OF_BYTES);
}
}
} catch (IOException e) {
throw ErrorUtil.createCommandException("error occurred while uploading balo to central: " + e.getMessage());
}
handleResponse(conn, orgName, moduleName, version);
Authenticator.setDefault(null);
} | Base | 1 |
private Certificate toCertificate(KeyDescriptorType keyDescriptorType) {
try {
List<Object> keyData = keyDescriptorType.getKeyInfo().getContent();
for (Object keyDatum : keyData) {
if (keyDatum instanceof JAXBElement<?>) {
JAXBElement<?> element = (JAXBElement<?>) keyDatum;
if (element.getDeclaredType() == X509DataType.class) {
X509DataType cert = (X509DataType) element.getValue();
List<Object> certData = cert.getX509IssuerSerialOrX509SKIOrX509SubjectName();
for (Object certDatum : certData) {
element = (JAXBElement<?>) certDatum;
if (element.getName().getLocalPart().equals("X509Certificate")) {
byte[] certBytes = (byte[]) element.getValue();
CertificateFactory cf = CertificateFactory.getInstance("X.509");
return cf.generateCertificate(new ByteArrayInputStream(certBytes));
}
}
}
}
}
return null;
} catch (CertificateException e) {
throw new IllegalArgumentException(e);
}
} | Base | 1 |
void requestResetPasswordNoEmail() throws Exception
{
when(this.userManager.exists(this.userReference)).thenReturn(true);
String exceptionMessage = "User has no email address.";
when(this.localizationManager.getTranslationPlain("xe.admin.passwordReset.error.noEmail"))
.thenReturn(exceptionMessage);
ResetPasswordException resetPasswordException = assertThrows(ResetPasswordException.class,
() -> this.resetPasswordManager.requestResetPassword(this.userReference));
assertEquals(exceptionMessage, resetPasswordException.getMessage());
} | Base | 1 |
private String marshallToString(Document document) throws TransformerException {
StringWriter sw = new StringWriter();
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.transform(new DOMSource(document), new StreamResult(sw));
return sw.toString();
} | Base | 1 |
public void testMatchOperation() {
JWKMatcher matcher = new JWKMatcher.Builder().keyOperation(KeyOperation.DECRYPT).build();
assertTrue(matcher.matches(new RSAKey.Builder(new Base64URL("n"), new Base64URL("e")).keyID("1")
.keyOperations(new HashSet<>(Collections.singletonList(KeyOperation.DECRYPT))).build()));
assertFalse(matcher.matches(new ECKey.Builder(ECKey.Curve.P_256, new Base64URL("x"), new Base64URL("y")).keyID("2").build()));
assertEquals("key_ops=decrypt", matcher.toString());
} | Base | 1 |
public Document read(URL url) throws DocumentException {
String systemID = url.toExternalForm();
InputSource source = new InputSource(systemID);
if (this.encoding != null) {
source.setEncoding(this.encoding);
}
return read(source);
} | Base | 1 |
public void translate(ServerEntityHeadLookPacket packet, GeyserSession session) {
Entity entity = session.getEntityCache().getEntityByJavaId(packet.getEntityId());
if (packet.getEntityId() == session.getPlayerEntity().getEntityId()) {
entity = session.getPlayerEntity();
}
if (entity == null) return;
entity.updateHeadLookRotation(session, packet.getHeadYaw());
} | Class | 2 |
private Runnable getDiscoveryRequestSetup(final String url) {
return new Runnable() {
public void run() {
expect(request.getHeader("Origin")).andStubReturn(null);
expect(request.getHeader("Referer")).andStubReturn(null);
expect(request.getRemoteHost()).andReturn("localhost");
expect(request.getRemoteAddr()).andReturn("127.0.0.1");
expect(request.getRequestURI()).andReturn("/jolokia/");
expect(request.getParameterMap()).andReturn(null);
expect(request.getAttribute(ConfigKey.JAAS_SUBJECT_REQUEST_ATTRIBUTE)).andReturn(null);
expect(request.getPathInfo()).andReturn(HttpTestUtil.HEAP_MEMORY_GET_REQUEST);
expect(request.getParameter(ConfigKey.MIME_TYPE.getKeyValue())).andReturn("text/plain");
StringBuffer buf = new StringBuffer();
buf.append(url).append(HttpTestUtil.HEAP_MEMORY_GET_REQUEST);
expect(request.getRequestURL()).andReturn(buf);
expect(request.getRequestURI()).andReturn("/jolokia" + HttpTestUtil.HEAP_MEMORY_GET_REQUEST);
expect(request.getContextPath()).andReturn("/jolokia");
expect(request.getAuthType()).andReturn("BASIC");
expect(request.getAttribute("subject")).andReturn(null);
expect(request.getParameter(ConfigKey.STREAMING.getKeyValue())).andReturn(null);
}
};
} | Base | 1 |
public void checkConnection(UrlArgument repositoryURL) {
execute(createCommandLine("hg").withArgs("id", "--id").withArg(repositoryURL).withNonArgSecrets(secrets).withEncoding("utf-8"), new NamedProcessTag(repositoryURL.forDisplay()));
} | Class | 2 |
public void newDocumentWebHomeFromURLTemplateProviderSpecifiedTerminal() throws Exception
{
// new document = xwiki:X.Y.WebHome
DocumentReference documentReference = new DocumentReference("xwiki", Arrays.asList("X", "Y"), "WebHome");
XWikiDocument document = mock(XWikiDocument.class);
when(document.getDocumentReference()).thenReturn(documentReference);
when(document.isNew()).thenReturn(true);
when(document.getLocalReferenceMaxLength()).thenReturn(255);
context.setDoc(document);
// Specifying a template provider in the URL: templateprovider=XWiki.MyTemplateProvider
String templateProviderFullName = "XWiki.MyTemplateProvider";
when(mockRequest.getParameter("templateprovider")).thenReturn(templateProviderFullName);
// Mock 1 existing template provider
mockExistingTemplateProviders(templateProviderFullName,
new DocumentReference("xwiki", Arrays.asList("XWiki"), "MyTemplateProvider"), Collections.EMPTY_LIST, true);
// Run the action
String result = action.render(context);
// The tests are below this line!
// Verify null is returned (this means the response has been returned)
assertNull(result);
// Note: We are creating the document X.Y as terminal and using a template, as specified in the template
// provider.
verify(mockURLFactory).createURL("X", "Y", "edit", "template=XWiki.MyTemplate&parent=Main.WebHome&title=Y",
null, "xwiki", context);
} | Class | 2 |
public static ResourceEvaluation evaluate(File file, String filename) {
ResourceEvaluation eval = new ResourceEvaluation();
try {
ImsManifestFileFilter visitor = new ImsManifestFileFilter();
Path fPath = PathUtils.visit(file, filename, visitor);
if(visitor.isValid()) {
Path realManifestPath = visitor.getManifestPath();
Path manifestPath = fPath.resolve(realManifestPath);
RootSearcher rootSearcher = new RootSearcher();
Files.walkFileTree(fPath, rootSearcher);
if(rootSearcher.foundRoot()) {
manifestPath = rootSearcher.getRoot().resolve(IMS_MANIFEST);
} else {
manifestPath = fPath.resolve(IMS_MANIFEST);
}
Document doc = IMSLoader.loadIMSDocument(manifestPath);
if(validateImsManifest(doc)) {
eval.setValid(true);
} else {
eval.setValid(false);
}
} else {
eval.setValid(false);
}
PathUtils.closeSubsequentFS(fPath);
} catch (IOException | IllegalArgumentException e) {
log.error("", e);
eval.setValid(false);
}
return eval;
} | Base | 1 |
public InputSource resolveEntity(String publicId, String systemId) {
// try create a relative URI reader...
if ((systemId != null) && (systemId.length() > 0)) {
if ((uriPrefix != null) && (systemId.indexOf(':') <= 0)) {
systemId = uriPrefix + systemId;
}
}
return new InputSource(systemId);
} | Base | 1 |
public void setIncludeInternalDTDDeclarations(boolean include) {
this.includeInternalDTDDeclarations = include;
} | Base | 1 |
public void resetPassword(UserReference userReference, String newPassword)
throws ResetPasswordException
{
this.checkUserReference(userReference);
XWikiContext context = this.contextProvider.get();
DocumentUserReference documentUserReference = (DocumentUserReference) userReference;
DocumentReference reference = documentUserReference.getReference();
try {
XWikiDocument userDocument = context.getWiki().getDocument(reference, context);
userDocument.removeXObjects(RESET_PASSWORD_REQUEST_CLASS_REFERENCE);
BaseObject userXObject = userDocument.getXObject(USER_CLASS_REFERENCE);
userXObject.setStringValue("password", newPassword);
String saveComment = this.localizationManager.getTranslationPlain(
"xe.admin.passwordReset.step2.versionComment.passwordReset");
context.getWiki().saveDocument(userDocument, saveComment, true, context);
} catch (XWikiException e) {
throw new ResetPasswordException("Cannot open user document to perform reset password.", e);
}
} | Base | 1 |
public void translate(FilterTextPacket packet, GeyserSession session) {
if (session.getOpenInventory() instanceof CartographyContainer) {
// We don't want to be able to rename in the cartography table
return;
}
packet.setFromServer(true);
session.sendUpstreamPacket(packet);
if (session.getOpenInventory() instanceof AnvilContainer) {
// Java Edition sends a packet every time an item is renamed even slightly in GUI. Fortunately, this works out for us now
ClientRenameItemPacket renameItemPacket = new ClientRenameItemPacket(packet.getText());
session.sendDownstreamPacket(renameItemPacket);
}
} | Class | 2 |
public static String getAttachedFilePath(String inputStudyOid) {
// Using a standard library to validate/Sanitize user inputs which will be used in path expression to prevent from path traversal
String studyOid = FilenameUtils.getName(inputStudyOid);
String attachedFilePath = CoreResources.getField("attached_file_location");
if (attachedFilePath == null || attachedFilePath.length() <= 0) {
attachedFilePath = CoreResources.getField("filePath") + "attached_files" + File.separator + studyOid + File.separator;
} else {
attachedFilePath += studyOid + File.separator;
}
return attachedFilePath;
} | Base | 1 |
public void corsWildCard() {
InputStream is = getClass().getResourceAsStream("/allow-origin2.xml");
PolicyRestrictor restrictor = new PolicyRestrictor(is);
assertTrue(restrictor.isCorsAccessAllowed("http://bla.com"));
assertTrue(restrictor.isCorsAccessAllowed("http://www.jolokia.org"));
assertTrue(restrictor.isCorsAccessAllowed("http://www.consol.de"));
} | Compound | 4 |
public byte[] toByteArray()
{
/* index || secretKeySeed || secretKeyPRF || publicSeed || root */
int n = params.getDigestSize();
int indexSize = (params.getHeight() + 7) / 8;
int secretKeySize = n;
int secretKeyPRFSize = n;
int publicSeedSize = n;
int rootSize = n;
int totalSize = indexSize + secretKeySize + secretKeyPRFSize + publicSeedSize + rootSize;
byte[] out = new byte[totalSize];
int position = 0;
/* copy index */
byte[] indexBytes = XMSSUtil.toBytesBigEndian(index, indexSize);
XMSSUtil.copyBytesAtOffset(out, indexBytes, position);
position += indexSize;
/* copy secretKeySeed */
XMSSUtil.copyBytesAtOffset(out, secretKeySeed, position);
position += secretKeySize;
/* copy secretKeyPRF */
XMSSUtil.copyBytesAtOffset(out, secretKeyPRF, position);
position += secretKeyPRFSize;
/* copy publicSeed */
XMSSUtil.copyBytesAtOffset(out, publicSeed, position);
position += publicSeedSize;
/* copy root */
XMSSUtil.copyBytesAtOffset(out, root, position);
/* concatenate bdsState */
byte[] bdsStateOut = null;
try
{
bdsStateOut = XMSSUtil.serialize(bdsState);
}
catch (IOException e)
{
e.printStackTrace();
throw new RuntimeException("error serializing bds state");
}
return Arrays.concatenate(out, bdsStateOut);
} | Base | 1 |
protected SymbolContext getContextLegacy() {
return new SymbolContext(HColorUtils.COL_D7E0F2, HColorUtils.COL_038048).withStroke(new UStroke(1.5));
} | Base | 1 |
public void existingDocumentFromUITemplateProviderSpecifiedTerminal() throws Exception
{
// current document = xwiki:Main.WebHome
DocumentReference documentReference = new DocumentReference("xwiki", Arrays.asList("Main"), "WebHome");
XWikiDocument document = mock(XWikiDocument.class);
when(document.getDocumentReference()).thenReturn(documentReference);
when(document.isNew()).thenReturn(false);
when(document.getLocalReferenceMaxLength()).thenReturn(255);
context.setDoc(document);
// Submit from the UI spaceReference=X&name=Y&templateProvider=XWiki.MyTemplateProvider
String templateProviderFullName = "XWiki.MyTemplateProvider";
String spaceReferenceString = "X";
when(mockRequest.getParameter("spaceReference")).thenReturn(spaceReferenceString);
when(mockRequest.getParameter("name")).thenReturn("Y");
when(mockRequest.getParameter("templateprovider")).thenReturn(templateProviderFullName);
// Mock 1 existing template provider that creates terminal documents.
mockExistingTemplateProviders(templateProviderFullName,
new DocumentReference("xwiki", Arrays.asList("XWiki"), "MyTemplateProvider"), Collections.EMPTY_LIST, true);
// Run the action
String result = action.render(context);
// The tests are below this line!
// Verify null is returned (this means the response has been returned)
assertNull(result);
// Note: We are creating the document X.Y as terminal and using a template, as specified in the template
// provider.
verify(mockURLFactory).createURL("X", "Y", "edit", "template=XWiki.MyTemplate&parent=Main.WebHome&title=Y",
null, "xwiki", context);
} | Class | 2 |
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
} | Class | 2 |
public void spliceToFile() throws Throwable {
EventLoopGroup group = new EpollEventLoopGroup(1);
File file = File.createTempFile("netty-splice", null);
file.deleteOnExit();
SpliceHandler sh = new SpliceHandler(file);
ServerBootstrap bs = new ServerBootstrap();
bs.channel(EpollServerSocketChannel.class);
bs.group(group).childHandler(sh);
bs.childOption(EpollChannelOption.EPOLL_MODE, EpollMode.LEVEL_TRIGGERED);
Channel sc = bs.bind(NetUtil.LOCALHOST, 0).syncUninterruptibly().channel();
Bootstrap cb = new Bootstrap();
cb.group(group);
cb.channel(EpollSocketChannel.class);
cb.handler(new ChannelInboundHandlerAdapter());
Channel cc = cb.connect(sc.localAddress()).syncUninterruptibly().channel();
for (int i = 0; i < data.length;) {
int length = Math.min(random.nextInt(1024 * 64), data.length - i);
ByteBuf buf = Unpooled.wrappedBuffer(data, i, length);
cc.writeAndFlush(buf);
i += length;
}
while (sh.future2 == null || !sh.future2.isDone() || !sh.future.isDone()) {
if (sh.exception.get() != null) {
break;
}
try {
Thread.sleep(50);
} catch (InterruptedException e) {
// Ignore.
}
}
sc.close().sync();
cc.close().sync();
if (sh.exception.get() != null && !(sh.exception.get() instanceof IOException)) {
throw sh.exception.get();
}
byte[] written = new byte[data.length];
FileInputStream in = new FileInputStream(file);
try {
Assert.assertEquals(written.length, in.read(written));
Assert.assertArrayEquals(data, written);
} finally {
in.close();
group.shutdownGracefully();
}
} | Base | 1 |
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);
} | Class | 2 |
private static AsciiString create(String name) {
return AsciiString.cached(Ascii.toLowerCase(name));
} | Class | 2 |
public void initWithCustomLogHandler() throws Exception {
servlet = new AgentServlet();
config = createMock(ServletConfig.class);
context = createMock(ServletContext.class);
HttpTestUtil.prepareServletConfigMock(config, new String[]{ConfigKey.LOGHANDLER_CLASS.getKeyValue(), CustomLogHandler.class.getName()});
HttpTestUtil.prepareServletContextMock(context,null);
expect(config.getServletContext()).andReturn(context).anyTimes();
expect(config.getServletName()).andReturn("jolokia").anyTimes();
replay(config, context);
servlet.init(config);
servlet.destroy();
assertTrue(CustomLogHandler.infoCount > 0);
} | Compound | 4 |
public void subValidateFail(ViolationCollector col) {
col.addViolation(FAILED+"subclass");
} | Class | 2 |
public ResetPasswordRequestResponse requestResetPassword(UserReference userReference) throws ResetPasswordException
{
this.checkUserReference(userReference);
UserProperties userProperties = this.userPropertiesResolver.resolve(userReference);
InternetAddress email = userProperties.getEmail();
if (email == null) {
String exceptionMessage =
this.localizationManager.getTranslationPlain("xe.admin.passwordReset.error.noEmail");
throw new ResetPasswordException(exceptionMessage);
}
DocumentUserReference documentUserReference = (DocumentUserReference) userReference;
DocumentReference reference = documentUserReference.getReference();
XWikiContext context = this.contextProvider.get();
try {
XWikiDocument userDocument = context.getWiki().getDocument(reference, context);
if (userDocument.getXObject(LDAP_CLASS_REFERENCE) != null) {
String exceptionMessage =
this.localizationManager.getTranslationPlain("xe.admin.passwordReset.error.ldapUser",
userReference.toString());
throw new ResetPasswordException(exceptionMessage);
}
BaseObject xObject = userDocument.getXObject(RESET_PASSWORD_REQUEST_CLASS_REFERENCE, true, context);
String verificationCode = context.getWiki().generateRandomString(30);
xObject.set(VERIFICATION_PROPERTY, verificationCode, context);
String saveComment =
this.localizationManager.getTranslationPlain("xe.admin.passwordReset.versionComment");
context.getWiki().saveDocument(userDocument, saveComment, true, context);
return new DefaultResetPasswordRequestResponse(userReference, email, verificationCode);
} catch (XWikiException e) {
throw new ResetPasswordException("Error when reading user document to perform reset password request.", e);
}
} | Base | 1 |
public void existingDocumentFromUITemplateProviderSpecifiedButOldSpaceType() throws Exception
{
// current document = xwiki:Main.WebHome
DocumentReference documentReference = new DocumentReference("xwiki", Arrays.asList("Main"), "WebHome");
XWikiDocument document = mock(XWikiDocument.class);
when(document.getDocumentReference()).thenReturn(documentReference);
when(document.isNew()).thenReturn(false);
when(document.getLocalReferenceMaxLength()).thenReturn(255);
context.setDoc(document);
// Submit from the UI spaceReference=X&name=Y&templateProvider=XWiki.MyTemplateProvider
String templateProviderFullName = "XWiki.MyTemplateProvider";
when(mockRequest.getParameter("spaceReference")).thenReturn("X");
when(mockRequest.getParameter("name")).thenReturn("Y");
when(mockRequest.getParameter("templateprovider")).thenReturn(templateProviderFullName);
// Mock 1 existing template provider
mockExistingTemplateProviders(templateProviderFullName,
new DocumentReference("xwiki", Arrays.asList("XWiki"), "MyTemplateProvider"), Collections.EMPTY_LIST, null,
"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.Y.WebHome as non-terminal, since the template provider does not specify a "terminal"
// property and we fallback on the "type" property's value. Also using the template extracted from the template
// provider.
verify(mockURLFactory).createURL("X.Y", "WebHome", "edit",
"template=XWiki.MyTemplate&parent=Main.WebHome&title=Y", null, "xwiki", context);
} | Class | 2 |
void semicolon() {
final PathAndQuery res = PathAndQuery.parse("/;?a=b;c=d");
assertThat(res).isNotNull();
assertThat(res.path()).isEqualTo("/;");
assertThat(res.query()).isEqualTo("a=b;c=d");
// '%3B' in a query string should never be decoded into ';'.
final PathAndQuery res2 = PathAndQuery.parse("/%3b?a=b%3Bc=d");
assertThat(res2).isNotNull();
assertThat(res2.path()).isEqualTo("/;");
assertThat(res2.query()).isEqualTo("a=b%3Bc=d");
} | Base | 1 |
public void newDocumentWebHomeFromURL() throws Exception
{
// new document = xwiki:X.Y.WebHome
DocumentReference documentReference = new DocumentReference("xwiki", Arrays.asList("X", "Y"), "WebHome");
XWikiDocument document = mock(XWikiDocument.class);
when(document.getDocumentReference()).thenReturn(documentReference);
when(document.isNew()).thenReturn(true);
when(document.getLocalReferenceMaxLength()).thenReturn(255);
context.setDoc(document);
// Run the action
String result = action.render(context);
// The tests are below this line!
// Verify null is returned (this means the response has been returned)
assertNull(result);
// Note1: The bebavior is the same for both a top level space and a child space WebHome.
// Note2: The title is not "WebHome", but "Y" (the space's name) to avoid exposing "WebHome" in the UI.
verify(mockURLFactory).createURL("X.Y", "WebHome", "edit", "template=&parent=Main.WebHome&title=Y", null,
"xwiki", context);
} | Class | 2 |
public Media createMedia(String title, String description, Object mediaObject, String businessPath, Identity author) {
Media media = null;
if (mediaObject instanceof EfficiencyStatement) {
EfficiencyStatement statement = (EfficiencyStatement) mediaObject;
String xml = myXStream.toXML(statement);
media = mediaDao.createMedia(title, description, xml, EFF_MEDIA, businessPath, null, 90, author);
ThreadLocalUserActivityLogger.log(PortfolioLoggingAction.PORTFOLIO_MEDIA_ADDED, getClass(),
LoggingResourceable.wrap(media));
}
return media;
} | Base | 1 |
private List<GlossaryItem> loadGlossaryItemListFromFile(VFSLeaf glossaryFile) {
List<GlossaryItem> glossaryItemList = new ArrayList<>();
if (glossaryFile == null) { return new ArrayList<>(); }
Object glossObj = XStreamHelper.readObject(xstreamReader, glossaryFile);
if (glossObj instanceof ArrayList) {
ArrayList<GlossaryItem> glossItemsFromFile = (ArrayList<GlossaryItem>) glossObj;
glossaryItemList.addAll(glossItemsFromFile);
} else {
log.error("The Glossary-XML-File " + glossaryFile.toString() + " seems not to be correct!");
}
Collections.sort(glossaryItemList);
return glossaryItemList;
} | Base | 1 |
public OHttpSession removeSession(final String iSessionId) {
acquireExclusiveLock();
try {
return sessions.remove(iSessionId);
} finally {
releaseExclusiveLock();
}
}
| Class | 2 |
void checkVerificationCodeUnexistingUser()
{
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.checkVerificationCode(this.userReference, "some code"));
assertEquals(exceptionMessage, resetPasswordException.getMessage());
} | Base | 1 |
public static HttpURLConnection createHttpUrlConnection(URL url, String proxyHost, int proxyPort,
String proxyUsername, String proxyPassword) {
try {
Proxy proxy = getProxy(proxyHost, proxyPort, proxyUsername, proxyPassword);
// set proxy if exists.
if (proxy == null) {
return (HttpURLConnection) url.openConnection();
} else {
return (HttpURLConnection) url.openConnection(proxy);
}
} catch (IOException e) {
throw ErrorUtil.createCommandException(e.getMessage());
}
} | Base | 1 |
public void testRenameTo() throws Exception {
TestHttpData test = new TestHttpData("test", UTF_8, 0);
try {
File tmpFile = File.createTempFile(UUID.randomUUID().toString(), ".tmp");
tmpFile.deleteOnExit();
final int totalByteCount = 4096;
byte[] bytes = new byte[totalByteCount];
PlatformDependent.threadLocalRandom().nextBytes(bytes);
ByteBuf content = Unpooled.wrappedBuffer(bytes);
test.setContent(content);
boolean succ = test.renameTo(tmpFile);
assertTrue(succ);
FileInputStream fis = new FileInputStream(tmpFile);
try {
byte[] buf = new byte[totalByteCount];
int count = 0;
int offset = 0;
int size = totalByteCount;
while ((count = fis.read(buf, offset, size)) > 0) {
offset += count;
size -= count;
if (offset >= totalByteCount || size <= 0) {
break;
}
}
assertArrayEquals(bytes, buf);
assertEquals(0, fis.available());
} finally {
fis.close();
}
} finally {
//release the ByteBuf in AbstractMemoryHttpData
test.delete();
}
} | Base | 1 |
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()));
}
}
}
} | Class | 2 |
public CommandExecutionResult createRobustConcise(String code, String full, TimingStyle type, boolean compact) {
final Player player = new PlayerRobustConcise(type, full, getSkinParam(), ruler, compactByDefault || compact);
players.put(code, player);
lastPlayer = player;
return CommandExecutionResult.ok();
} | Base | 1 |
public void testWhitespaceBeforeTransferEncoding01() {
String requestStr = "GET /some/path HTTP/1.1\r\n" +
" Transfer-Encoding : chunked\r\n" +
"Content-Length: 1\r\n" +
"Host: netty.io\r\n\r\n" +
"a";
testInvalidHeaders0(requestStr);
} | Base | 1 |
public SpotProtocolDecoder(Protocol protocol) {
super(protocol);
try {
documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
xPath = XPathFactory.newInstance().newXPath();
messageExpression = xPath.compile("//messageList/message");
} catch (ParserConfigurationException | XPathExpressionException e) {
throw new RuntimeException(e);
}
} | Base | 1 |
public int size() {
return ByteUtils.bitLength(n.decode());
} | Class | 2 |
public void corsAccessCheck() {
BackendManager backendManager = new BackendManager(config,log);
assertTrue(backendManager.isCorsAccessAllowed("http://bla.com"));
backendManager.destroy();
} | Compound | 4 |
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);
} | Class | 2 |
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");
} | Class | 2 |
public void existingDocumentFromUITopLevelDocument() 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 name=Y
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("Y", "WebHome", "edit", "template=&parent=Main.WebHome&title=Y", null, "xwiki",
context);
} | Class | 2 |
public SAXReader(String xmlReaderClassName, boolean validating)
throws SAXException {
if (xmlReaderClassName != null) {
this.xmlReader = XMLReaderFactory
.createXMLReader(xmlReaderClassName);
}
this.validating = validating;
} | Base | 1 |
public Collection<StyleSignatureBasic> toSignatures() {
List<StyleSignatureBasic> results = new ArrayList<>(Collections.singletonList(StyleSignatureBasic.empty()));
boolean star = false;
for (Iterator<String> it = data.iterator(); it.hasNext();) {
String s = it.next();
if (s.endsWith("*")) {
star = true;
s = s.substring(0, s.length() - 1);
}
final String[] names = s.split(",");
final List<StyleSignatureBasic> tmp = new ArrayList<>();
for (StyleSignatureBasic ss : results)
for (String name : names)
tmp.add(ss.add(name));
results = tmp;
}
if (star)
for (ListIterator<StyleSignatureBasic> it = results.listIterator(); it.hasNext();) {
final StyleSignatureBasic tmp = it.next().addStar();
it.set(tmp);
}
return Collections.unmodifiableCollection(results);
} | Base | 1 |
public void testCurveCheckNegative_P256_attackPt2()
throws Exception {
// The malicious JWE contains a public key with order 2447
String maliciousJWE = "eyJhbGciOiJFQ0RILUVTK0ExMjhLVyIsImVuYyI6IkExMjhDQkMtSFMyNTYiLCJlcGsiOnsia3R5IjoiRUMiLCJ4IjoiWE9YR1E5XzZRQ3ZCZzN1OHZDSS1VZEJ2SUNBRWNOTkJyZnFkN3RHN29RNCIsInkiOiJoUW9XTm90bk56S2x3aUNuZUprTElxRG5UTnc3SXNkQkM1M1ZVcVZqVkpjIiwiY3J2IjoiUC0yNTYifX0.UGb3hX3ePAvtFB9TCdWsNkFTv9QWxSr3MpYNiSBdW630uRXRBT3sxw.6VpU84oMob16DxOR98YTRw.y1UslvtkoWdl9HpugfP0rSAkTw1xhm_LbK1iRXzGdpYqNwIG5VU33UBpKAtKFBoA1Kk_sYtfnHYAvn-aes4FTg.UZPN8h7FcvA5MIOq-Pkj8A";
JWEObject jweObject = JWEObject.parse(maliciousJWE);
ECPublicKey ephemeralPublicKey = jweObject.getHeader().getEphemeralPublicKey().toECPublicKey();
ECPrivateKey privateKey = generateECPrivateKey(ECKey.Curve.P_256);
try {
ECDH.ensurePointOnCurve(ephemeralPublicKey, privateKey);
fail();
} catch (JOSEException e) {
assertEquals("Invalid ephemeral public key: Point not on expected curve", e.getMessage());
}
} | Base | 1 |
private ModelAndView renameGroup(HttpServletRequest request, HttpServletResponse response) throws Exception {
String oldName = request.getParameter("groupName");
String newName = request.getParameter("newName");
if (StringUtils.hasText(oldName) && StringUtils.hasText(newName)) {
m_groupRepository.renameGroup(oldName, newName);
}
return listGroups(request, response);
} | Base | 1 |
public void translate(ServerSpawnPaintingPacket packet, GeyserSession session) {
Vector3f position = Vector3f.from(packet.getPosition().getX(), packet.getPosition().getY(), packet.getPosition().getZ());
PaintingEntity entity = new PaintingEntity(packet.getEntityId(),
session.getEntityCache().getNextEntityId().incrementAndGet(),
position, PaintingType.getByPaintingType(packet.getPaintingType()), packet.getDirection().ordinal());
session.getEntityCache().spawnEntity(entity);
} | Class | 2 |
void noEncoding() {
final PathAndQuery res = PathAndQuery.parse("/a?b=c");
assertThat(res).isNotNull();
assertThat(res.path()).isEqualTo("/a");
assertThat(res.query()).isEqualTo("b=c");
} | Base | 1 |
public void multipleValuesPerNameIterator() {
final HttpHeadersBase headers = newEmptyHeaders();
headers.add("name1", "value1");
headers.add("name1", "value2");
assertThat(headers.size()).isEqualTo(2);
final List<String> values = ImmutableList.copyOf(headers.valueIterator("name1"));
assertThat(values).containsExactly("value1", "value2");
} | Class | 2 |
private void ensureInitialized() throws SQLException {
if (!initialized) {
throw new PSQLException(
GT.tr(
"This SQLXML object has not been initialized, so you cannot retrieve data from it."),
PSQLState.OBJECT_NOT_IN_STATE);
}
// Is anyone loading data into us at the moment?
if (!active) {
return;
}
if (byteArrayOutputStream != null) {
try {
data = conn.getEncoding().decode(byteArrayOutputStream.toByteArray());
} catch (IOException ioe) {
throw new PSQLException(GT.tr("Failed to convert binary xml data to encoding: {0}.",
conn.getEncoding().name()), PSQLState.DATA_ERROR, ioe);
} finally {
byteArrayOutputStream = null;
active = false;
}
} else if (stringWriter != null) {
// This is also handling the work for Stream, SAX, and StAX Results
// as they will use the same underlying stringwriter variable.
//
data = stringWriter.toString();
stringWriter = null;
active = false;
} else if (domResult != null) {
// Copy the content from the result to a source
// and use the identify transform to get it into a
// friendlier result format.
try {
TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer();
DOMSource domSource = new DOMSource(domResult.getNode());
StringWriter stringWriter = new StringWriter();
StreamResult streamResult = new StreamResult(stringWriter);
transformer.transform(domSource, streamResult);
data = stringWriter.toString();
} catch (TransformerException te) {
throw new PSQLException(GT.tr("Unable to convert DOMResult SQLXML data to a string."),
PSQLState.DATA_ERROR, te);
} finally {
domResult = null;
active = false;
}
}
} | Base | 1 |
private static File newFile() throws IOException {
File file = File.createTempFile("netty-", ".tmp");
file.deleteOnExit();
final FileOutputStream out = new FileOutputStream(file);
out.write(data);
out.close();
return file;
} | Base | 1 |
public static SecretKey deriveSharedSecret(final ECPublicKey publicKey,
final ECPrivateKey privateKey,
final Provider provider)
throws JOSEException {
// Get an ECDH key agreement instance from the JCA provider
KeyAgreement keyAgreement;
try {
if (provider != null) {
keyAgreement = KeyAgreement.getInstance("ECDH", provider);
} else {
keyAgreement = KeyAgreement.getInstance("ECDH");
}
} catch (NoSuchAlgorithmException e) {
throw new JOSEException("Couldn't get an ECDH key agreement instance: " + e.getMessage(), e);
}
try {
keyAgreement.init(privateKey);
keyAgreement.doPhase(publicKey, true);
} catch (InvalidKeyException e) {
throw new JOSEException("Invalid key for ECDH key agreement: " + e.getMessage(), e);
}
return new SecretKeySpec(keyAgreement.generateSecret(), "AES");
} | Base | 1 |
public void translate(PacketViolationWarningPacket packet, GeyserSession session) {
// Not translated since this is something that the developers need to know
session.getConnector().getLogger().error("Packet violation warning sent from client! " + packet.toString());
} | Class | 2 |
public void testFileRegionCountLargerThenFile(ServerBootstrap sb, Bootstrap cb) throws Throwable {
File file = File.createTempFile("netty-", ".tmp");
file.deleteOnExit();
final FileOutputStream out = new FileOutputStream(file);
out.write(data);
out.close();
sb.childHandler(new SimpleChannelInboundHandler<ByteBuf>() {
@Override
protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) {
// Just drop the message.
}
});
cb.handler(new ChannelInboundHandlerAdapter());
Channel sc = sb.bind().sync().channel();
Channel cc = cb.connect(sc.localAddress()).sync().channel();
// Request file region which is bigger then the underlying file.
FileRegion region = new DefaultFileRegion(
new RandomAccessFile(file, "r").getChannel(), 0, data.length + 1024);
assertThat(cc.writeAndFlush(region).await().cause(), CoreMatchers.<Throwable>instanceOf(IOException.class));
cc.close().sync();
sc.close().sync();
} | Base | 1 |
private ModelAndView renameGroup(HttpServletRequest request, HttpServletResponse response) throws Exception {
String oldName = request.getParameter("groupName");
String newName = request.getParameter("newName");
if (StringUtils.hasText(oldName) && StringUtils.hasText(newName)) {
m_groupRepository.renameGroup(oldName, newName);
}
return listGroups(request, response);
} | Compound | 4 |
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));
} | Class | 2 |
private <T> byte[] marshallToBytes(JAXBElement<T> object, Class<T> type) throws SAMLException {
try {
JAXBContext context = JAXBContext.newInstance(type);
Marshaller marshaller = context.createMarshaller();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
marshaller.marshal(object, baos);
return baos.toByteArray();
} catch (JAXBException e) {
throw new SAMLException("Unable to marshallRequest JAXB SAML object to bytes.", e);
}
} | Base | 1 |
void percent() {
final PathAndQuery res = PathAndQuery.parse("/%25");
assertThat(res).isNotNull();
assertThat(res.path()).isEqualTo("/%25");
assertThat(res.query()).isNull();
} | Base | 1 |
public URIDryConverter(URI base, Map<PackageID, Manifest> dependencyManifests, boolean isBuild) {
super(base, dependencyManifests, isBuild);
this.base = URI.create(base.toString() + "/modules/info/");
try {
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
proxy = getProxy();
} catch (NoSuchAlgorithmException | KeyManagementException e) {
// ignore errors
}
} | Base | 1 |
public void configure(ServletContextHandler context) {
context.setContextPath("/");
context.getSessionHandler().setMaxInactiveInterval(serverConfig.getSessionTimeout());
context.setInitParameter(EnvironmentLoader.ENVIRONMENT_CLASS_PARAM, DefaultWebEnvironment.class.getName());
context.addEventListener(new EnvironmentLoaderListener());
context.addFilter(new FilterHolder(shiroFilter), "/*", EnumSet.allOf(DispatcherType.class));
context.addFilter(new FilterHolder(gitFilter), "/*", EnumSet.allOf(DispatcherType.class));
context.addServlet(new ServletHolder(preReceiveServlet), GitPreReceiveCallback.PATH + "/*");
context.addServlet(new ServletHolder(postReceiveServlet), GitPostReceiveCallback.PATH + "/*");
/*
* Add wicket servlet as the default servlet which will serve all requests failed to
* match a path pattern
*/
context.addServlet(new ServletHolder(wicketServlet), "/");
context.addServlet(new ServletHolder(attachmentUploadServlet), "/attachment_upload");
context.addServlet(new ServletHolder(new ClasspathAssetServlet(ImageScope.class)), "/img/*");
context.addServlet(new ServletHolder(new ClasspathAssetServlet(IconScope.class)), "/icon/*");
context.getSessionHandler().addEventListener(new HttpSessionListener() {
@Override
public void sessionCreated(HttpSessionEvent se) {
}
@Override
public void sessionDestroyed(HttpSessionEvent se) {
webSocketManager.onDestroySession(se.getSession().getId());
}
});
/*
* Configure a servlet to serve contents under site folder. Site folder can be used
* to hold site specific web assets.
*/
ServletHolder fileServletHolder = new ServletHolder(new FileAssetServlet(Bootstrap.getSiteDir()));
context.addServlet(fileServletHolder, "/site/*");
context.addServlet(fileServletHolder, "/robots.txt");
context.addServlet(new ServletHolder(jerseyServlet), "/rest/*");
} | Base | 1 |
public void withRestrictor() throws InvalidSyntaxException, MalformedObjectNameException {
setupRestrictor(new InnerRestrictor(true,false,true,false,true,false,true));
assertTrue(restrictor.isHttpMethodAllowed(HttpMethod.GET));
assertFalse(restrictor.isTypeAllowed(RequestType.EXEC));
assertTrue(restrictor.isAttributeReadAllowed(new ObjectName("java.lang:type=Memory"), "HeapMemoryUsage"));
assertFalse(restrictor.isAttributeWriteAllowed(new ObjectName("java.lang:type=Memory"), "HeapMemoryUsage"));
assertTrue(restrictor.isOperationAllowed(new ObjectName("java.lang:type=Memory"), "gc"));
assertFalse(restrictor.isRemoteAccessAllowed("localhost", "127.0.0.1"));
assertTrue(restrictor.isCorsAccessAllowed("http://bla.com"));
} | Compound | 4 |
final protected FontConfiguration getFontConfiguration() {
if (UseStyle.useBetaStyle() == false)
return FontConfiguration.create(skinParam, FontParam.TIMING, null);
return FontConfiguration.create(skinParam, StyleSignatureBasic.of(SName.root, SName.element, SName.timingDiagram)
.getMergedStyle(skinParam.getCurrentStyleBuilder()));
} | Base | 1 |
private DefaultHttpClient makeHttpClient() {
DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
try {
logger.debug("Installing forgiving hostname verifier and trust managers");
X509TrustManager trustManager = createTrustManager();
X509HostnameVerifier hostNameVerifier = createHostNameVerifier();
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, new TrustManager[] { trustManager }, new SecureRandom());
SSLSocketFactory ssf = new SSLSocketFactory(sslContext, hostNameVerifier);
ClientConnectionManager ccm = defaultHttpClient.getConnectionManager();
SchemeRegistry sr = ccm.getSchemeRegistry();
sr.register(new Scheme("https", 443, ssf));
} catch (NoSuchAlgorithmException e) {
logger.error("Error creating context to handle TLS connections: {}", e.getMessage());
} catch (KeyManagementException e) {
logger.error("Error creating context to handle TLS connections: {}", e.getMessage());
}
return defaultHttpClient;
} | Class | 2 |
public static byte[] decryptAuthenticated(final SecretKey secretKey,
final byte[] iv,
final byte[] cipherText,
final byte[] aad,
final byte[] authTag,
final Provider ceProvider,
final Provider macProvider)
throws JOSEException {
// Extract MAC + AES/CBC keys from input secret key
CompositeKey compositeKey = new CompositeKey(secretKey);
// AAD length to 8 byte array
byte[] al = AAD.computeLength(aad);
// Check MAC
int hmacInputLength = aad.length + iv.length + cipherText.length + al.length;
byte[] hmacInput = ByteBuffer.allocate(hmacInputLength).
put(aad).
put(iv).
put(cipherText).
put(al).
array();
byte[] hmac = HMAC.compute(compositeKey.getMACKey(), hmacInput, macProvider);
byte[] expectedAuthTag = Arrays.copyOf(hmac, compositeKey.getTruncatedMACByteLength());
boolean macCheckPassed = true;
if (! ConstantTimeUtils.areEqual(expectedAuthTag, authTag)) {
// Thwart timing attacks by delaying exception until after decryption
macCheckPassed = false;
}
byte[] plainText = decrypt(compositeKey.getAESKey(), iv, cipherText, ceProvider);
if (! macCheckPassed) {
throw new JOSEException("MAC check failed");
}
return plainText;
} | Base | 1 |
public static <T> T throw0(Throwable throwable) {
if (throwable == null) throw new NullPointerException();
getUnsafe().throwException(throwable);
throw new RuntimeException();
} | Class | 2 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.