code
stringlengths
12
2.05k
label_name
stringclasses
5 values
label
int64
0
4
public void testGetShellCommandLineNonWindows() throws Exception { Commandline cmd = new Commandline( new BourneShell() ); cmd.setExecutable( "/usr/bin" ); cmd.addArguments( new String[] { "a", "b" } ); String[] shellCommandline = cmd.getShellCommandline(); assertEquals( "Command line size", 3, shellCommandline.length ); assertEquals( "/bin/sh", shellCommandline[0] ); assertEquals( "-c", shellCommandline[1] ); if ( Os.isFamily( Os.FAMILY_WINDOWS ) ) { assertEquals( "\\usr\\bin a b", shellCommandline[2] ); } else { assertEquals( "/usr/bin a b", shellCommandline[2] ); } }
Base
1
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 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
protected List<EfficiencyStatement> findEfficiencyStatements(IdentityRef identity) { List<EfficiencyStatement> efficiencyStatements = new ArrayList<>(); StringBuilder sb = new StringBuilder(); sb.append("select statement from effstatement as statement") .append(" where statement.identity.key=:identityKey"); List<UserEfficiencyStatementImpl> statements = dbInstance.getCurrentEntityManager() .createQuery(sb.toString(), UserEfficiencyStatementImpl.class) .setParameter("identityKey", identity.getKey()) .getResultList(); for(UserEfficiencyStatementImpl statement:statements) { if(StringHelper.containsNonWhitespace(statement.getStatementXml())) { EfficiencyStatement s = (EfficiencyStatement)xstream.fromXML(statement.getStatementXml()); efficiencyStatements.add(s); } } return efficiencyStatements; }
Base
1
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); poly.update(ciphertext, ciphertextOffset, dataLen); finish(ad, dataLen); int temp = 0; for (int index = 0; index < 16; ++index) temp |= (polyKey[index] ^ ciphertext[ciphertextOffset + dataLen + index]); if ((temp & 0xFF) != 0) Noise.throwBadTagException(); encrypt(ciphertext, ciphertextOffset, plaintext, plaintextOffset, dataLen); return dataLen; }
Base
1
public void shouldNotGetModificationsFromOtherBranches() throws Exception { makeACommitToSecondBranch(); hg(workingDirectory, "pull").runOrBomb(null); List<Modification> actual = hgCommand.modificationsSince(new StringRevision(REVISION_0)); assertThat(actual.size(), is(2)); assertThat(actual.get(0).getRevision(), is(REVISION_2)); assertThat(actual.get(1).getRevision(), is(REVISION_1)); }
Class
2
public static synchronized InitialContext getInitialContext(final Hints hints) throws NamingException { return getInitialContext(); }
Class
2
public byte[] allocateJobCaches(byte[] cacheAllocationRequestBytes) { CacheAllocationRequest allocationRequest = (CacheAllocationRequest) SerializationUtils .deserialize(cacheAllocationRequestBytes); return SerializationUtils.serialize((Serializable) jobManager.allocateJobCaches( getJobToken(), allocationRequest.getCurrentTime(), allocationRequest.getInstances())); }
Base
1
private String getMimeType(HttpServletRequest pReq) { String requestMimeType = pReq.getParameter(ConfigKey.MIME_TYPE.getKeyValue()); if (requestMimeType != null) { return requestMimeType; } return configMimeType; }
Base
1
public byte[] decrypt(final JWEHeader header, final Base64URL encryptedKey, final Base64URL iv, final Base64URL cipherText, final Base64URL authTag) throws JOSEException { final JWEAlgorithm alg = header.getAlgorithm(); final ECDH.AlgorithmMode algMode = ECDH.resolveAlgorithmMode(alg); critPolicy.ensureHeaderPasses(header); // Get ephemeral EC key ECKey ephemeralKey = header.getEphemeralPublicKey(); if (ephemeralKey == null) { throw new JOSEException("Missing ephemeral public EC key \"epk\" JWE header parameter"); } ECPublicKey ephemeralPublicKey = ephemeralKey.toECPublicKey(); // Curve check ECDH.ensurePointOnCurve(ephemeralPublicKey, getPrivateKey()); // Derive 'Z' SecretKey Z = ECDH.deriveSharedSecret( ephemeralPublicKey, privateKey, getJCAContext().getKeyEncryptionProvider()); // Derive shared key via concat KDF getConcatKDF().getJCAContext().setProvider(getJCAContext().getMACProvider()); // update before concat SecretKey sharedKey = ECDH.deriveSharedKey(header, Z, getConcatKDF()); final SecretKey cek; if (algMode.equals(ECDH.AlgorithmMode.DIRECT)) { cek = sharedKey; } else if (algMode.equals(ECDH.AlgorithmMode.KW)) { if (encryptedKey == null) { throw new JOSEException("Missing JWE encrypted key"); } cek = AESKW.unwrapCEK(sharedKey, encryptedKey.decode(), getJCAContext().getKeyEncryptionProvider()); } else { throw new JOSEException("Unexpected JWE ECDH algorithm mode: " + algMode); } return ContentCryptoProvider.decrypt(header, encryptedKey, iv, cipherText, authTag, cek, getJCAContext()); }
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
public <T> List<T> search(final String filter, final Object[] filterArgs, final Mapper<T> mapper, final int maxResultCount) { final List<T> searchResults = new ArrayList<>(); for (String searchBase : ldapConfiguration.getSearchBases()) { int resultsToFetch = resultsToFetch(maxResultCount, searchResults.size()); if (resultsToFetch == -1) { break; } try { final SearchRequest searchRequest = new SearchRequestImpl() .setScope(SearchScope.SUBTREE) .addAttributes("*") .setSizeLimit(resultsToFetch) .setFilter(format(filter, filterArgs)) .setTimeLimit(ldapConfiguration.getSearchTimeout()) .setBase(new Dn(searchBase)); searchResults.addAll(ldapConnectionTemplate.search(searchRequest, mapper)); } catch (LdapException e) { LOG.error(e.getMessage(), e); } } return searchResults; }
Class
2
public void addUser(JpaUser user) throws UnauthorizedException { if (!UserDirectoryUtils.isCurrentUserAuthorizedHandleRoles(securityService, user.getRoles())) throw new UnauthorizedException("The user is not allowed to set the admin role on other users"); // Create a JPA user with an encoded password. String encodedPassword = PasswordEncoder.encode(user.getPassword(), user.getUsername()); // Only save internal roles Set<JpaRole> roles = UserDirectoryPersistenceUtil.saveRoles(filterRoles(user.getRoles()), emf); JpaOrganization organization = UserDirectoryPersistenceUtil.saveOrganization( (JpaOrganization) user.getOrganization(), emf); JpaUser newUser = new JpaUser(user.getUsername(), encodedPassword, organization, user.getName(), user.getEmail(), user.getProvider(), user.isManageable(), roles); // Then save the user EntityManager em = null; EntityTransaction tx = null; try { em = emf.createEntityManager(); tx = em.getTransaction(); tx.begin(); em.persist(newUser); tx.commit(); cache.put(user.getUsername() + DELIMITER + user.getOrganization().getId(), newUser); } finally { if (tx.isActive()) { tx.rollback(); } if (em != null) em.close(); } updateGroupMembership(user); }
Class
2
public void testEntryEquals() { final HttpHeadersBase nameValue = newEmptyHeaders(); nameValue.add("name", "value"); final HttpHeadersBase nameValueCopy = newEmptyHeaders(); nameValueCopy.add("name", "value"); final Map.Entry<AsciiString, String> same1 = nameValue.iterator().next(); final Map.Entry<AsciiString, String> same2 = nameValueCopy.iterator().next(); assertThat(same2).isEqualTo(same1); assertThat(same2.hashCode()).isEqualTo(same1.hashCode()); final HttpHeadersBase name1Value = newEmptyHeaders(); name1Value.add("name1", "value"); final HttpHeadersBase name2Value = newEmptyHeaders(); name2Value.add("name2", "value"); final Map.Entry<AsciiString, String> nameDifferent1 = name1Value.iterator().next(); final Map.Entry<AsciiString, String> nameDifferent2 = name2Value.iterator().next(); assertThat(nameDifferent1).isNotEqualTo(nameDifferent2); assertThat(nameDifferent1.hashCode()).isNotEqualTo(nameDifferent2.hashCode()); final HttpHeadersBase nameValue1 = newEmptyHeaders(); nameValue1.add("name", "value1"); final HttpHeadersBase nameValue2 = newEmptyHeaders(); nameValue2.add("name", "value2"); final Map.Entry<AsciiString, String> valueDifferent1 = nameValue1.iterator().next(); final Map.Entry<AsciiString, String> valueDifferent2 = nameValue2.iterator().next(); assertThat(valueDifferent1).isNotEqualTo(valueDifferent2); assertThat(valueDifferent1.hashCode()).isNotEqualTo(valueDifferent2.hashCode()); }
Class
2
public <T> T toBean(Class<T> beanClass) { setTag(new Tag(beanClass)); if (getVersion() != null) { try { MigrationHelper.migrate(getVersion(), beanClass.newInstance(), this); removeVersion(); } catch (InstantiationException | IllegalAccessException e) { throw new RuntimeException(e); } } return (T) new OneYaml().construct(this); }
Base
1
void setup() { this.saveAction = new SaveAction(); context = oldcore.getXWikiContext(); xWiki = mock(XWiki.class); context.setWiki(this.xWiki); mockRequest = mock(XWikiRequest.class); context.setRequest(mockRequest); mockResponse = mock(XWikiResponse.class); context.setResponse(mockResponse); mockDocument = mock(XWikiDocument.class); context.setDoc(mockDocument); mockClonedDocument = mock(XWikiDocument.class); when(mockDocument.clone()).thenReturn(mockClonedDocument); mockForm = mock(EditForm.class); context.setForm(mockForm); when(this.entityNameValidationConfiguration.useValidation()).thenReturn(false); context.setUserReference(USER_REFERENCE); }
Class
2
public Object getResourceDataForKey(String key) { Object data = null; String dataString = null; Matcher matcher = DATA_SEPARATOR_PATTERN.matcher(key); if (matcher.find()) { if (log.isDebugEnabled()) { log.debug(Messages.getMessage( Messages.RESTORE_DATA_FROM_RESOURCE_URI_INFO, key, dataString)); } int dataStart = matcher.end(); dataString = key.substring(dataStart); byte[] objectArray = null; byte[] dataArray; try { dataArray = dataString.getBytes("ISO-8859-1"); objectArray = decrypt(dataArray); } catch (UnsupportedEncodingException e1) { // default encoding always presented. } if ("B".equals(matcher.group(1))) { data = objectArray; } else { try { ObjectInputStream in = new ObjectInputStream( new ByteArrayInputStream(objectArray)); data = in.readObject(); } catch (StreamCorruptedException e) { log.error(Messages .getMessage(Messages.STREAM_CORRUPTED_ERROR), e); } catch (IOException e) { log.error(Messages .getMessage(Messages.DESERIALIZE_DATA_INPUT_ERROR), e); } catch (ClassNotFoundException e) { log .error( Messages .getMessage(Messages.DATA_CLASS_NOT_FOUND_ERROR), e); } } } return data; }
Base
1
public void shouldThrowExceptionForBadConnection() throws Exception { String url = "http://not-exists"; HgCommand hgCommand = new HgCommand(null, null, null, null, null); assertThatThrownBy(() -> hgCommand.checkConnection(new UrlArgument(url))) .isExactlyInstanceOf(CommandLineException.class); }
Class
2
public void validateFail2(ViolationCollector col) { col.addViolation(FAILED + "2"); }
Class
2
public SAXReader(boolean validating) { this.validating = validating; }
Base
1
private static void handleErrorResponse(HttpURLConnection conn, String url, String moduleFullName) { try (BufferedReader reader = new BufferedReader( new InputStreamReader(conn.getErrorStream(), Charset.defaultCharset()))) { StringBuilder result = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { result.append(line); } MapValue payload = (MapValue) JSONParser.parse(result.toString()); createError("error: " + payload.getStringValue("message")); } catch (IOException e) { createError("failed to pull the module '" + moduleFullName + "' from the remote repository '" + url + "'"); } }
Base
1
public String getHeader(String name) { //logger.info("Ineader .. parameter ......."); String value = super.getHeader(name); if (value == null) return null; //logger.info("Ineader RequestWrapper ........... value ...."); return cleanXSS(value); }
Base
1
public void emptyHeaderNameNotAllowed() { newEmptyHeaders().add("", "foo"); }
Class
2
public RedirectView callback(@RequestParam(defaultValue = "/") String redirect, @PathVariable String serverId, @RequestParam String code, @RequestParam String state, HttpServletRequest request, HttpSession session) throws UnsupportedEncodingException { try { String cachedState = (String) session.getAttribute(STATE_SESSION_KEY); // if (!state.equals(cachedState)) throw new BusinessException("state error"); oAuth2RequestService.doEvent(serverId, new OAuth2CodeAuthBeforeEvent(code, state, request::getParameter)); return new RedirectView(URLDecoder.decode(redirect, "UTF-8")); } finally { session.removeAttribute(STATE_SESSION_KEY); } }
Compound
4
public void newDocumentWebHomeFromURLTemplateProviderSpecifiedButOldPageTypeButOverriddenFromUIToNonTerminal() 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, null, "page"); // Run the action String result = action.render(context); // The tests are below this line! // Verify null is returned (this means the response has been returned) assertNull(result); // Note: We are creating the document X.Y.WebHome as non-terminal, since even if the template provider did not // specify a "terminal" property and it used the old "page" type, the UI explicitly asked for a non-terminal // document. 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 void authorizeRequest(Operation op) { op.complete(); }
Class
2
public void testFormat() throws Exception { assertEquals("<a> <b>c</b></a>", format("<a><b>c</b></a>", 1).replaceAll("[\r\n]", "")); assertEquals("<a> <b>c</b></a>", format("<a><b>c</b></a>", 3).replaceAll("[\r\n]", "")); assertEquals("<a><b>c</b></a>", format("<a><b>c</b></a>", -21)); assertThrows(IllegalArgumentException.class, () -> format("<a><b>c</b></a>", 0)); // check if the XXE protection is enabled String xxeAttack = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" + " <!DOCTYPE test [\n" + " <!ENTITY xxe SYSTEM \"file:///etc/passwd\">\n" + " ]>" + "<a><b>&xxe;</b></a>"; assertEquals(xxeAttack, format(xxeAttack, 1)); // wrongly formatted XML assertEquals("<a><b>c</b><a>", format("<a><b>c</b><a>", 1)); }
Base
1
public void translate(ServerPingPacket packet, GeyserSession session) { session.sendDownstreamPacket(new ClientPongPacket(packet.getId())); }
Class
2
public void translate(ServerMultiBlockChangePacket packet, GeyserSession session) { for (BlockChangeRecord record : packet.getRecords()) { ChunkUtils.updateBlock(session, record.getBlock(), record.getPosition()); } }
Class
2
public void existingDocumentFromUITemplateSpecified() 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&template=XWiki.MyTemplate String templateDocumentFullName = "XWiki.MyTemplate"; DocumentReference templateDocumentReference = new DocumentReference("MyTemplate", Arrays.asList("XWiki"), "xwiki"); when(mockRequest.getParameter("spaceReference")).thenReturn("X"); when(mockRequest.getParameter("name")).thenReturn("Y"); when(mockRequest.getParameter("template")).thenReturn("XWiki.MyTemplate"); // Mock the passed template document as existing. mockTemplateDocumentExisting(templateDocumentFullName, templateDocumentReference); // 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 and using the template specified in the request. verify(mockURLFactory).createURL("X.Y", "WebHome", "edit", "template=XWiki.MyTemplate&parent=Main.WebHome&title=Y", null, "xwiki", context); }
Class
2
default List<MediaType> accept() { return getAll(HttpHeaders.ACCEPT) .stream() .flatMap(x -> Arrays.stream(x.split(","))) .flatMap(s -> ConversionService.SHARED.convert(s, MediaType.class).map(Stream::of).orElse(Stream.empty())) .distinct() .collect(Collectors.toList()); }
Class
2
public void translate(ServerWindowPropertyPacket packet, GeyserSession session) { Inventory inventory = InventoryUtils.getInventory(session, packet.getWindowId()); if (inventory == null) return; InventoryTranslator translator = session.getInventoryTranslator(); if (translator != null) { translator.updateProperty(session, inventory, packet.getRawProperty(), packet.getValue()); } }
Class
2
public void validateFail3(ViolationCollector col) { col.addViolation(FAILED + "3"); }
Class
2
public void onTaskSelectionEvent(@Observes TaskSelectionEvent event){ selectedTaskId = event.getTaskId(); selectedTaskName = event.getTaskName(); view.getTaskIdAndName().setText(String.valueOf(selectedTaskId) + " - "+selectedTaskName); view.getContent().clear(); String placeToGo; if(event.getPlace() != null && !event.getPlace().equals("")){ placeToGo = event.getPlace(); }else{ placeToGo = "Task Details"; } DefaultPlaceRequest defaultPlaceRequest = new DefaultPlaceRequest(placeToGo); //Set Parameters here: defaultPlaceRequest.addParameter("taskId", String.valueOf(selectedTaskId)); defaultPlaceRequest.addParameter("taskName", selectedTaskName); Set<Activity> activities = activityManager.getActivities(defaultPlaceRequest); AbstractWorkbenchScreenActivity activity = ((AbstractWorkbenchScreenActivity) activities.iterator().next()); activitiesMap.put(placeToGo, activity); IsWidget widget = activity.getWidget(); activity.launch(place, null); activity.onStartup(defaultPlaceRequest); view.getContent().add(widget); activity.onOpen(); }
Base
1
private SearchResult lookupUser(String accountName) throws NamingException { InitialDirContext context = initContext(); String searchString = searchFilter.replace(":login", accountName); SearchControls searchControls = new SearchControls(); String[] attributeFilter = {idAttribute, nameAttribute, mailAttribute}; searchControls.setReturningAttributes(attributeFilter); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); NamingEnumeration<SearchResult> results = context.search(searchBase, searchString, searchControls); SearchResult searchResult = null; if (results.hasMoreElements()) { searchResult = results.nextElement(); if (results.hasMoreElements()) { LOGGER.warn("Matched multiple users for the accountName: " + accountName); return null; } } return searchResult; }
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
private static final RestrictorCheck CORS_CHECK = new RestrictorCheck() { /** {@inheritDoc} */ public boolean check(Restrictor restrictor, Object... args) { return restrictor.isCorsAccessAllowed((String) args[0]); } };
Compound
4
public static XStream createXStreamInstance() { return new EnhancedXStream(false); }
Base
1
public String accessToken(String username) { Algorithm algorithm = Algorithm.HMAC256(SECRET); return JWT.create() .withExpiresAt(new Date(new Date().getTime() + ACCESS_EXPIRE_TIME)) .withIssuer(ISSUER) .withClaim("username", username) .sign(algorithm); }
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 boolean isCorsAccessAllowed(String pOrigin) { return checkRestrictorService(CORS_CHECK,pOrigin); }
Compound
4
private void securityCheck(String filename) { Assert.doesNotContain(filename, ".."); }
Base
1
function findLateSubscriptionSortedByPriority() { if (late_subscriptions.length === 0) { return null; } late_subscriptions.sort(compare_subscriptions); // istanbul ignore next if (doDebug) { debugLog( late_subscriptions .map( (s: Subscription) => "[ id = " + s.id + " prio=" + s.priority + " t=" + s.timeToExpiration + " ka=" + s.timeToKeepAlive + " m?=" + s.hasUncollectedMonitoredItemNotifications + " " + SubscriptionState[s.state] + " " + s.messageSent + "]" ) .join(" \n") ); } return late_subscriptions[late_subscriptions.length - 1]; }
Base
1
public void create() throws Exception { final JettyServerFactory jettyServerFactory = mock(JettyServerFactory.class); final StaticFilesConfiguration staticFilesConfiguration = mock(StaticFilesConfiguration.class); final Routes routes = mock(Routes.class); when(jettyServerFactory.create(100,10,10000)).thenReturn(new Server()); final EmbeddedJettyFactory embeddedJettyFactory = new EmbeddedJettyFactory(jettyServerFactory); embeddedServer = embeddedJettyFactory.create(routes, staticFilesConfiguration, false); embeddedServer.ignite("localhost", 8080, null, 100,10,10000); verify(jettyServerFactory, times(1)).create(100,10,10000); verifyNoMoreInteractions(jettyServerFactory); }
Base
1
public String getEncryptedValue() { try { Cipher cipher = KEY.encrypt(); // add the magic suffix which works like a check sum. return new String(Base64.encode(cipher.doFinal((value+MAGIC).getBytes("UTF-8")))); } catch (GeneralSecurityException e) { throw new Error(e); // impossible } catch (UnsupportedEncodingException e) { throw new Error(e); // impossible } }
Class
2
public static Object readObject(XStream xStream, String xml) { try(InputStream is = new ByteArrayInputStream(xml.getBytes(ENCODING))) { return readObject(xStream, is); } catch (Exception e) { throw new OLATRuntimeException(XStreamHelper.class, "could not read Object from string: " + xml, e); } }
Base
1
public void headersWithSameNamesButDifferentValuesShouldNotBeEquivalent() { final HttpHeadersBase headers1 = newEmptyHeaders(); headers1.add("name1", "value1"); final HttpHeadersBase headers2 = newEmptyHeaders(); headers1.add("name1", "value2"); assertThat(headers1).isNotEqualTo(headers2); }
Class
2
public void shouldThrowExceptionIfUpdateFails() throws Exception { InMemoryStreamConsumer output = ProcessOutputStreamConsumer.inMemoryConsumer(); // delete repository in order to fail the hg pull command assertThat(FileUtils.deleteQuietly(serverRepo), is(true)); // now hg pull will fail and throw an exception assertThatThrownBy(() -> hgCommand.updateTo(new StringRevision("tip"), output)) .isExactlyInstanceOf(RuntimeException.class); }
Class
2
public InvalidExtensionException(String[] allowedExtension, String extension, String filename) { super("filename : [" + filename + "], extension : [" + extension + "], allowed extension : [" + Arrays.toString(allowedExtension) + "]"); this.allowedExtension = allowedExtension; this.extension = extension; this.filename = filename; }
Base
1
public void translate(ServerUpdateViewDistancePacket packet, GeyserSession session) { session.setRenderDistance(packet.getViewDistance()); }
Class
2
public PlayerAnalog(String code, ISkinParam skinParam, TimingRuler ruler, boolean compact) { super(code, skinParam, ruler, compact); this.suggestedHeight = 100; }
Base
1
public List<Modification> modificationsSince(Revision revision) { InMemoryStreamConsumer consumer = inMemoryConsumer(); bombUnless(pull(consumer), "Failed to run hg pull command: " + consumer.getAllOutput()); CommandLine hg = hg("log", "-r", "tip:" + revision.getRevision(), "-b", branch, "--style", templatePath()); return new HgModificationSplitter(execute(hg)).filterOutRevision(revision); }
Class
2
void consecutiveSlashes() { final PathAndQuery res = PathAndQuery.parse( "/path//with///consecutive////slashes?/query//with///consecutive////slashes"); assertThat(res).isNotNull(); assertThat(res.path()).isEqualTo("/path/with/consecutive/slashes"); assertThat(res.query()).isEqualTo("/query//with///consecutive////slashes"); // Encoded slashes final PathAndQuery res2 = PathAndQuery.parse( "/path%2F/with/%2F/consecutive//%2F%2Fslashes?/query%2F/with/%2F/consecutive//%2F%2Fslashes"); assertThat(res2).isNotNull(); assertThat(res2.path()).isEqualTo("/path%2F/with/%2F/consecutive/%2F%2Fslashes"); assertThat(res2.query()).isEqualTo("/query%2F/with/%2F/consecutive//%2F%2Fslashes"); }
Base
1
public <T extends Result> T setResult(Class<T> resultClass) throws SQLException { try { if (isDebugEnabled()) { debugCode( "getSource(" + (resultClass != null ? resultClass.getSimpleName() + ".class" : "null") + ')'); } checkEditable(); if (resultClass == null || resultClass == DOMResult.class) { domResult = new DOMResult(); state = State.SET_CALLED; return (T) domResult; } else if (resultClass == SAXResult.class) { SAXTransformerFactory transformerFactory = (SAXTransformerFactory) TransformerFactory.newInstance(); TransformerHandler transformerHandler = transformerFactory.newTransformerHandler(); Writer writer = setCharacterStreamImpl(); transformerHandler.setResult(new StreamResult(writer)); SAXResult saxResult = new SAXResult(transformerHandler); closable = writer; state = State.SET_CALLED; return (T) saxResult; } else if (resultClass == StAXResult.class) { XMLOutputFactory xof = XMLOutputFactory.newInstance(); Writer writer = setCharacterStreamImpl(); StAXResult staxResult = new StAXResult(xof.createXMLStreamWriter(writer)); closable = writer; state = State.SET_CALLED; return (T) staxResult; } else if (StreamResult.class.equals(resultClass)) { Writer writer = setCharacterStreamImpl(); StreamResult streamResult = new StreamResult(writer); closable = writer; state = State.SET_CALLED; return (T) streamResult; } throw unsupported(resultClass.getName()); } catch (Exception e) { throw logAndConvert(e); } }
Base
1
public void translate(ServerDisconnectPacket packet, GeyserSession session) { session.disconnect(MessageTranslator.convertMessage(packet.getReason(), session.getLocale())); }
Class
2
public PersistentTask updateTask(Task task, Serializable runnableTask, Identity modifier, Date scheduledDate) { PersistentTask ptask = dbInstance.getCurrentEntityManager() .find(PersistentTask.class, task.getKey(), LockModeType.PESSIMISTIC_WRITE); if(ptask != null) { ptask.setLastModified(new Date()); ptask.setScheduledDate(scheduledDate); ptask.setStatus(TaskStatus.newTask); ptask.setStatusBeforeEditStr(null); ptask.setTask(xstream.toXML(runnableTask)); ptask = dbInstance.getCurrentEntityManager().merge(ptask); if(modifier != null) { //add to the list of modifier PersistentTaskModifier mod = new PersistentTaskModifier(); mod.setCreationDate(new Date()); mod.setModifier(modifier); mod.setTask(ptask); dbInstance.getCurrentEntityManager().persist(mod); } dbInstance.commit(); } return ptask; }
Base
1
private String escapeEl(@Nullable String s) { if (s == null || s.isEmpty()) { return s; } final Matcher m = ESCAPE_PATTERN.matcher(s); final StringBuffer sb = new StringBuffer(s.length() + 16); while (m.find()) { m.appendReplacement(sb, "\\\\\\${"); } m.appendTail(sb); return sb.toString(); }
Class
2
public Argument<Publisher> argumentType() { return Argument.of(Publisher.class); }
Class
2
private boolean extract(ArrayList<String> errors, URL source, File target) { FileOutputStream os = null; InputStream is = null; boolean extracting = false; try { if (!target.exists() || isStale(source, target) ) { is = source.openStream(); if (is != null) { byte[] buffer = new byte[4096]; os = new FileOutputStream(target); extracting = true; int read; while ((read = is.read(buffer)) != -1) { os.write(buffer, 0, read); } os.close(); is.close(); chmod("755", target); } } } catch (Throwable e) { try { if (os != null) os.close(); } catch (IOException e1) { } try { if (is != null) is.close(); } catch (IOException e1) { } if (extracting && target.exists()) target.delete(); errors.add(e.getMessage()); return false; } return true; }
Base
1
private void ensureCorrectTheme(Intent data) { String oldListLayout = data.getStringExtra(SettingsActivity.SP_FEED_LIST_LAYOUT); String newListLayout = mPrefs.getString(SettingsActivity.SP_FEED_LIST_LAYOUT,"0"); if (ThemeChooser.themeRequiresRestartOfUI() || !newListLayout.equals(oldListLayout)) { NewsReaderListActivity.this.recreate(); } else if (data.hasExtra(SettingsActivity.CACHE_CLEARED)) { resetUiAndStartSync(); } }
Base
1
public void handle(HttpServletRequest request, HttpServletResponse response) throws Exception { // We're sending an XML response, so set the response content type to text/xml response.setContentType("text/xml"); // Parse the incoming request as XML SAXReader xmlReader = new SAXReader(); Document doc = xmlReader.read(request.getInputStream()); Element env = doc.getRootElement(); Element body = env.element("body"); // First handle any new subscriptions List<SubscriptionRequest> requests = new ArrayList<SubscriptionRequest>(); List<Element> elements = body.elements("subscribe"); for (Element e : elements) { requests.add(new SubscriptionRequest(e.attributeValue("topic"))); } ServletLifecycle.beginRequest(request); try { ServletContexts.instance().setRequest(request); Manager.instance().initializeTemporaryConversation(); ServletLifecycle.resumeConversation(request); for (SubscriptionRequest req : requests) { req.subscribe(); } // Then handle any unsubscriptions List<String> unsubscribeTokens = new ArrayList<String>(); elements = body.elements("unsubscribe"); for (Element e : elements) { unsubscribeTokens.add(e.attributeValue("token")); } for (String token : unsubscribeTokens) { RemoteSubscriber subscriber = SubscriptionRegistry.instance(). getSubscription(token); if (subscriber != null) { subscriber.unsubscribe(); } } } finally { Lifecycle.endRequest(); } // Package up the response marshalResponse(requests, response.getOutputStream()); }
Class
2
private <T> T unmarshallFromDocument(Document document, Class<T> type) throws SAMLException { try { JAXBContext context = JAXBContext.newInstance(type); Unmarshaller unmarshaller = context.createUnmarshaller(); JAXBElement<T> element = unmarshaller.unmarshal(document, type); return element.getValue(); } catch (JAXBException e) { throw new SAMLException("Unable to unmarshall SAML response", e); } }
Base
1
protected void setDispatchHandler(DispatchHandler dispatchHandler) { this.dispatchHandler = dispatchHandler; }
Base
1
final void setObject(CharSequence name, Iterable<?> values) { final AsciiString normalizedName = normalizeName(name); requireNonNull(values, "values"); final int h = normalizedName.hashCode(); final int i = index(h); remove0(h, i, normalizedName); for (Object v: values) { requireNonNullElement(values, v); add0(h, i, normalizedName, fromObject(v)); } }
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); poly.update(ciphertext, ciphertextOffset, dataLen); finish(ad, dataLen); int temp = 0; for (int index = 0; index < 16; ++index) temp |= (polyKey[index] ^ ciphertext[ciphertextOffset + dataLen + index]); if ((temp & 0xFF) != 0) Noise.throwBadTagException(); encrypt(ciphertext, ciphertextOffset, plaintext, plaintextOffset, dataLen); return dataLen; }
Base
1
public static void main(String[] args) { // Will serve all static file are under "/public" in classpath if the route isn't consumed by others routes. staticFileLocation("/public"); get("/hello", (request, response) -> { return "Hello World!"; }); }
Base
1
public void translate(ServerVehicleMovePacket packet, GeyserSession session) { Entity entity = session.getRidingVehicleEntity(); if (entity == null) return; entity.moveAbsolute(session, Vector3f.from(packet.getX(), packet.getY(), packet.getZ()), packet.getYaw(), packet.getPitch(), false, true); }
Class
2
private <T> Document marshallToDocument(JAXBElement<T> object, Class<T> type) throws SAMLException { try { JAXBContext context = JAXBContext.newInstance(type); Marshaller marshaller = context.createMarshaller(); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); DocumentBuilder db = dbf.newDocumentBuilder(); Document document = db.newDocument(); marshaller.marshal(object, document); return document; } catch (JAXBException | ParserConfigurationException e) { throw new SAMLException("Unable to marshallRequest JAXB SAML object to DOM.", e); } }
Base
1
public static void main(String[] args) throws LifecycleException { String webappDirLocation; if (Constants.IN_JAR) { webappDirLocation = "webapp"; } else { webappDirLocation = "src/main/webapp/"; } Tomcat tomcat = new Tomcat(); String webPort = System.getenv("PORT"); if (webPort == null || webPort.isEmpty()) { webPort = "8080"; } tomcat.setPort(Integer.valueOf(webPort)); tomcat.getConnector(); // Declare an alternative location for your "WEB-INF/classes" dir // Servlet 3.0 annotation will work File additionWebInfClasses; if (Constants.IN_JAR) { additionWebInfClasses = new File(""); } else { additionWebInfClasses = new File("target/classes"); } tomcat.setBaseDir(additionWebInfClasses.toString()); //idea的路径eclipse启动的路径有区别 if (!Constants.IN_JAR && !new File("").getAbsolutePath().endsWith(File.separator + "web")) { webappDirLocation = "web/" + webappDirLocation; } tomcat.addWebapp("", new File(webappDirLocation).getAbsolutePath()); tomcat.start(); tomcat.getServer().await(); }
Base
1
void controlChars() { assertThat(PathAndQuery.parse("/\0")).isNull(); assertThat(PathAndQuery.parse("/a\nb")).isNull(); assertThat(PathAndQuery.parse("/a\u007fb")).isNull(); // Escaped assertThat(PathAndQuery.parse("/%00")).isNull(); assertThat(PathAndQuery.parse("/a%09b")).isNull(); assertThat(PathAndQuery.parse("/a%0ab")).isNull(); assertThat(PathAndQuery.parse("/a%0db")).isNull(); assertThat(PathAndQuery.parse("/a%7fb")).isNull(); // With query string assertThat(PathAndQuery.parse("/\0?c")).isNull(); assertThat(PathAndQuery.parse("/a\tb?c")).isNull(); assertThat(PathAndQuery.parse("/a\nb?c")).isNull(); assertThat(PathAndQuery.parse("/a\rb?c")).isNull(); assertThat(PathAndQuery.parse("/a\u007fb?c")).isNull(); // With query string with control chars assertThat(PathAndQuery.parse("/?\0")).isNull(); assertThat(PathAndQuery.parse("/?%00")).isNull(); assertThat(PathAndQuery.parse("/?a\u007fb")).isNull(); assertThat(PathAndQuery.parse("/?a%7Fb")).isNull(); // However, 0x0A, 0x0D, 0x09 should be accepted in a query string. assertThat(PathAndQuery.parse("/?a\tb").query()).isEqualTo("a%09b"); assertThat(PathAndQuery.parse("/?a\nb").query()).isEqualTo("a%0Ab"); assertThat(PathAndQuery.parse("/?a\rb").query()).isEqualTo("a%0Db"); assertThat(PathAndQuery.parse("/?a%09b").query()).isEqualTo("a%09b"); assertThat(PathAndQuery.parse("/?a%0Ab").query()).isEqualTo("a%0Ab"); assertThat(PathAndQuery.parse("/?a%0Db").query()).isEqualTo("a%0Db"); }
Base
1
public void existingDocumentTerminalFromUI() 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&tocreate=terminal when(mockRequest.getParameter("spaceReference")).thenReturn("X"); when(mockRequest.getParameter("name")).thenReturn("Y"); when(mockRequest.getParameter("tocreate")).thenReturn("terminal"); // Run the action String result = action.render(context); // The tests are below this line! // Verify null is returned (this means the response has been returned) assertNull(result); // Note: We are creating X.Y instead of X.Y.WebHome because the tocreate parameter says "terminal". verify(mockURLFactory).createURL("X", "Y", "edit", "template=&parent=Main.WebHome&title=Y", null, "xwiki", context); }
Class
2
private String getSkinResourcePath(String resource) { String skinFolder = getSkinFolder(); String resourcePath = skinFolder + resource; // Prevent inclusion of templates from other directories Path normalizedResource = Paths.get(resourcePath).normalize(); // Protect against directory attacks. if (!normalizedResource.startsWith(skinFolder)) { LOGGER.warn("Direct access to skin file [{}] refused. Possible break-in attempt!", normalizedResource); return null; } return resourcePath; }
Base
1
private void testBSI() throws Exception { KeyPairGenerator kpGen = KeyPairGenerator.getInstance("ECDSA", "BC"); kpGen.initialize(new ECGenParameterSpec(TeleTrusTObjectIdentifiers.brainpoolP512r1.getId())); KeyPair kp = kpGen.generateKeyPair(); byte[] data = "Hello World!!!".getBytes(); String[] cvcAlgs = { "SHA1WITHCVC-ECDSA", "SHA224WITHCVC-ECDSA", "SHA256WITHCVC-ECDSA", "SHA384WITHCVC-ECDSA", "SHA512WITHCVC-ECDSA" }; String[] cvcOids = { EACObjectIdentifiers.id_TA_ECDSA_SHA_1.getId(), EACObjectIdentifiers.id_TA_ECDSA_SHA_224.getId(), EACObjectIdentifiers.id_TA_ECDSA_SHA_256.getId(), EACObjectIdentifiers.id_TA_ECDSA_SHA_384.getId(), EACObjectIdentifiers.id_TA_ECDSA_SHA_512.getId() }; testBsiAlgorithms(kp, data, cvcAlgs, cvcOids); String[] plainAlgs = { "SHA1WITHPLAIN-ECDSA", "SHA224WITHPLAIN-ECDSA", "SHA256WITHPLAIN-ECDSA", "SHA384WITHPLAIN-ECDSA", "SHA512WITHPLAIN-ECDSA", "RIPEMD160WITHPLAIN-ECDSA" }; String[] plainOids = { BSIObjectIdentifiers.ecdsa_plain_SHA1.getId(), BSIObjectIdentifiers.ecdsa_plain_SHA224.getId(), BSIObjectIdentifiers.ecdsa_plain_SHA256.getId(), BSIObjectIdentifiers.ecdsa_plain_SHA384.getId(), BSIObjectIdentifiers.ecdsa_plain_SHA512.getId(), BSIObjectIdentifiers.ecdsa_plain_RIPEMD160.getId() }; testBsiAlgorithms(kp, data, plainAlgs, plainOids); }
Base
1
public void existingDocumentNonTerminalFromUIDeprecatedIgnoringPage() throws Exception { // current document = xwiki:Main.WebHome DocumentReference documentReference = new DocumentReference("xwiki", Arrays.asList("Main"), "WebHome"); XWikiDocument document = mock(XWikiDocument.class); when(document.getDocumentReference()).thenReturn(documentReference); when(document.isNew()).thenReturn(false); when(document.getLocalReferenceMaxLength()).thenReturn(255); context.setDoc(document); // Submit from the UI space=X&page=Y&tocreate=space when(mockRequest.getParameter("space")).thenReturn("X"); when(mockRequest.getParameter("page")).thenReturn("Y"); when(mockRequest.getParameter("tocreate")).thenReturn("space"); // Run the action String result = action.render(context); // The tests are below this line! // Verify null is returned (this means the response has been returned) assertNull(result); // Note: We are creating X.WebHome instead of X.Y because the tocreate parameter says "space" and the page // parameter is ignored. verify(mockURLFactory).createURL("X", "WebHome", "edit", "template=&parent=Main.WebHome&title=X", null, "xwiki", context); }
Class
2
private static Stream<Arguments> provideFilesAndExpectedExceptionType() { return Stream.of( Arguments.of("abnormal/corrupt-header.rar", CorruptHeaderException.class), Arguments.of("abnormal/mainHeaderNull.rar", BadRarArchiveException.class) ); }
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 encodeByteArray2() { Packet<byte[]> packet = new Packet<>(Parser.BINARY_EVENT); packet.data = new byte[2]; packet.id = 0; packet.nsp = "/"; Helpers.testBin(packet); }
Base
1
public Argument<CompletableFuture> argumentType() { return Argument.of(CompletableFuture.class); }
Class
2
public synchronized <T extends Result> T setResult(Class<T> resultClass) throws SQLException { checkFreed(); initialize(); if (resultClass == null || DOMResult.class.equals(resultClass)) { domResult = new DOMResult(); active = true; return (T) domResult; } else if (SAXResult.class.equals(resultClass)) { try { SAXTransformerFactory transformerFactory = (SAXTransformerFactory) SAXTransformerFactory.newInstance(); TransformerHandler transformerHandler = transformerFactory.newTransformerHandler(); stringWriter = new StringWriter(); transformerHandler.setResult(new StreamResult(stringWriter)); active = true; return (T) new SAXResult(transformerHandler); } catch (TransformerException te) { throw new PSQLException(GT.tr("Unable to create SAXResult for SQLXML."), PSQLState.UNEXPECTED_ERROR, te); } } else if (StreamResult.class.equals(resultClass)) { stringWriter = new StringWriter(); active = true; return (T) new StreamResult(stringWriter); } else if (StAXResult.class.equals(resultClass)) { stringWriter = new StringWriter(); try { XMLOutputFactory xof = XMLOutputFactory.newInstance(); XMLStreamWriter xsw = xof.createXMLStreamWriter(stringWriter); active = true; return (T) new StAXResult(xsw); } catch (XMLStreamException xse) { throw new PSQLException(GT.tr("Unable to create StAXResult for SQLXML"), PSQLState.UNEXPECTED_ERROR, xse); } } throw new PSQLException(GT.tr("Unknown XML Result class: {0}", resultClass), PSQLState.INVALID_PARAMETER_TYPE); }
Base
1
public void multipleValuesPerNameIteratorEmpty() { final HttpHeadersBase headers = newEmptyHeaders(); assertThat(headers.valueIterator("name")).isExhausted(); assertThatThrownBy(() -> headers.valueIterator("name").next()) .isInstanceOf(NoSuchElementException.class); }
Class
2
public static final String getRevision() { return "a"; }
Class
2
public HgVersion version() { CommandLine hg = createCommandLine("hg").withArgs("version").withEncoding("utf-8"); String hgOut = execute(hg, new NamedProcessTag("hg version check")).outputAsString(); return HgVersion.parse(hgOut); }
Class
2
public static ByteBuffer serializeToByteBuffer(final Object payload) throws IOException { return ByteBuffer.wrap(serializeToBytes(payload)); }
Base
1
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (request instanceof HttpServletRequest && response instanceof HttpServletResponse) { HttpServletRequest httpReq = (HttpServletRequest) request; HttpServletResponse httpResp = (HttpServletResponse) response; if ("GET".equals(httpReq.getMethod())) { Meteor meteor = Meteor.build(httpReq, SCOPE.REQUEST, Collections.<BroadcastFilter>emptyList(), null); String pushSessionId = httpReq.getParameter(PUSH_SESSION_ID_PARAM); Session session = null; if (pushSessionId != null) { ensureServletContextAvailable(request); PushContext pushContext = (PushContext) servletContext.getAttribute(PushContext.INSTANCE_KEY_NAME); session = pushContext.getSessionManager().getPushSession(pushSessionId); } if (session == null) { if (LOGGER.isDebugEnabled()) { LOGGER.debug(MessageFormat.format("Session {0} was not found", pushSessionId)); } httpResp.sendError(HttpServletResponse.SC_BAD_REQUEST); return; } httpResp.setContentType("text/plain"); try { Request pushRequest = new RequestImpl(meteor, session); httpReq.setAttribute(SESSION_ATTRIBUTE_NAME, session); httpReq.setAttribute(REQUEST_ATTRIBUTE_NAME, pushRequest); pushRequest.suspend(); } catch (Exception e) { LOGGER.error(e.getMessage(), e); } return; } } }
Class
2
public void setXMLReaderClassName(String xmlReaderClassName) throws SAXException { setXMLReader(XMLReaderFactory.createXMLReader(xmlReaderClassName)); }
Base
1
void allReservedCharacters() { final PathAndQuery res = PathAndQuery.parse("/#/:[]@!$&'()*+,;=?a=/#/:[]@!$&'()*+,;="); assertThat(res).isNotNull(); assertThat(res.path()).isEqualTo("/#/:[]@!$&'()*+,;="); assertThat(res.query()).isEqualTo("a=/#/:[]@!$&'()*+,;="); final PathAndQuery res2 = PathAndQuery.parse("/%23%2F%3A%5B%5D%40%21%24%26%27%28%29%2A%2B%2C%3B%3D%3F" + "?a=%23%2F%3A%5B%5D%40%21%24%26%27%28%29%2A%2B%2C%3B%3D%3F"); assertThat(res2).isNotNull(); assertThat(res2.path()).isEqualTo("/#%2F:[]@!$&'()*+,;=?"); assertThat(res2.query()).isEqualTo("a=%23%2F%3A%5B%5D%40%21%24%26%27%28%29%2A%2B%2C%3B%3D%3F"); }
Base
1
public void testSetOrdersPseudoHeadersCorrectly() { final HttpHeadersBase headers = newHttp2Headers(); final HttpHeadersBase other = newEmptyHeaders(); other.add("name2", "value2"); other.add("name3", "value3"); other.add("name4", "value4"); other.authority("foo"); final int headersSizeBefore = headers.size(); headers.set(other); verifyPseudoHeadersFirst(headers); verifyAllPseudoHeadersPresent(headers); assertThat(headers.size()).isEqualTo(headersSizeBefore + 1); assertThat(headers.authority()).isEqualTo("foo"); assertThat(headers.get("name2")).isEqualTo("value2"); assertThat(headers.get("name3")).isEqualTo("value3"); assertThat(headers.get("name4")).isEqualTo("value4"); }
Class
2
protected void afterFeaturesReceived() throws SecurityRequiredException, NotConnectedException { StartTls startTlsFeature = getFeature(StartTls.ELEMENT, StartTls.NAMESPACE); if (startTlsFeature != null) { if (startTlsFeature.required() && config.getSecurityMode() == SecurityMode.disabled) { notifyConnectionError(new SecurityRequiredByServerException()); return; } if (config.getSecurityMode() != ConnectionConfiguration.SecurityMode.disabled) { send(new StartTls()); } } // If TLS is required but the server doesn't offer it, disconnect // from the server and throw an error. First check if we've already negotiated TLS // and are secure, however (features get parsed a second time after TLS is established). if (!isSecureConnection() && startTlsFeature == null && getConfiguration().getSecurityMode() == SecurityMode.required) { throw new SecurityRequiredByClientException(); } if (getSASLAuthentication().authenticationSuccessful()) { // If we have received features after the SASL has been successfully completed, then we // have also *maybe* received, as it is an optional feature, the compression feature // from the server. maybeCompressFeaturesReceived.reportSuccess(); } }
Class
2
final void addObject(CharSequence name, Iterable<?> values) { final AsciiString normalizedName = normalizeName(name); requireNonNull(values, "values"); for (Object v : values) { requireNonNullElement(values, v); addObject(normalizedName, v); } }
Class
2
public void testGetShellCommandLineBash_WithSingleQuotedArg() throws Exception { Commandline cmd = new Commandline( new BourneShell() ); cmd.setExecutable( "/bin/echo" ); cmd.addArguments( new String[] { "\'hello world\'" } ); String[] shellCommandline = cmd.getShellCommandline(); assertEquals( "Command line size", 3, shellCommandline.length ); assertEquals( "/bin/sh", shellCommandline[0] ); assertEquals( "-c", shellCommandline[1] ); String expectedShellCmd = "/bin/echo \'hello world\'"; if ( Os.isFamily( Os.FAMILY_WINDOWS ) ) { expectedShellCmd = "\\bin\\echo \'hello world\'"; } assertEquals( expectedShellCmd, shellCommandline[2] ); }
Base
1
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); poly.update(ciphertext, ciphertextOffset, dataLen); finish(ad, dataLen); int temp = 0; for (int index = 0; index < 16; ++index) temp |= (polyKey[index] ^ ciphertext[ciphertextOffset + dataLen + index]); if ((temp & 0xFF) != 0) Noise.throwBadTagException(); encrypt(ciphertext, ciphertextOffset, plaintext, plaintextOffset, dataLen); return dataLen; }
Base
1
void sendResetPasswordEmailRequest() throws Exception { when(this.referenceSerializer.serialize(this.userReference)).thenReturn("user:Foobar"); when(this.userProperties.getFirstName()).thenReturn("Foo"); when(this.userProperties.getLastName()).thenReturn("Bar"); AuthenticationResourceReference resourceReference = new AuthenticationResourceReference(AuthenticationAction.RESET_PASSWORD); String verificationCode = "foobar4242"; resourceReference.addParameter("u", "user:Foobar"); resourceReference.addParameter("v", verificationCode); ExtendedURL firstExtendedURL = new ExtendedURL(Arrays.asList("authenticate", "reset"), resourceReference.getParameters()); when(this.resourceReferenceSerializer.serialize(resourceReference)).thenReturn(firstExtendedURL); when(this.urlNormalizer.normalize(firstExtendedURL)).thenReturn( new ExtendedURL(Arrays.asList("xwiki", "authenticate", "reset"), resourceReference.getParameters()) ); XWikiURLFactory urlFactory = mock(XWikiURLFactory.class); when(this.context.getURLFactory()).thenReturn(urlFactory); when(urlFactory.getServerURL(this.context)).thenReturn(new URL("http://xwiki.org")); InternetAddress email = new InternetAddress("[email protected]"); DefaultResetPasswordRequestResponse requestResponse = new DefaultResetPasswordRequestResponse(this.userReference, email, verificationCode); this.resetPasswordManager.sendResetPasswordEmailRequest(requestResponse); verify(this.resetPasswordMailSender).sendResetPasswordEmail("Foo Bar", email, new URL("http://xwiki.org/xwiki/authenticate/reset?u=user%3AFoobar&v=foobar4242")); }
Base
1
protected DispatchHandler getDispatchHandler() { if (dispatchHandler == null) { dispatchHandler = new DispatchHandler(); } return dispatchHandler; }
Base
1
public void highlightInMuc(Conversation conversation, String nick) { switchToConversation(conversation, null, false, nick, false); }
Class
2
public void testSelectByUseNotSpecifiedOrSignature() { JWKSelector selector = new JWKSelector(new JWKMatcher.Builder().keyUses(KeyUse.SIGNATURE, null).build()); List<JWK> keyList = new ArrayList<>(); keyList.add(new RSAKey.Builder(new Base64URL("n"), new Base64URL("e")).keyID("1").keyUse(KeyUse.SIGNATURE).build()); keyList.add(new ECKey.Builder(ECKey.Curve.P_256, new Base64URL("x"), new Base64URL("y")).keyID("2").build()); keyList.add(new ECKey.Builder(ECKey.Curve.P_256, new Base64URL("x"), new Base64URL("y")).keyID("3").keyUse(KeyUse.ENCRYPTION).build()); JWKSet jwkSet = new JWKSet(keyList); List<JWK> matches = selector.select(jwkSet); RSAKey key1 = (RSAKey)matches.get(0); assertEquals(KeyType.RSA, key1.getKeyType()); assertEquals(KeyUse.SIGNATURE, key1.getKeyUse()); assertEquals("1", key1.getKeyID()); ECKey key2 = (ECKey)matches.get(1); assertEquals(KeyType.EC, key2.getKeyType()); assertEquals("2", key2.getKeyID()); assertEquals(2, matches.size()); }
Base
1
public static byte[] serializeToBytes(final Object payload) throws IOException { final ByteArrayOutputStream bos = new ByteArrayOutputStream(); serializeToStream(bos, payload); return bos.toByteArray(); }
Base
1
public void debug() throws IOException, ServletException { servlet = new AgentServlet(); initConfigMocks(new String[]{ConfigKey.DEBUG.getKeyValue(), "true"},null,"No access restrictor found",null); context.log(find("URI:")); context.log(find("Path-Info:")); context.log(find("Request:")); context.log(find("time:")); context.log(find("Response:")); context.log(find("TestDetector"),isA(RuntimeException.class)); expectLastCall().anyTimes(); replay(config, context); servlet.init(config); StringWriter sw = initRequestResponseMocks(); expect(request.getPathInfo()).andReturn(HttpTestUtil.HEAP_MEMORY_GET_REQUEST); expect(request.getParameter(ConfigKey.MIME_TYPE.getKeyValue())).andReturn(null); replay(request, response); servlet.doGet(request, response); assertTrue(sw.toString().contains("used")); servlet.destroy(); }
Compound
4
public int clone(ConsoleOutputStreamConsumer outputStreamConsumer, UrlArgument repositoryUrl) { CommandLine hg = createCommandLine("hg").withArgs("clone").withArg("-b").withArg(branch).withArg(repositoryUrl) .withArg(workingDir.getAbsolutePath()).withNonArgSecrets(secrets).withEncoding("utf-8"); return execute(hg, outputStreamConsumer); }
Class
2
callback: (request: PublishRequest, response: PublishResponse) => void;
Base
1
public void setProperty(String name, Object value) throws SAXException { getXMLReader().setProperty(name, value); }
Base
1