code
stringlengths
12
2.05k
label_name
stringclasses
5 values
label
int64
0
4
default Optional<MediaType> contentType() { return getFirst(HttpHeaders.CONTENT_TYPE, MediaType.class); }
Class
2
public void setEntityResolver(EntityResolver entityResolver) { this.entityResolver = entityResolver; }
Base
1
private void processExtras(Bundle extras) { final String downloadUuid = extras.getString(ConversationsActivity.EXTRA_DOWNLOAD_UUID); final String text = extras.getString(Intent.EXTRA_TEXT); final String nick = extras.getString(ConversationsActivity.EXTRA_NICK); final boolean asQuote = extras.getBoolean(ConversationsActivity.EXTRA_AS_QUOTE); final boolean pm = extras.getBoolean(ConversationsActivity.EXTRA_IS_PRIVATE_MESSAGE, false); final List<Uri> uris = extractUris(extras); if (uris != null && uris.size() > 0) { final List<Uri> cleanedUris = cleanUris(new ArrayList<>(uris)); mediaPreviewAdapter.addMediaPreviews(Attachment.of(getActivity(), cleanedUris)); toggleInputMethod(); return; } if (nick != null) { if (pm) { Jid jid = conversation.getJid(); try { Jid next = Jid.of(jid.getLocal(), jid.getDomain(), nick); privateMessageWith(next); } catch (final IllegalArgumentException ignored) { //do nothing } } else { final MucOptions mucOptions = conversation.getMucOptions(); if (mucOptions.participating() || conversation.getNextCounterpart() != null) { highlightInConference(nick); } } } else { if (text != null && asQuote) { quoteText(text); } else { appendText(text); } } final Message message = downloadUuid == null ? null : conversation.findMessageWithFileAndUuid(downloadUuid); if (message != null) { startDownloadable(message); } }
Class
2
public void view(@RequestParam String filename, @RequestParam(required = false) String base, @RequestParam(required = false) Integer tailLines, HttpServletResponse response) throws IOException { securityCheck(filename); response.setContentType(MediaType.TEXT_PLAIN_VALUE); Path path = loggingPath(base); FileProvider fileProvider = getFileProvider(path); if (tailLines != null) { fileProvider.tailContent(path, filename, response.getOutputStream(), tailLines); } else { fileProvider.streamContent(path, filename, response.getOutputStream()); } }
Base
1
public void toScientificString(StringBuilder result) { assert(!isApproximate); if (isNegative()) { result.append('-'); } if (precision == 0) { result.append("0E+0"); return; } // NOTE: It is not safe to add to lOptPos (aka maxInt) or subtract from // rOptPos (aka -maxFrac) due to overflow. int upperPos = Math.min(precision + scale, lOptPos) - scale - 1; int lowerPos = Math.max(scale, rOptPos) - scale; int p = upperPos; result.append((char) ('0' + getDigitPos(p))); if ((--p) >= lowerPos) { result.append('.'); for (; p >= lowerPos; p--) { result.append((char) ('0' + getDigitPos(p))); } } result.append('E'); int _scale = upperPos + scale; if (_scale < 0) { _scale *= -1; result.append('-'); } else { result.append('+'); } if (_scale == 0) { result.append('0'); } int insertIndex = result.length(); while (_scale > 0) { int quot = _scale / 10; int rem = _scale % 10; result.insert(insertIndex, (char) ('0' + rem)); _scale = quot; } }
Base
1
public void translate(ServerPlayerAbilitiesPacket packet, GeyserSession session) { session.setCanFly(packet.isCanFly()); session.setFlying(packet.isFlying()); session.sendAdventureSettings(); }
Class
2
protected List<PropertySource> readPropertySourceListFromFiles(String files) { List<PropertySource> propertySources = new ArrayList<>(); Collection<PropertySourceLoader> propertySourceLoaders = getPropertySourceLoaders(); Optional<Collection<String>> filePathList = Optional.ofNullable(files) .filter(value -> !value.isEmpty()) .map(value -> value.split(FILE_SEPARATOR)) .map(Arrays::asList) .map(Collections::unmodifiableList); filePathList.ifPresent(list -> { if (!list.isEmpty()) { int order = AbstractPropertySourceLoader.DEFAULT_POSITION + 50; for (String filePath: list) { if (!propertySourceLoaders.isEmpty()) { String extension = NameUtils.extension(filePath); String fileName = NameUtils.filename(filePath); Optional<PropertySourceLoader> propertySourceLoader = Optional.ofNullable(loaderByFormatMap.get(extension)); if (propertySourceLoader.isPresent()) { if (LOG.isDebugEnabled()) { LOG.debug("Reading property sources from loader: {}", propertySourceLoader); } Optional<Map<String, Object>> properties = readPropertiesFromLoader(fileName, filePath, propertySourceLoader.get()); if (properties.isPresent()) { propertySources.add(PropertySource.of(filePath, properties.get(), order)); } order++; } else { throw new ConfigurationException("Unsupported properties file format: " + fileName); } } } } }); return propertySources; }
Base
1
public TMap readMapBegin() throws TException { return new TMap(readByte(), readByte(), readI32()); }
Base
1
private void parse(UserRequest ureq) { String[] sFiles = ureq.getHttpReq().getParameterValues(FORM_ID); if (sFiles == null || sFiles.length == 0) return; files = Arrays.asList(sFiles); }
Base
1
public void validateFail(ViolationCollector col) { }
Class
2
private Document parseFromBytes(byte[] bytes) throws SAMLException { DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); try { DocumentBuilder builder = documentBuilderFactory.newDocumentBuilder(); return builder.parse(new ByteArrayInputStream(bytes)); } catch (ParserConfigurationException | SAXException | IOException e) { throw new SAMLException("Unable to parse SAML v2.0 authentication response", e); } }
Base
1
public void testGetShellCommandLineBash_WithWorkingDirectory() throws Exception { Commandline cmd = new Commandline( new BourneShell() ); cmd.setExecutable( "/bin/echo" ); cmd.addArguments( new String[] { "hello world" } ); File root = File.listRoots()[0]; File workingDirectory = new File( root, "path with spaces" ); cmd.setWorkingDirectory( workingDirectory ); String[] shellCommandline = cmd.getShellCommandline(); assertEquals( "Command line size", 3, shellCommandline.length ); assertEquals( "/bin/sh", shellCommandline[0] ); assertEquals( "-c", shellCommandline[1] ); String expectedShellCmd = "cd \"" + root.getAbsolutePath() + "path with spaces\" && /bin/echo \'hello world\'"; if ( Os.isFamily( Os.FAMILY_WINDOWS ) ) { expectedShellCmd = "cd \"" + root.getAbsolutePath() + "path with spaces\" && \\bin\\echo \'hello world\'"; } assertEquals( expectedShellCmd, shellCommandline[2] ); }
Base
1
public void testLoadMapper_serializade() { //create a mapper String mapperId = UUID.randomUUID().toString(); String sessionId = UUID.randomUUID().toString().substring(0, 32); PersistentMapper sMapper = new PersistentMapper("mapper-to-persist"); PersistedMapper pMapper = mapperDao.persistMapper(sessionId, mapperId, sMapper, -1); Assert.assertNotNull(pMapper); dbInstance.commitAndCloseSession(); //load the mapper PersistedMapper loadedMapper = mapperDao.loadByMapperId(mapperId); Assert.assertNotNull(loadedMapper); Assert.assertEquals(pMapper, loadedMapper); Assert.assertEquals(mapperId, loadedMapper.getMapperId()); Object objReloaded = XStreamHelper.createXStreamInstance().fromXML(pMapper.getXmlConfiguration()); Assert.assertTrue(objReloaded instanceof PersistentMapper); PersistentMapper sMapperReloaded = (PersistentMapper)objReloaded; Assert.assertEquals("mapper-to-persist", sMapperReloaded.getKey()); }
Base
1
public void encodeByteArray() { Packet<byte[]> packet = new Packet<>(Parser.BINARY_EVENT); packet.data = "abc".getBytes(Charset.forName("UTF-8")); packet.id = 23; packet.nsp = "/cool"; Helpers.testBin(packet); }
Base
1
public static boolean isPermitted( final Optional<AuthenticationService> authenticationService, final Optional<User> optionalUser, final JsonRpcMethod jsonRpcMethod) { AtomicBoolean foundMatchingPermission = new AtomicBoolean(); if (authenticationService.isPresent()) { if (optionalUser.isPresent()) { User user = optionalUser.get(); for (String perm : jsonRpcMethod.getPermissions()) { user.isAuthorized( perm, (authed) -> { if (authed.result()) { LOG.trace( "user {} authorized : {} via permission {}", user, jsonRpcMethod.getName(), perm); foundMatchingPermission.set(true); } }); } } } else { // no auth provider configured thus anything is permitted foundMatchingPermission.set(true); } if (!foundMatchingPermission.get()) { LOG.trace("user NOT authorized : {}", jsonRpcMethod.getName()); } return foundMatchingPermission.get(); }
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 (!haskey) { // 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(); setup(ad); ghash.update(ciphertext, ciphertextOffset, dataLen); ghash.pad(ad != null ? ad.length : 0, dataLen); ghash.finish(enciv, 0, 16); int temp = 0; for (int index = 0; index < 16; ++index) temp |= (hashKey[index] ^ enciv[index] ^ ciphertext[ciphertextOffset + dataLen + index]); if ((temp & 0xFF) != 0) Noise.throwBadTagException(); encryptCTR(ciphertext, ciphertextOffset, plaintext, plaintextOffset, dataLen); return dataLen; }
Base
1
public void existingDocumentFromUITemplateProviderSpecified() throws Exception { // current document = xwiki:Main.WebHome DocumentReference documentReference = new DocumentReference("xwiki", Arrays.asList("Main"), "WebHome"); XWikiDocument document = mock(XWikiDocument.class); when(document.getDocumentReference()).thenReturn(documentReference); when(document.isNew()).thenReturn(false); when(document.getLocalReferenceMaxLength()).thenReturn(255); context.setDoc(document); // Submit from the UI spaceReference=X&name=Y&templateProvider=XWiki.MyTemplateProvider String templateProviderFullName = "XWiki.MyTemplateProvider"; when(mockRequest.getParameter("spaceReference")).thenReturn("X"); when(mockRequest.getParameter("name")).thenReturn("Y"); when(mockRequest.getParameter("templateprovider")).thenReturn(templateProviderFullName); // Mock 1 existing template provider mockExistingTemplateProviders(templateProviderFullName, new DocumentReference("xwiki", Arrays.asList("XWiki"), "MyTemplateProvider"), Collections.EMPTY_LIST); // Run the action String result = action.render(context); // The tests are below this line! // Verify null is returned (this means the response has been returned) assertNull(result); // Note: We are creating X.Y and using the template extracted from the template provider. verify(mockURLFactory).createURL("X.Y", "WebHome", "edit", "template=XWiki.MyTemplate&parent=Main.WebHome&title=Y", null, "xwiki", context); }
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 (keySpec == null) { // 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(); try { setup(ad); int result = cipher.update(plaintext, plaintextOffset, length, ciphertext, ciphertextOffset); cipher.doFinal(ciphertext, ciphertextOffset + result); } catch (InvalidKeyException e) { // Shouldn't happen. throw new IllegalStateException(e); } catch (InvalidAlgorithmParameterException e) { // Shouldn't happen. throw new IllegalStateException(e); } catch (IllegalBlockSizeException e) { // Shouldn't happen. throw new IllegalStateException(e); } catch (BadPaddingException e) { // Shouldn't happen. throw new IllegalStateException(e); } ghash.update(ciphertext, ciphertextOffset, length); ghash.pad(ad != null ? ad.length : 0, length); ghash.finish(ciphertext, ciphertextOffset + length, 16); for (int index = 0; index < 16; ++index) ciphertext[ciphertextOffset + length + index] ^= hashKey[index]; return length + 16; }
Base
1
private void processReturnFiles(VFSLeaf target, List<BulkAssessmentRow> rows) { Map<String, BulkAssessmentRow> assessedIdToRow = new HashMap<>(); for(BulkAssessmentRow row:rows) { assessedIdToRow.put(row.getAssessedId(), row); } if(target.exists()) { File parentTarget = ((LocalImpl)target).getBasefile().getParentFile(); ZipEntry entry; try(InputStream is = target.getInputStream(); ZipInputStream zis = new ZipInputStream(is)) { byte[] b = new byte[FileUtils.BSIZE]; while ((entry = zis.getNextEntry()) != null) { if(!entry.isDirectory()) { while (zis.read(b) > 0) { //continue } Path op = new File(parentTarget, entry.getName()).toPath(); if(!Files.isHidden(op) && !op.toFile().isDirectory()) { Path parentDir = op.getParent(); String assessedId = parentDir.getFileName().toString(); String filename = op.getFileName().toString(); BulkAssessmentRow row; if(assessedIdToRow.containsKey(assessedId)) { row = assessedIdToRow.get(assessedId); } else { row = new BulkAssessmentRow(); row.setAssessedId(assessedId); assessedIdToRow.put(assessedId, row); rows.add(row); } if(row.getReturnFiles() == null) { row.setReturnFiles(new ArrayList<String>(2)); } row.getReturnFiles().add(filename); } } } } catch(Exception e) { logError("", e); } } }
Base
1
public void testBourneShellQuotingCharacters() throws Exception { // { ' ', '$', ';', '&', '|', '<', '>', '*', '?', '(', ')' }; // test with values http://steve-parker.org/sh/bourne.shtml Appendix B - Meta-characters and Reserved Words Commandline commandline = new Commandline( newShell() ); commandline.setExecutable( "chmod" ); commandline.getShell().setQuotedArgumentsEnabled( true ); commandline.createArg().setValue( " " ); commandline.createArg().setValue( "|" ); commandline.createArg().setValue( "&&" ); commandline.createArg().setValue( "||" ); commandline.createArg().setValue( ";" ); commandline.createArg().setValue( ";;" ); commandline.createArg().setValue( "&" ); commandline.createArg().setValue( "()" ); commandline.createArg().setValue( "<" ); commandline.createArg().setValue( "<<" ); commandline.createArg().setValue( ">" ); commandline.createArg().setValue( ">>" ); commandline.createArg().setValue( "*" ); commandline.createArg().setValue( "?" ); commandline.createArg().setValue( "[" ); commandline.createArg().setValue( "]" ); commandline.createArg().setValue( "{" ); commandline.createArg().setValue( "}" ); commandline.createArg().setValue( "`" ); String[] lines = commandline.getShellCommandline(); System.out.println( Arrays.asList( lines ) ); assertEquals( "/bin/sh", lines[0] ); assertEquals( "-c", lines[1] ); assertEquals( "chmod ' ' '|' '&&' '||' ';' ';;' '&' '()' '<' '<<' '>' '>>' '*' '?' '[' ']' '{' '}' '`'", lines[2] ); }
Base
1
public void setErrorHandler(ErrorHandler errorHandler) { this.errorHandler = errorHandler; }
Base
1
public void sendError(int sc, String msg) throws IOException { if (isIncluding()) { Logger.log(Logger.ERROR, Launcher.RESOURCES, "IncludeResponse.Error", new String[] { "" + sc, msg }); return; } Logger.log(Logger.DEBUG, Launcher.RESOURCES, "WinstoneResponse.SendingError", new String[] { "" + sc, msg }); if ((this.webAppConfig != null) && (this.req != null)) { RequestDispatcher rd = this.webAppConfig .getErrorDispatcherByCode(req.getRequestURI(), sc, msg, null); if (rd != null) { try { rd.forward(this.req, this); return; } catch (IllegalStateException err) { throw err; } catch (IOException err) { throw err; } catch (Throwable err) { Logger.log(Logger.WARNING, Launcher.RESOURCES, "WinstoneResponse.ErrorInErrorPage", new String[] { rd.getName(), sc + "" }, err); return; } } } // If we are here there was no webapp and/or no request object, so // show the default error page if (this.errorStatusCode == null) { this.statusCode = sc; } String output = Launcher.RESOURCES.getString("WinstoneResponse.ErrorPage", new String[] { sc + "", (msg == null ? "" : msg), "", Launcher.RESOURCES.getString("ServerVersion"), "" + new Date() }); setContentLength(output.getBytes(getCharacterEncoding()).length); Writer out = getWriter(); out.write(output); out.flush(); }
Base
1
public URL createURL(String spaces, String name, String queryString, String anchor, String wikiId, XWikiContext context, FilesystemExportContext exportContext) throws Exception { // Check if the current user has the right to view the SX file. We do this since this is what would happen // in XE when a SX action is called (check done in XWikiAction). // Note that we cannot just open an HTTP connection to the SX action here since we wouldn't be authenticated... // Thus we have to simulate the same behavior as the SX action... List<String> spaceNames = this.legacySpaceResolve.resolve(spaces); DocumentReference sxDocumentReference = new DocumentReference(wikiId, spaceNames, name); this.authorizationManager.checkAccess(Right.VIEW, sxDocumentReference); // Set the SX document as the current document in the XWiki Context since unfortunately the SxSource code // uses the current document in the context instead of accepting it as a parameter... XWikiDocument sxDocument = context.getWiki().getDocument(sxDocumentReference, context); Map<String, Object> backup = new HashMap<>(); XWikiDocument.backupContext(backup, context); try { sxDocument.setAsContextDoc(context); return processSx(spaceNames, name, queryString, context, exportContext); } finally { XWikiDocument.restoreContext(backup, context); } }
Base
1
private static boolean validateChainData(JsonNode data) throws Exception { ECPublicKey lastKey = null; boolean validChain = false; for (JsonNode node : data) { JWSObject jwt = JWSObject.parse(node.asText()); if (!validChain) { validChain = EncryptionUtils.verifyJwt(jwt, EncryptionUtils.getMojangPublicKey()); } if (lastKey != null) { if (!EncryptionUtils.verifyJwt(jwt, lastKey)) return false; } JsonNode payloadNode = JSON_MAPPER.readTree(jwt.getPayload().toString()); JsonNode ipkNode = payloadNode.get("identityPublicKey"); Preconditions.checkState(ipkNode != null && ipkNode.getNodeType() == JsonNodeType.STRING, "identityPublicKey node is missing in chain"); lastKey = EncryptionUtils.generateKey(ipkNode.asText()); } return validChain; }
Class
2
public Operation.OperationResult executeFixedCostOperation( final MessageFrame frame, final EVM evm) { Bytes shiftAmount = frame.popStackItem(); if (shiftAmount.size() > 4 && (shiftAmount = shiftAmount.trimLeadingZeros()).size() > 4) { frame.popStackItem(); frame.pushStackItem(UInt256.ZERO); } else { final int shiftAmountInt = shiftAmount.toInt(); final Bytes value = leftPad(frame.popStackItem()); if (shiftAmountInt >= 256) { frame.pushStackItem(UInt256.ZERO); } else { frame.pushStackItem(value.shiftLeft(shiftAmountInt)); } } return successResponse; }
Base
1
public void translate(LoginDisconnectPacket packet, GeyserSession session) { // The client doesn't manually get disconnected so we have to do it ourselves session.disconnect(MessageTranslator.convertMessage(packet.getReason(), session.getLocale())); }
Class
2
public void translate(EntityEventPacket packet, GeyserSession session) { switch (packet.getType()) { case EATING_ITEM: // Resend the packet so we get the eating sounds session.sendUpstreamPacket(packet); return; case COMPLETE_TRADE: ClientSelectTradePacket selectTradePacket = new ClientSelectTradePacket(packet.getData()); session.sendDownstreamPacket(selectTradePacket); session.scheduleInEventLoop(() -> { Entity villager = session.getPlayerEntity(); Inventory openInventory = session.getOpenInventory(); if (openInventory instanceof MerchantContainer) { MerchantContainer merchantInventory = (MerchantContainer) openInventory; VillagerTrade[] trades = merchantInventory.getVillagerTrades(); if (trades != null && packet.getData() >= 0 && packet.getData() < trades.length) { VillagerTrade trade = merchantInventory.getVillagerTrades()[packet.getData()]; openInventory.setItem(2, GeyserItemStack.from(trade.getOutput()), session); villager.getMetadata().put(EntityData.TRADE_XP, trade.getXp() + villager.getMetadata().getInt(EntityData.TRADE_XP)); villager.updateBedrockMetadata(session); } } }, 100, TimeUnit.MILLISECONDS); return; } session.getConnector().getLogger().debug("Did not translate incoming EntityEventPacket: " + packet.toString()); }
Class
2
private void sendStreamingResponse(HttpExchange pExchange, ParsedUri pParsedUri, JSONStreamAware pJson) throws IOException { Headers headers = pExchange.getResponseHeaders(); if (pJson != null) { headers.set("Content-Type", getMimeType(pParsedUri) + "; charset=utf-8"); String callback = pParsedUri.getParameter(ConfigKey.CALLBACK.getKeyValue()); pExchange.sendResponseHeaders(200, 0); Writer writer = new OutputStreamWriter(pExchange.getResponseBody(), "UTF-8"); IoUtil.streamResponseAndClose(writer, pJson, callback); } else { headers.set("Content-Type", "text/plain"); pExchange.sendResponseHeaders(200,-1); } }
Base
1
final void set(CharSequence name, String... values) { final AsciiString normalizedName = normalizeName(name); requireNonNull(values, "values"); final int h = normalizedName.hashCode(); final int i = index(h); remove0(h, i, normalizedName); for (String v : values) { requireNonNullElement(values, v); add0(h, i, normalizedName, v); } }
Class
2
public void translate(LoginSuccessPacket packet, GeyserSession session) { PlayerEntity playerEntity = session.getPlayerEntity(); AuthType remoteAuthType = session.getRemoteAuthType(); // Required, or else Floodgate players break with Spigot chunk caching GameProfile profile = packet.getProfile(); playerEntity.setUsername(profile.getName()); playerEntity.setUuid(profile.getId()); // Check if they are not using a linked account if (remoteAuthType == AuthType.OFFLINE || playerEntity.getUuid().getMostSignificantBits() == 0) { SkinManager.handleBedrockSkin(playerEntity, session.getClientData()); } if (remoteAuthType == AuthType.FLOODGATE) { // We'll send the skin upload a bit after the handshake packet (aka this packet), // because otherwise the global server returns the data too fast. session.getAuthData().upload(session.getConnector()); } }
Class
2
public void translate(ServerSpawnPlayerPacket packet, GeyserSession session) { Vector3f position = Vector3f.from(packet.getX(), packet.getY(), packet.getZ()); Vector3f rotation = Vector3f.from(packet.getYaw(), packet.getPitch(), packet.getYaw()); PlayerEntity entity; if (packet.getUuid().equals(session.getPlayerEntity().getUuid())) { // Server is sending a fake version of the current player entity = new PlayerEntity(session.getPlayerEntity().getProfile(), packet.getEntityId(), session.getEntityCache().getNextEntityId().incrementAndGet(), position, Vector3f.ZERO, rotation); } else { entity = session.getEntityCache().getPlayerEntity(packet.getUuid()); if (entity == null) { GeyserConnector.getInstance().getLogger().error(LanguageUtils.getLocaleStringLog("geyser.entity.player.failed_list", packet.getUuid())); return; } entity.setEntityId(packet.getEntityId()); entity.setPosition(position); entity.setRotation(rotation); } session.getEntityCache().cacheEntity(entity); entity.sendPlayer(session); SkinManager.requestAndHandleSkinAndCape(entity, session, null); }
Class
2
public static SecretKey decryptCEK(final PrivateKey priv, final byte[] encryptedCEK, final int keyLength, final Provider provider) throws JOSEException { try { Cipher cipher = CipherHelper.getInstance("RSA/ECB/PKCS1Padding", provider); cipher.init(Cipher.DECRYPT_MODE, priv); byte[] secretKeyBytes = cipher.doFinal(encryptedCEK); if (ByteUtils.bitLength(secretKeyBytes) != keyLength) { // CEK key length mismatch return null; } return new SecretKeySpec(secretKeyBytes, "AES"); } catch (Exception e) { // java.security.NoSuchAlgorithmException // java.security.InvalidKeyException // javax.crypto.IllegalBlockSizeException // javax.crypto.BadPaddingException throw new JOSEException("Couldn't decrypt Content Encryption Key (CEK): " + e.getMessage(), e); } }
Class
2
public void getPermissions() { List<String> permissions = method.getPermissions(); assertThat(permissions).containsExactlyInAnyOrder("net:*", "net:listening", "*:*"); }
Class
2
private File createTemporaryFolderIn(File parentFolder) throws IOException { File createdFolder = null; for (int i = 0; i < TEMP_DIR_ATTEMPTS; ++i) { // Use createTempFile to get a suitable folder name. String suffix = ".tmp"; File tmpFile = File.createTempFile(TMP_PREFIX, suffix, parentFolder); String tmpName = tmpFile.toString(); // Discard .tmp suffix of tmpName. String folderName = tmpName.substring(0, tmpName.length() - suffix.length()); createdFolder = new File(folderName); if (createdFolder.mkdir()) { tmpFile.delete(); return createdFolder; } tmpFile.delete(); } throw new IOException("Unable to create temporary directory in: " + parentFolder.toString() + ". Tried " + TEMP_DIR_ATTEMPTS + " times. " + "Last attempted to create: " + createdFolder.toString()); }
Class
2
private static String encodeToPercents(Bytes value, boolean isPath) { final BitSet allowedChars = isPath ? ALLOWED_PATH_CHARS : ALLOWED_QUERY_CHARS; final int length = value.length; boolean needsEncoding = false; for (int i = 0; i < length; i++) { if (!allowedChars.get(value.data[i] & 0xFF)) { needsEncoding = true; break; } } if (!needsEncoding) { // Deprecated, but it fits perfect for our use case. // noinspection deprecation return new String(value.data, 0, 0, length); } final StringBuilder buf = new StringBuilder(length); for (int i = 0; i < length; i++) { final int b = value.data[i] & 0xFF; if (b == PERCENT_ENCODING_MARKER && (i + 1) < length) { final int marker = value.data[i + 1] & 0xFF; final String percentEncodedChar = MARKER_TO_PERCENT_ENCODED_CHAR[marker]; if (percentEncodedChar != null) { buf.append(percentEncodedChar); i++; continue; } } if (allowedChars.get(b)) { buf.append((char) b); } else if (b == ' ') { if (isPath) { buf.append("%20"); } else { buf.append('+'); } } else { buf.append('%'); appendHexNibble(buf, b >>> 4); appendHexNibble(buf, b & 0xF); } } return buf.toString(); }
Base
1
public void translate(ServerChatPacket packet, GeyserSession session) { TextPacket textPacket = new TextPacket(); textPacket.setPlatformChatId(""); textPacket.setSourceName(""); textPacket.setXuid(session.getAuthData().getXboxUUID()); switch (packet.getType()) { case CHAT: textPacket.setType(TextPacket.Type.CHAT); break; case SYSTEM: textPacket.setType(TextPacket.Type.SYSTEM); break; case NOTIFICATION: textPacket.setType(TextPacket.Type.TIP); break; default: textPacket.setType(TextPacket.Type.RAW); break; } textPacket.setNeedsTranslation(false); textPacket.setMessage(MessageTranslator.convertMessage(packet.getMessage(), session.getLocale())); session.sendUpstreamPacket(textPacket); }
Class
2
void equal() { final PathAndQuery res = PathAndQuery.parse("/=?a=b=1"); assertThat(res).isNotNull(); assertThat(res.path()).isEqualTo("/="); assertThat(res.query()).isEqualTo("a=b=1"); // '%3D' in a query string should never be decoded into '='. final PathAndQuery res2 = PathAndQuery.parse("/%3D?a%3db=1"); assertThat(res2).isNotNull(); assertThat(res2.path()).isEqualTo("/="); assertThat(res2.query()).isEqualTo("a%3Db=1"); }
Base
1
public void existingDocumentFromUINoName() throws Exception { // current document = xwiki:Main.WebHome DocumentReference documentReference = new DocumentReference("xwiki", Arrays.asList("Main"), "WebHome"); XWikiDocument document = mock(XWikiDocument.class); when(document.getDocumentReference()).thenReturn(documentReference); when(document.isNew()).thenReturn(false); when(document.getLocalReferenceMaxLength()).thenReturn(255); context.setDoc(document); // Just landed on the create page or submitted with no values (no name) specified. // Run the action String result = action.render(context); // The tests are below this line! // Verify that the create template is rendered, so the UI is displayed for the user to enter the missing values. assertEquals("create", result); // We should not get this far so no redirect should be done, just the template will be rendered. verify(mockURLFactory, never()).createURL(any(), any(), any(), any(), any(), any(), any(XWikiContext.class)); }
Class
2
public void translate(AnimatePacket packet, GeyserSession session) { // Stop the player sending animations before they have fully spawned into the server if (!session.isSpawned()) { return; } switch (packet.getAction()) { case SWING_ARM: // Delay so entity damage can be processed first session.scheduleInEventLoop(() -> session.sendDownstreamPacket(new ClientPlayerSwingArmPacket(Hand.MAIN_HAND)), 25, TimeUnit.MILLISECONDS ); break; // These two might need to be flipped, but my recommendation is getting moving working first case ROW_LEFT: // Packet value is a float of how long one has been rowing, so we convert that into a boolean session.setSteeringLeft(packet.getRowingTime() > 0.0); ClientSteerBoatPacket steerLeftPacket = new ClientSteerBoatPacket(session.isSteeringLeft(), session.isSteeringRight()); session.sendDownstreamPacket(steerLeftPacket); break; case ROW_RIGHT: session.setSteeringRight(packet.getRowingTime() > 0.0); ClientSteerBoatPacket steerRightPacket = new ClientSteerBoatPacket(session.isSteeringLeft(), session.isSteeringRight()); session.sendDownstreamPacket(steerRightPacket); break; } }
Class
2
protected DocumentReference resolveTemplate(String template) { if (StringUtils.isNotBlank(template)) { DocumentReference templateReference = this.currentmixedReferenceResolver.resolve(template); // Make sure the current user have access to the template document before copying it if (this.autorization.hasAccess(Right.VIEW, templateReference)) { return templateReference; } } return null; }
Class
2
void validSave() throws Exception { when(mockClonedDocument.getRCSVersion()).thenReturn(new Version("1.2")); when(mockClonedDocument.getComment()).thenReturn("My Changes"); when(mockClonedDocument.getLock(this.context)).thenReturn(mock(XWikiLock.class)); when(mockForm.getTemplate()).thenReturn(""); assertFalse(saveAction.save(this.context)); assertEquals(new Version("1.2"), this.context.get("SaveAction.savedObjectVersion")); verify(mockClonedDocument).readFromTemplate("", this.context); verify(mockClonedDocument).setAuthor("XWiki.FooBar"); verify(mockClonedDocument).setMetaDataDirty(true); verify(this.xWiki).checkSavingDocument(USER_REFERENCE, mockClonedDocument, "My Changes", false, this.context); verify(this.xWiki).saveDocument(mockClonedDocument, "My Changes", false, this.context); verify(mockClonedDocument).removeLock(this.context); }
Class
2
final void setObject(CharSequence name, Object... values) { final AsciiString normalizedName = normalizeName(name); requireNonNull(values, "values"); final int h = normalizedName.hashCode(); final int i = index(h); remove0(h, i, normalizedName); for (Object v: values) { requireNonNullElement(values, v); add0(h, i, normalizedName, fromObject(v)); } }
Class
2
public static long compileTime() { return 1649510957985L; }
Base
1
private static void validate(final byte[] iv, final int authTagLength) throws JOSEException { if (ByteUtils.bitLength(iv) != IV_BIT_LENGTH) { throw new JOSEException(String.format("IV length of %d bits is required, got %d", IV_BIT_LENGTH, ByteUtils.bitLength(iv))); } if (authTagLength != AUTH_TAG_BIT_LENGTH) { throw new JOSEException(String.format("Authentication tag length of %d bits is required, got %d", AUTH_TAG_BIT_LENGTH, authTagLength)); } }
Class
2
public void handle(final HttpServletRequest request, final HttpServletResponse response) throws Exception { new ContextualHttpServletRequest(request) { @Override public void process() throws Exception { ServletContexts.instance().setRequest(request); if (request.getQueryString() == null) { throw new ServletException("Invalid request - no component specified"); } Set<Component> components = new HashSet<Component>(); Set<Type> types = new HashSet<Type>(); response.setContentType("text/javascript"); Enumeration e = request.getParameterNames(); while (e.hasMoreElements()) { String componentName = ((String) e.nextElement()).trim(); Component component = Component.forName(componentName); if (component == null) { try { Class c = Reflections.classForName(componentName); appendClassSource(response.getOutputStream(), c, types); } catch (ClassNotFoundException ex) { log.error(String.format("Component not found: [%s]", componentName)); throw new ServletException("Invalid request - component not found."); } } else { components.add(component); } } generateComponentInterface(components, response.getOutputStream(), types); } }.run(); }
Class
2
public Controller execute(FolderComponent folderComponent, UserRequest ureq, WindowControl wControl, Translator trans) { setTranslator(trans); currentContainer = folderComponent.getCurrentContainer(); if (currentContainer.canWrite() != VFSConstants.YES) { throw new AssertException("Cannot write to current folder."); } status = FolderCommandHelper.sanityCheck(wControl, folderComponent); if(status == FolderCommandStatus.STATUS_FAILED) { return null; } selection = new FileSelection(ureq, folderComponent.getCurrentContainerPath()); status = FolderCommandHelper.sanityCheck3(wControl, folderComponent, selection); if(status == FolderCommandStatus.STATUS_FAILED) { return null; } if(selection.getFiles().isEmpty()) { status = FolderCommandStatus.STATUS_FAILED; wControl.setWarning(trans.translate("warning.file.selection.empty")); return null; } initForm(ureq); return this; }
Base
1
public static Object deserialize(byte[] data) throws IOException, ClassNotFoundException { ByteArrayInputStream in = new ByteArrayInputStream(data); ObjectInputStream is = new ObjectInputStream(in); return is.readObject(); }
Base
1
public void init(KeyGenerationParameters param) { this.param = (RSAKeyGenerationParameters)param; this.iterations = getNumberOfIterations(this.param.getStrength(), this.param.getCertainty()); }
Class
2
public void setAllShouldOverwriteSomeAndLeaveOthersUntouched() { final HttpHeadersBase h1 = newEmptyHeaders(); h1.add("name1", "value1"); h1.add("name2", "value2"); h1.add("name2", "value3"); h1.add("name3", "value4"); final HttpHeadersBase h2 = newEmptyHeaders(); h2.add("name1", "value5"); h2.add("name2", "value6"); h2.add("name1", "value7"); final HttpHeadersBase expected = newEmptyHeaders(); expected.add("name1", "value5"); expected.add("name2", "value6"); expected.add("name1", "value7"); expected.add("name3", "value4"); h1.set(h2); assertThat(h1).isEqualTo(expected); }
Class
2
public BourneShell( boolean isLoginShell ) { setShellCommand( "/bin/sh" ); setArgumentQuoteDelimiter( '\'' ); setExecutableQuoteDelimiter( '\"' ); setSingleQuotedArgumentEscaped( true ); setSingleQuotedExecutableEscaped( false ); setQuotedExecutableEnabled( true ); setArgumentEscapePattern("'\\%s'"); if ( isLoginShell ) { addShellArg( "-l" ); } }
Base
1
private ServiceStat getRateLimitOpCountStat() throws Throwable { URI managementServiceUri = this.host.getManagementServiceUri(); return this.host.getServiceStats(managementServiceUri) .get(ServiceHostManagementService.STAT_NAME_RATE_LIMITED_OP_COUNT); }
Class
2
protected void runTeardown() { Assert.assertTrue("Error during initialization", messagedInitialization); Assert.assertTrue("HTTP connection is not allowed", messagedAccessDenied); }
Class
2
public void handle(HttpServletRequest request, final HttpServletResponse response) throws Exception { // We're sending an XML response, so set the response content type to text/xml response.setContentType("text/xml"); // Parse the incoming request as XML SAXReader xmlReader = new SAXReader(); Document doc = xmlReader.read(request.getInputStream()); Element env = doc.getRootElement(); final List<PollRequest> polls = unmarshalRequests(env); new ContextualHttpServletRequest(request) { @Override public void process() throws Exception { for (PollRequest req : polls) { req.poll(); } // Package up the response marshalResponse(polls, response.getOutputStream()); } }.run(); }
Class
2
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { String filename = file.getFileName().toString(); 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 DomainSocketAddress newSocketAddress() { try { File file; do { file = File.createTempFile("NETTY", "UDS"); if (!file.delete()) { throw new IOException("failed to delete: " + file); } } while (file.getAbsolutePath().length() > 128); return new DomainSocketAddress(file); } catch (IOException e) { throw new IllegalStateException(e); } }
Base
1
protected void parseModuleConfigFile(Digester digester, String path) throws UnavailableException { InputStream input = null; try { URL url = getServletContext().getResource(path); // If the config isn't in the servlet context, try the class loader // which allows the config files to be stored in a jar if (url == null) { url = getClass().getResource(path); } if (url == null) { String msg = internal.getMessage("configMissing", path); log.error(msg); throw new UnavailableException(msg); } InputSource is = new InputSource(url.toExternalForm()); input = url.openStream(); is.setByteStream(input); digester.parse(is); } catch (MalformedURLException e) { handleConfigException(path, e); } catch (IOException e) { handleConfigException(path, e); } catch (SAXException e) { handleConfigException(path, e); } finally { if (input != null) { try { input.close(); } catch (IOException e) { throw new UnavailableException(e.getMessage()); } } } }
Class
2
public Document read(Reader reader) throws DocumentException { InputSource source = new InputSource(reader); if (this.encoding != null) { source.setEncoding(this.encoding); } return read(source); }
Base
1
static public UStroke getStrokeInternal(IGroup group, ISkinParam skinParam, Style style) { final Colors colors = group.getColors(); if (colors.getSpecificLineStroke() != null) return colors.getSpecificLineStroke(); if (style != null) return style.getStroke(); if (group.getUSymbol() != null && group.getUSymbol() != USymbols.PACKAGE) return group.getUSymbol().getSkinParameter().getStroke(skinParam, group.getStereotype()); return GeneralImageBuilder.getForcedStroke(group.getStereotype(), skinParam); }
Base
1
public void testCurveCheckOk() throws Exception { ECPublicKey ephemeralPublicKey = generateECPublicKey(ECKey.Curve.P_256); ECPrivateKey privateKey = generateECPrivateKey(ECKey.Curve.P_256); ECDH.ensurePointOnCurve(ephemeralPublicKey, privateKey); }
Base
1
public Claims validateToken(String token) throws AuthenticationException { try { RsaKeyUtil rsaKeyUtil = new RsaKeyUtil(); PublicKey publicKey = rsaKeyUtil.fromPemEncoded(keycloakPublicKey); return Jwts.parser().setSigningKey(publicKey).parseJws(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 void addSynchronously(MediaPackage mediaPackage) throws SearchException, MediaPackageException, IllegalArgumentException, UnauthorizedException { if (mediaPackage == null) { throw new IllegalArgumentException("Unable to add a null mediapackage"); } logger.debug("Attempting to add mediapackage {} to search index", mediaPackage.getIdentifier()); AccessControlList acl = authorizationService.getActiveAcl(mediaPackage).getA(); Date now = new Date(); try { if (indexManager.add(mediaPackage, acl, now)) { logger.info("Added mediapackage `{}` to the search index, using ACL `{}`", mediaPackage, acl); } else { logger.warn("Failed to add mediapackage {} to the search index", mediaPackage.getIdentifier()); } } catch (SolrServerException e) { throw new SearchException(e); } try { persistence.storeMediaPackage(mediaPackage, acl, now); } catch (SearchServiceDatabaseException e) { logger.error("Could not store media package to search database {}: {}", mediaPackage.getIdentifier(), e); throw new SearchException(e); } }
Class
2
public AuthenticationInfo loadAuthenticationInfo(JSONWebToken token) { Key key = getJWTKey(); Jwt jwt; try { jwt = Jwts.parser().setSigningKey(key).parse(token.getPrincipal()); } catch (JwtException e) { throw new AuthenticationException(e); } String credentials = legacyHashing ? token.getCredentials() : encryptPassword(token.getCredentials()); Object principal = extractPrincipalFromWebToken(jwt); return new SimpleAuthenticationInfo(principal, credentials, getName()); }
Base
1
public static IRubyObject read_memory(ThreadContext context, IRubyObject klazz, IRubyObject content) { String data = content.convertToString().asJavaString(); return getSchema(context, (RubyClass) klazz, new StreamSource(new StringReader(data))); }
Base
1
public ChangeState(TimeTick when, String comment, Colors colors, String... states) { if (states.length == 0) { throw new IllegalArgumentException(); } this.when = when; this.states = states; this.comment = comment; this.colors = colors; }
Base
1
public void shouldNotAllowToListFileOutsideRoot() throws Exception { // given expectedException.expect(IllegalArgumentException.class); expectedException.expectMessage(containsString("this String argument must not contain the substring [..]")); // when logViewEndpoint.view("../somefile", null, null, null); }
Base
1
public void translate(ServerSetActionBarTextPacket 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.ACTIONBAR); titlePacket.setText(text); titlePacket.setXuid(""); titlePacket.setPlatformOnlineId(""); session.sendUpstreamPacket(titlePacket); }
Class
2
public static <T> T withPassword(AuthenticationRequestType type, Properties info, PasswordAction<char @Nullable [], T> action) throws PSQLException, IOException { char[] password = null; String authPluginClassName = PGProperty.AUTHENTICATION_PLUGIN_CLASS_NAME.get(info); if (authPluginClassName == null || authPluginClassName.equals("")) { // Default auth plugin simply pulls password directly from connection properties String passwordText = PGProperty.PASSWORD.get(info); if (passwordText != null) { password = passwordText.toCharArray(); } } else { AuthenticationPlugin authPlugin; try { authPlugin = (AuthenticationPlugin) ObjectFactory.instantiate(authPluginClassName, info, false, null); } catch (Exception ex) { LOGGER.log(Level.FINE, "Unable to load Authentication Plugin " + ex.toString()); throw new PSQLException(ex.getMessage(), PSQLState.UNEXPECTED_ERROR); } password = authPlugin.getPassword(type); } try { return action.apply(password); } finally { if (password != null) { java.util.Arrays.fill(password, (char) 0); } } }
Class
2
public void testCycle_ECDH_ES_Curve_P256_attackPoint1() throws Exception { ECKey ecJWK = generateECJWK(ECKey.Curve.P_256); BigInteger privateReceiverKey = ecJWK.toECPrivateKey().getS(); JWEHeader header = new JWEHeader.Builder(JWEAlgorithm.ECDH_ES, EncryptionMethod.A128GCM) .agreementPartyUInfo(Base64URL.encode("Alice")) .agreementPartyVInfo(Base64URL.encode("Bob")) .build(); // attacking point #1 with order 113 // BigInteger attackerOrderGroup1 = new BigInteger("113"); BigInteger receiverPrivateKeyModAttackerOrderGroup1 = privateReceiverKey .mod(attackerOrderGroup1); // System.out.println("The receiver private key is equal to " // + receiverPrivateKeyModAttackerOrderGroup1 + " mod " // + attackerOrderGroup1); // The malicious JWE contains a public key with order 113 String maliciousJWE1 = "eyJhbGciOiJFQ0RILUVTK0ExMjhLVyIsImVuYyI6IkExMjhDQkMtSFMyNTYiLCJlcGsiOnsia3R5IjoiRUMiLCJ4IjoiZ1RsaTY1ZVRRN3otQmgxNDdmZjhLM203azJVaURpRzJMcFlrV0FhRkpDYyIsInkiOiJjTEFuakthNGJ6akQ3REpWUHdhOUVQclJ6TUc3ck9OZ3NpVUQta2YzMEZzIiwiY3J2IjoiUC0yNTYifX0.qGAdxtEnrV_3zbIxU2ZKrMWcejNltjA_dtefBFnRh9A2z9cNIqYRWg.pEA5kX304PMCOmFSKX_cEg.a9fwUrx2JXi1OnWEMOmZhXd94-bEGCH9xxRwqcGuG2AMo-AwHoljdsH5C_kcTqlXS5p51OB1tvgQcMwB5rpTxg.72CHiYFecyDvuUa43KKT6w"; JWEObject jweObject1 = JWEObject.parse(maliciousJWE1); ECDHDecrypter decrypter = new ECDHDecrypter(ecJWK.toECPrivateKey()); // decrypter.getJCAContext().setKeyEncryptionProvider(BouncyCastleProviderSingleton.getInstance()); try { jweObject1.decrypt(decrypter); fail(); } catch (JOSEException e) { assertEquals("Invalid ephemeral public key: Point not on expected curve", e.getMessage()); } // this proof that receiverPrivateKey is equals 26 % 113 // assertEquals("Gambling is illegal at Bushwood sir, and I never slice.", // jweObject1.getPayload().toString()); // THIS CAN BE DOIN MANY TIME // .... // AND THAN CHINESE REMAINDER THEOREM FTW }
Base
1
public void setIncludeExternalDTDDeclarations(boolean include) { this.includeExternalDTDDeclarations = include; }
Base
1
public void translate(ServerSetSubtitleTextPacket 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.SUBTITLE); titlePacket.setText(text); titlePacket.setXuid(""); titlePacket.setPlatformOnlineId(""); session.sendUpstreamPacket(titlePacket); }
Class
2
private HColor getColorLegacy(ISkinParam skinParam, ColorParam colorParam, Stereotype stereo) { return new Rose().getHtmlColor(skinParam, stereo, colorParam); }
Base
1
private static void createBaloInHomeRepo(HttpURLConnection conn, String modulePathInBaloCache, String moduleNameWithOrg, boolean isNightlyBuild, String newUrl, String contentDisposition) { long responseContentLength = conn.getContentLengthLong(); if (responseContentLength <= 0) { createError("invalid response from the server, please try again"); } String resolvedURI = conn.getHeaderField(RESOLVED_REQUESTED_URI); if (resolvedURI == null || resolvedURI.equals("")) { resolvedURI = newUrl; } String[] uriParts = resolvedURI.split("/"); String moduleVersion = uriParts[uriParts.length - 3]; validateModuleVersion(moduleVersion); String baloFile = getBaloFileName(contentDisposition, uriParts[uriParts.length - 1]); Path baloCacheWithModulePath = Paths.get(modulePathInBaloCache, moduleVersion); //<user.home>.ballerina/balo_cache/<org-name>/<module-name>/<module-version> Path baloPath = Paths.get(baloCacheWithModulePath.toString(), baloFile); if (baloPath.toFile().exists()) { createError("module already exists in the home repository: " + baloPath.toString()); } createBaloFileDirectory(baloCacheWithModulePath); writeBaloFile(conn, baloPath, moduleNameWithOrg + ":" + moduleVersion, responseContentLength); handleNightlyBuild(isNightlyBuild, baloCacheWithModulePath); }
Base
1
public int addFileName(String file) { workUnitList.add(new WorkUnit(file)); return size(); }
Base
1
public void translate(ServerSetTitlesAnimationPacket packet, GeyserSession session) { SetTitlePacket titlePacket = new SetTitlePacket(); titlePacket.setType(SetTitlePacket.Type.TIMES); titlePacket.setText(""); titlePacket.setFadeInTime(packet.getFadeIn()); titlePacket.setFadeOutTime(packet.getFadeOut()); titlePacket.setStayTime(packet.getStay()); titlePacket.setXuid(""); titlePacket.setPlatformOnlineId(""); session.sendUpstreamPacket(titlePacket); }
Class
2
public AbstractEpsgFactory(final Hints userHints) throws FactoryException { super(MAXIMUM_PRIORITY - 20); // The following hints have no effect on this class behaviour, // but tell to the user what this factory do about axis order. hints.put(Hints.FORCE_LONGITUDE_FIRST_AXIS_ORDER, Boolean.FALSE); hints.put(Hints.FORCE_STANDARD_AXIS_DIRECTIONS, Boolean.FALSE); hints.put(Hints.FORCE_STANDARD_AXIS_UNITS, Boolean.FALSE); // // We need to obtain our DataSource if (userHints != null) { Object hint = userHints.get(Hints.EPSG_DATA_SOURCE); if (hint instanceof String) { String name = (String) hint; try { dataSource = (DataSource) GeoTools.getInitialContext().lookup(name); } catch (NamingException e) { throw new FactoryException("A EPSG_DATA_SOURCE hint is required:" + e); } hints.put(Hints.EPSG_DATA_SOURCE, dataSource); } else if (hint instanceof DataSource) { dataSource = (DataSource) hint; hints.put(Hints.EPSG_DATA_SOURCE, dataSource); } else { throw new FactoryException("A EPSG_DATA_SOURCE hint is required."); } } else { throw new FactoryException("A EPSG_DATA_SOURCE hint is required."); } }
Class
2
public void removingANameForASecondTimeShouldReturnFalse() { final HttpHeadersBase headers = newEmptyHeaders(); headers.add("name1", "value1"); headers.add("name2", "value2"); assertThat(headers.remove("name2")).isTrue(); assertThat(headers.remove("name2")).isFalse(); }
Class
2
public void newDocumentWebHomeFromURLTemplateProviderSpecifiedTerminalOverriddenFromUIToNonTerminal() 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); when(mockRequest.getParameter("tocreate")).thenReturn("nonterminal"); // 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.WebHome as non-terminal even if the template provider says otherwise. // Also 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 <T> List<T> search(String filter, Object[] filterArgs, Mapper<T> mapper, int maxResult) { List<T> results = new ArrayList<>(); DirContext dirContext = getDirContext(ldapConfiguration, ldapConfiguration.getManagerDn(), ldapConfiguration.getPassword()); try { List<SearchResult> searchResults = search(dirContext, filter, filterArgs, maxResult, false); for (SearchResult result : searchResults) { results.add(mapper.mapObject(new ResultWrapper(result.getAttributes()))); } } catch (NamingException e) { throw new LdapException(e); } finally { closeContextSilently(dirContext); } return results; }
Class
2
public void newDocumentWebHomeFromURLTemplateProviderSpecifiedButNotAllowed() 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"), Arrays.asList("AnythingButX")); // Run the action String result = action.render(context); // The tests are below this line! // Verify that the create template is rendered, so the UI is displayed for the user to see the error. assertEquals("create", result); // Check that the exception is properly set in the context for the UI to display. XWikiException exception = (XWikiException) this.oldcore.getScriptContext().getAttribute("createException"); assertNotNull(exception); assertEquals(XWikiException.ERROR_XWIKI_APP_TEMPLATE_NOT_AVAILABLE, exception.getCode()); // We should not get this far so no redirect should be done, just the template will be rendered. verify(mockURLFactory, never()).createURL(any(), any(), any(), any(), any(), any(), any(XWikiContext.class)); }
Class
2
public void setDefaultHandler(ElementHandler handler) { getDispatchHandler().setDefaultHandler(handler); }
Base
1
public static void serializeToStream(final OutputStream os, final Object payload) throws IOException { ObjectOutputStream oos = null; try { oos = new ObjectOutputStream(os); oos.writeObject(payload); } finally { if (oos != null) { try { oos.close(); } catch (IOException ignore) { // empty catch block } } } }
Base
1
public Group createDefaultReadGroup(Context context, Collection collection, String typeOfGroupString, int defaultRead) throws SQLException, AuthorizeException { Group role = groupService.create(context); groupService.setName(role, "COLLECTION_" + collection.getID().toString() + "_" + typeOfGroupString + "_DEFAULT_READ"); // Remove existing privileges from the anonymous group. authorizeService.removePoliciesActionFilter(context, collection, defaultRead); // Grant our new role the default privileges. authorizeService.addPolicy(context, collection, defaultRead, role); groupService.update(context, role); return role; }
Class
2
public void translate(ContainerClosePacket packet, GeyserSession session) { byte windowId = packet.getId(); //Client wants close confirmation session.sendUpstreamPacket(packet); session.setClosingInventory(false); if (windowId == -1 && session.getOpenInventory() instanceof MerchantContainer) { // 1.16.200 - window ID is always -1 sent from Bedrock windowId = (byte) session.getOpenInventory().getId(); } Inventory openInventory = session.getOpenInventory(); if (openInventory != null) { if (windowId == openInventory.getId()) { ClientCloseWindowPacket closeWindowPacket = new ClientCloseWindowPacket(windowId); session.sendDownstreamPacket(closeWindowPacket); InventoryUtils.closeInventory(session, windowId, false); } else if (openInventory.isPending()) { InventoryUtils.displayInventory(session, openInventory); openInventory.setPending(false); } } }
Class
2
default Optional<Integer> findInt(CharSequence name) { return get(name, Integer.class); }
Class
2
public VideoMetadata readVideoMetadataFile(OLATResource videoResource){ VFSContainer baseContainer= FileResourceManager.getInstance().getFileResourceRootImpl(videoResource); VFSLeaf metaDataFile = (VFSLeaf) baseContainer.resolve(FILENAME_VIDEO_METADATA_XML); try { return (VideoMetadata) XStreamHelper.readObject(XStreamHelper.createXStreamInstance(), metaDataFile); } catch (Exception e) { log.error("Error while parsing XStream file for videoResource::{}", videoResource, e); // return an empty, so at least it displays something and not an error VideoMetadata meta = new VideoMetadataImpl(); meta.setWidth(800); meta.setHeight(600); return meta; } }
Base
1
void routingResult() throws URISyntaxException { final RoutingResultBuilder builder = RoutingResult.builder(); final RoutingResult routingResult = builder.path("/foo") .query("bar=baz") .rawParam("qux", "quux") .negotiatedResponseMediaType(MediaType.JSON_UTF_8) .build(); assertThat(routingResult.isPresent()).isTrue(); assertThat(routingResult.path()).isEqualTo("/foo"); assertThat(routingResult.query()).isEqualTo("bar=baz"); assertThat(routingResult.pathParams()).containsOnly(new SimpleEntry<>("qux", "quux")); assertThat(routingResult.negotiatedResponseMediaType()).isSameAs(MediaType.JSON_UTF_8); }
Base
1
public void translate(ServerAdvancementTabPacket packet, GeyserSession session) { AdvancementsCache advancementsCache = session.getAdvancementsCache(); advancementsCache.setCurrentAdvancementCategoryId(packet.getTabId()); advancementsCache.buildAndShowListForm(); }
Class
2
public SAXReader(DocumentFactory factory, boolean validating) { this.factory = factory; this.validating = validating; }
Base
1
public SAXEntityResolver(String uriPrefix) { this.uriPrefix = uriPrefix; }
Base
1
public void add(File fileToAdd) { String[] args = new String[]{"add", fileToAdd.getName()}; CommandLine gitAdd = gitWd().withArgs(args); runOrBomb(gitAdd); }
Class
2
public Cipher encrypt() { try { Cipher cipher = Secret.getCipher(ALGORITHM); cipher.init(Cipher.ENCRYPT_MODE, getKey()); return cipher; } catch (GeneralSecurityException e) { throw new AssertionError(e); } }
Class
2
public String[] getCommandline() { final String[] args = getArguments(); String executable = getExecutable(); if ( executable == null ) { return args; } final String[] result = new String[args.length + 1]; result[0] = executable; System.arraycopy( args, 0, result, 1, args.length ); return result; }
Base
1
public static byte[] computeLength(final byte[] aad) { final int bitLength = ByteUtils.bitLength(aad); return ByteBuffer.allocate(8).putLong(bitLength).array(); }
Class
2
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
public void correctExample() throws Exception { assertThat(ConstraintViolations.format(validator.validate(new CorrectExample()))) .isEmpty(); assertThat(TestLoggerFactory.getAllLoggingEvents()) .isEmpty(); }
Class
2
public static String printFormattedMetadata(final IBaseDataObject payload) { final StringBuilder out = new StringBuilder(); out.append(LS); for (final Map.Entry<String, Collection<Object>> entry : payload.getParameters().entrySet()) { out.append(entry.getKey() + SEP + entry.getValue() + LS); } return out.toString(); }
Base
1
public void testHeaderNameNormalization() { final HttpHeadersBase headers = newHttp2Headers(); headers.add("Foo", "bar"); assertThat(headers.getAll("foo")).containsExactly("bar"); assertThat(headers.getAll("fOO")).containsExactly("bar"); assertThat(headers.names()).contains(HttpHeaderNames.of("foo")) .doesNotContain(AsciiString.of("Foo")); }
Class
2
public TSet readSetBegin() throws TException { return new TSet(readByte(), readI32()); }
Base
1
private void verifyHostname(X509Certificate cert) throws CertificateParsingException { try { Collection sans = cert.getSubjectAlternativeNames(); if (sans == null) { String dn = cert.getSubjectX500Principal().getName(); LdapName ln = new LdapName(dn); for (Rdn rdn : ln.getRdns()) { if (rdn.getType().equalsIgnoreCase("CN")) { String peer = client.getServerName().toLowerCase(); if (peer.equals(((String)rdn.getValue()).toLowerCase())) return; } } } else { Iterator i = sans.iterator(); while (i.hasNext()) { List nxt = (List)i.next(); if (((Integer)nxt.get(0)).intValue() == 2) { String peer = client.getServerName().toLowerCase(); if (peer.equals(((String)nxt.get(1)).toLowerCase())) return; } else if (((Integer)nxt.get(0)).intValue() == 7) { String peer = ((CConn)client).getSocket().getPeerAddress(); if (peer.equals(((String)nxt.get(1)).toLowerCase())) return; } } } Object[] answer = {"YES", "NO"}; int ret = JOptionPane.showOptionDialog(null, "Hostname verification failed. Do you want to continue?", "Hostname Verification Failure", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE, null, answer, answer[0]); if (ret != JOptionPane.YES_OPTION) throw new WarningException("Hostname verification failed."); } catch (CertificateParsingException e) { throw new SystemException(e.getMessage()); } catch (InvalidNameException e) { throw new SystemException(e.getMessage()); } }
Base
1
protected SymbolContext getContextLegacy() { if (UseStyle.useBetaStyle() == false) return new SymbolContext(HColorUtils.COL_D7E0F2, HColorUtils.COL_038048).withStroke(new UStroke(2)); final HColor lineColor = style.value(PName.LineColor).asColor(skinParam.getThemeStyle(), skinParam.getIHtmlColorSet()); final HColor backgroundColor = style.value(PName.BackGroundColor).asColor(skinParam.getThemeStyle(), skinParam.getIHtmlColorSet()); return new SymbolContext(backgroundColor, lineColor).withStroke(getStroke()); }
Base
1