code
stringlengths
12
2.05k
label_name
stringclasses
5 values
label
int64
0
4
protected final void populateUrlAttributeMap(final Map<String, String> urlParameters) { urlParameters.put("pgtUrl", encodeUrl(this.proxyCallbackUrl)); }
Class
2
public int encryptWithAd(byte[] ad, byte[] plaintext, int plaintextOffset, byte[] ciphertext, int ciphertextOffset, int length) throws ShortBufferException { int space; if (ciphertextOffset > ciphertext.length) space = 0; else space = ciphertext.length - ciphertextOffset; if (!haskey) { // The key is not set yet - return the plaintext as-is. if (length > space) throw new ShortBufferException(); if (plaintext != ciphertext || plaintextOffset != ciphertextOffset) System.arraycopy(plaintext, plaintextOffset, ciphertext, ciphertextOffset, length); return length; } if (space < 16 || length > (space - 16)) throw new ShortBufferException(); setup(ad); encryptCTR(plaintext, plaintextOffset, ciphertext, ciphertextOffset, length); 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
/*package*/ static SecretKey getLegacyKey() throws GeneralSecurityException { String secret = SECRET; if(secret==null) return Jenkins.getInstance().getSecretKeyAsAES128(); return Util.toAes128Key(secret); }
Class
2
private boolean isStale(URL source, File target) { if( source.getProtocol().equals("jar") ) { // unwrap the jar protocol... try { String parts[] = source.getFile().split(Pattern.quote("!")); source = new URL(parts[0]); } catch (MalformedURLException e) { return false; } } File sourceFile=null; if( source.getProtocol().equals("file") ) { sourceFile = new File(source.getFile()); } if( sourceFile!=null && sourceFile.exists() ) { if( sourceFile.lastModified() > target.lastModified() ) { return true; } } return false; }
Base
1
public static synchronized InitialContext getInitialContext() throws NamingException { if (context == null) { try { context = new InitialContext(); } catch (Exception e) { throw handleException(e); } } return context; }
Class
2
private String stripComments(String theScript) { return BLOCK_COMMENT_STRIPPER.matcher(theScript).replaceAll(""); }
Base
1
public void setStringInternEnabled(boolean stringInternEnabled) { this.stringInternEnabled = stringInternEnabled; }
Base
1
void empty() { final PathAndQuery res = PathAndQuery.parse(null); assertThat(res).isNotNull(); assertThat(res.path()).isEqualTo("/"); assertThat(res.query()).isNull(); final PathAndQuery res2 = PathAndQuery.parse(""); assertThat(res2).isNotNull(); assertThat(res2.path()).isEqualTo("/"); assertThat(res2.query()).isNull(); final PathAndQuery res3 = PathAndQuery.parse("?"); assertThat(res3).isNotNull(); assertThat(res3.path()).isEqualTo("/"); assertThat(res3.query()).isEqualTo(""); }
Base
1
public void checkConnection(UrlArgument repoUrl) { final String ref = fullUpstreamRef(); final CommandLine commandLine = git().withArgs("ls-remote").withArg(repoUrl).withArg(ref); final ConsoleResult result = commandLine.runOrBomb(new NamedProcessTag(repoUrl.forDisplay())); if (!hasExactlyOneMatchingBranch(result)) { throw new CommandLineException(format("The ref %s could not be found.", ref)); } }
Class
2
protected int getExpectedErrors() { return hasJavaNetURLPermission ? 2 : 1; // Security error must be reported as an error. Java 8 reports two errors. }
Class
2
new X509TrustManager() { public java.security.cert.X509Certificate[] getAcceptedIssuers() { return new java.security.cert.X509Certificate[]{}; } public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) { //No need to implement. } public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) { //No need to implement. } }
Base
1
public void todo_oldTasks() { String taskName = UUID.randomUUID().toString(); PersistentTask ctask = persistentTaskDao.createTask(taskName, new DummyTask()); //simulate a task from a previous boot PersistentTask ptask = new PersistentTask(); ptask.setCreationDate(new Date()); ptask.setLastModified(new Date()); ptask.setName(UUID.randomUUID().toString()); ptask.setStatus(TaskStatus.inWork); ptask.setExecutorBootId(UUID.randomUUID().toString()); ptask.setExecutorNode(Integer.toString(WebappHelper.getNodeId())); ptask.setTask(XStreamHelper.createXStreamInstance().toXML(new DummyTask())); dbInstance.getCurrentEntityManager().persist(ptask); //simulate a task from an other node PersistentTask alienTask = new PersistentTask(); alienTask.setCreationDate(new Date()); alienTask.setLastModified(new Date()); alienTask.setName(UUID.randomUUID().toString()); alienTask.setStatus(TaskStatus.inWork); alienTask.setExecutorBootId(UUID.randomUUID().toString()); alienTask.setExecutorNode(Integer.toString(WebappHelper.getNodeId() + 1)); alienTask.setTask(XStreamHelper.createXStreamInstance().toXML(new DummyTask())); dbInstance.getCurrentEntityManager().persist(alienTask); dbInstance.commitAndCloseSession(); List<Long> todos = persistentTaskDao.tasksToDo(); Assert.assertNotNull(todos); Assert.assertFalse(todos.isEmpty()); Assert.assertTrue(todos.contains(ptask.getKey())); Assert.assertTrue(todos.contains(ctask.getKey())); Assert.assertFalse(todos.contains(alienTask.getKey())); }
Base
1
public Controller getMediaController(UserRequest ureq, WindowControl wControl, Media media, MediaRenderingHints hints) { String statementXml = media.getContent(); EfficiencyStatement statement = null; if(StringHelper.containsNonWhitespace(statementXml)) { try { statement = (EfficiencyStatement)myXStream.fromXML(statementXml); } catch (Exception e) { log.error("Cannot load efficiency statement from artefact", e); } } CertificateAndEfficiencyStatementController ctrl = new CertificateAndEfficiencyStatementController(wControl, ureq, statement); ctrl.disableMediaCollector(); return ctrl; }
Base
1
private final HColor getBackColor(UmlDiagramType umlDiagramType, Style style) { if (EntityUtils.groupRoot(group)) return null; final HColor result = group.getColors().getColor(ColorType.BACK); if (result != null) return result; final Stereotype stereo = group.getStereotype(); if (UseStyle.useBetaStyle()) return style.value(PName.BackGroundColor).asColor(skinParam.getThemeStyle(), skinParam.getIHtmlColorSet()); final USymbol sym = group.getUSymbol() == null ? USymbols.PACKAGE : group.getUSymbol(); final ColorParam backparam = umlDiagramType == UmlDiagramType.ACTIVITY ? ColorParam.partitionBackground : sym.getColorParamBack(); final HColor c1 = skinParam.getHtmlColor(backparam, stereo, false); if (c1 != null) return c1; if (parentCluster == null) return null; return parentCluster.getBackColor(umlDiagramType, style); }
Base
1
public VFSContainer createChildContainer(String name) { File fNewFile = new File(getBasefile(), name); if (!fNewFile.mkdir()) return null; LocalFolderImpl locFI = new LocalFolderImpl(fNewFile, this); locFI.setDefaultItemFilter(defaultFilter); return locFI; }
Base
1
private ModelAndView renameGroup(HttpServletRequest request, HttpServletResponse response) throws Exception { String oldName = request.getParameter("groupName"); String newName = request.getParameter("newName"); if (StringUtils.hasText(oldName) && StringUtils.hasText(newName)) { m_groupRepository.renameGroup(oldName, newName); } return listGroups(request, response); }
Compound
4
public VFSLeaf createChildLeaf(String name) { File fNewFile = new File(getBasefile(), name); try { if(!fNewFile.getParentFile().exists()) { fNewFile.getParentFile().mkdirs(); } if (!fNewFile.createNewFile()) { log.warn("Could not create a new leaf::" + name + " in container::" + getBasefile().getAbsolutePath() + " - file alreay exists"); return null; } } catch (Exception e) { log.error("Error while creating child leaf::" + name + " in container::" + getBasefile().getAbsolutePath(), e); return null; } return new LocalFileImpl(fNewFile, this); }
Base
1
private String getMimeType(ParsedUri pParsedUri) { if (pParsedUri.getParameter(ConfigKey.CALLBACK.getKeyValue()) != null) { return "text/javascript"; } else { String mimeType = pParsedUri.getParameter(ConfigKey.MIME_TYPE.getKeyValue()); if (mimeType != null) { return mimeType; } mimeType = configuration.get(ConfigKey.MIME_TYPE); return mimeType != null ? mimeType : ConfigKey.MIME_TYPE.getDefaultValue(); } }
Base
1
public void translate(ServerEntityRemoveEffectPacket packet, GeyserSession session) { Entity entity; if (packet.getEntityId() == session.getPlayerEntity().getEntityId()) { entity = session.getPlayerEntity(); session.getEffectCache().removeEffect(packet.getEffect()); } else { entity = session.getEntityCache().getEntityByJavaId(packet.getEntityId()); } if (entity == null) return; MobEffectPacket mobEffectPacket = new MobEffectPacket(); mobEffectPacket.setEvent(MobEffectPacket.Event.REMOVE); mobEffectPacket.setRuntimeEntityId(entity.getGeyserId()); mobEffectPacket.setEffectId(EntityUtils.toBedrockEffectId(packet.getEffect())); session.sendUpstreamPacket(mobEffectPacket); }
Class
2
protected String getCorsDomain(String referer, String userAgent) { String dom = null; if (referer != null && referer.toLowerCase() .matches("https?://([a-z0-9,-]+[.])*draw[.]io/.*")) { dom = referer.toLowerCase().substring(0, referer.indexOf(".draw.io/") + 8); } else if (referer != null && referer.toLowerCase() .matches("https?://([a-z0-9,-]+[.])*diagrams[.]net/.*")) { dom = referer.toLowerCase().substring(0, referer.indexOf(".diagrams.net/") + 13); } else if (referer != null && referer.toLowerCase() .matches("https?://([a-z0-9,-]+[.])*quipelements[.]com/.*")) { dom = referer.toLowerCase().substring(0, referer.indexOf(".quipelements.com/") + 17); } // Enables Confluence/Jira proxy via referer or hardcoded user-agent (for old versions) // UA refers to old FF on macOS so low risk and fixes requests from existing servers else if ((referer != null && referer.equals("draw.io Proxy Confluence Server")) || (userAgent != null && userAgent.equals( "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.12; rv:50.0) Gecko/20100101 Firefox/50.0"))) { dom = ""; } return dom; }
Base
1
void requestResetPasswordWithoutPR() throws Exception { when(this.authorizationManager.hasAccess(Right.PROGRAM)).thenReturn(false); assertNull(this.scriptService.requestResetPassword(mock(UserReference.class))); verify(this.resetPasswordManager, never()).requestResetPassword(any()); verify(this.resetPasswordManager, never()).sendResetPasswordEmailRequest(any()); }
Base
1
public void setStripWhitespaceText(boolean stripWhitespaceText) { this.stripWhitespaceText = stripWhitespaceText; }
Base
1
public String createSession(final String iDatabaseName, final String iUserName, final String iUserPassword) { acquireExclusiveLock(); try { final String id = "OS" + System.currentTimeMillis() + random.nextLong(); sessions.put(id, new OHttpSession(id, iDatabaseName, iUserName, iUserPassword)); return id; } finally { releaseExclusiveLock(); } }
Class
2
public void translate(SetPlayerGameTypePacket packet, GeyserSession session) { // no SetPlayerGameTypePacket playerGameTypePacket = new SetPlayerGameTypePacket(); playerGameTypePacket.setGamemode(session.getGameMode().ordinal()); session.sendUpstreamPacket(playerGameTypePacket); }
Class
2
public Element handle(Element request, Map<String, Object> context) throws ServiceException { ZimbraSoapContext zsc = getZimbraSoapContext(context); Account account = getRequestedAccount(getZimbraSoapContext(context)); if (!canAccessAccount(zsc, account)) throw ServiceException.PERM_DENIED("can not access account"); String name = request.getAttribute(AccountConstants.E_NAME); String typeStr = request.getAttribute(AccountConstants.A_TYPE, "account"); GalSearchType type = GalSearchType.fromString(typeStr); boolean needCanExpand = request.getAttributeBool(AccountConstants.A_NEED_EXP, false); String galAcctId = request.getAttribute(AccountConstants.A_GAL_ACCOUNT_ID, null); GalSearchParams params = new GalSearchParams(account, zsc); params.setType(type); params.setRequest(request); params.setQuery(name); params.setLimit(account.getContactAutoCompleteMaxResults()); params.setNeedCanExpand(needCanExpand); params.setResponseName(AccountConstants.AUTO_COMPLETE_GAL_RESPONSE); if (galAcctId != null) params.setGalSyncAccount(Provisioning.getInstance().getAccountById(galAcctId)); GalSearchControl gal = new GalSearchControl(params); gal.autocomplete(); return params.getResultCallback().getResponse(); }
Class
2
public void translate(ServerUnlockRecipesPacket packet, GeyserSession session) { if (packet.getAction() == UnlockRecipesAction.REMOVE) { session.getUnlockedRecipes().removeAll(Arrays.asList(packet.getRecipes())); } else { session.getUnlockedRecipes().addAll(Arrays.asList(packet.getRecipes())); } }
Class
2
public void translate(ServerStatisticsPacket packet, GeyserSession session) { session.updateStatistics(packet.getStatistics()); if (session.isWaitingForStatistics()) { session.setWaitingForStatistics(false); StatisticsUtils.buildAndSendStatisticsMenu(session); } }
Class
2
final void add(CharSequence name, Iterable<String> values) { final AsciiString normalizedName = normalizeName(name); requireNonNull(values, "values"); final int h = normalizedName.hashCode(); final int i = index(h); for (String v : values) { requireNonNullElement(values, v); add0(h, i, normalizedName, v); } }
Class
2
public IdImpl(String id) { this.id = id; }
Class
2
public void testAADLengthComputation() { Assert.assertArrayEquals(AAD_LENGTH, com.nimbusds.jose.crypto.AAD.computeLength(AAD)); }
Class
2
private String escapeString(final String string) { if (string == null || string.length() == 0) { return "\"\""; } char c = 0; int i; final int len = string.length(); final StringBuilder sb = new StringBuilder(len + 4); String t; sb.append('"'); for (i = 0; i < len; i += 1) { c = string.charAt(i); switch (c) { case '\\': case '"': sb.append('\\'); sb.append(c); break; case '/': // if (b == '<') { sb.append('\\'); // } sb.append(c); break; case '\b': sb.append("\\b"); break; case '\t': sb.append("\\t"); break; case '\n': sb.append("\\n"); break; case '\f': sb.append("\\f"); break; case '\r': sb.append("\\r"); break; default: if (c < ' ') { t = "000" + Integer.toHexString(c); sb.append("\\u" + t.substring(t.length() - 4)); } else { sb.append(c); } } } sb.append('"'); return sb.toString(); }
Base
1
public Controller execute(FolderComponent fc, UserRequest ureq, WindowControl windowControl, Translator trans) { this.folderComponent = fc; this.translator = trans; this.fileSelection = new FileSelection(ureq, fc.getCurrentContainerPath()); VelocityContainer main = new VelocityContainer("mc", VELOCITY_ROOT + "/movecopy.html", translator, this); main.contextPut("fileselection", fileSelection); //check if command is executed on a file list containing invalid filenames or paths if(!fileSelection.getInvalidFileNames().isEmpty()) { main.contextPut("invalidFileNames", fileSelection.getInvalidFileNames()); } selTree = new MenuTree(null, "seltree", this); FolderTreeModel ftm = new FolderTreeModel(ureq.getLocale(), fc.getRootContainer(), true, false, true, fc.getRootContainer().canWrite() == VFSConstants.YES, new EditableFilter()); selTree.setTreeModel(ftm); selectButton = LinkFactory.createButton(move ? "move" : "copy", main, this); cancelButton = LinkFactory.createButton("cancel", main, this); main.put("seltree", selTree); if (move) { main.contextPut("move", Boolean.TRUE); } setInitialComponent(main); return this; }
Base
1
public XssHttpServletRequestWrapper(HttpServletRequest request) { super(request); }
Base
1
protected Map<String, Serializable> getPrincipal(Jwt jwt) { Map<String, Serializable> principal = new HashMap<>(); principal.put("jwt", (Serializable) jwt.getBody()); return principal; }
Base
1
private String getLocalePrefix(FacesContext context) { String localePrefix = null; localePrefix = context.getExternalContext().getRequestParameterMap().get("loc"); if(localePrefix != null){ return localePrefix; } String appBundleName = context.getApplication().getMessageBundle(); if (null != appBundleName) { Locale locale = null; if (context.getViewRoot() != null) { locale = context.getViewRoot().getLocale(); } else { locale = context.getApplication().getViewHandler().calculateLocale(context); } try { ResourceBundle appBundle = ResourceBundle.getBundle(appBundleName, locale, Util.getCurrentLoader(ResourceManager.class)); localePrefix = appBundle .getString(ResourceHandler.LOCALE_PREFIX); } catch (MissingResourceException mre) { if (LOGGER.isLoggable(Level.FINEST)) { LOGGER.log(Level.FINEST, "Ignoring missing resource", mre); } } } return localePrefix; }
Base
1
public void newDocumentWebHomeFromURLTemplateProviderSpecifiedButOldPageType() throws Exception { // new document = xwiki:X.Y.WebHome DocumentReference documentReference = new DocumentReference("xwiki", Arrays.asList("X", "Y"), "WebHome"); XWikiDocument document = mock(XWikiDocument.class); when(document.getDocumentReference()).thenReturn(documentReference); when(document.isNew()).thenReturn(true); when(document.getLocalReferenceMaxLength()).thenReturn(255); context.setDoc(document); // Specifying a template provider in the URL: templateprovider=XWiki.MyTemplateProvider String templateProviderFullName = "XWiki.MyTemplateProvider"; when(mockRequest.getParameter("templateprovider")).thenReturn(templateProviderFullName); // Mock 1 existing template provider mockExistingTemplateProviders(templateProviderFullName, new DocumentReference("xwiki", Arrays.asList("XWiki"), "MyTemplateProvider"), Collections.EMPTY_LIST, 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 as terminal, since the template provider did not specify a "terminal" // property and it used the old "page" type instead. Also using a template, as specified in the template // provider. verify(mockURLFactory).createURL("X", "Y", "edit", "template=XWiki.MyTemplate&parent=Main.WebHome&title=Y", null, "xwiki", context); }
Class
2
public void testMatchUse() { JWKMatcher matcher = new JWKMatcher.Builder().keyUse(KeyUse.ENCRYPTION).build(); assertTrue(matcher.matches(new RSAKey.Builder(new Base64URL("n"), new Base64URL("e")).keyID("1").keyUse(KeyUse.ENCRYPTION).build())); assertFalse(matcher.matches(new ECKey.Builder(ECKey.Curve.P_256, new Base64URL("x"), new Base64URL("y")).keyID("2").build())); assertEquals("use=enc", matcher.toString()); }
Base
1
public void testUri() { final HttpHeadersBase headers = newHttp2Headers(); assertThat(headers.uri()).isEqualTo(URI.create("https://netty.io/index.html")); }
Class
2
private boolean isAdmin(String accountName) { if (this.adminFilter != null) { try { InitialDirContext context = initContext(); String searchString = adminFilter.replace(":login", accountName); SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); NamingEnumeration<SearchResult> results = context.search(searchBase, searchString, searchControls); if (results.hasMoreElements()) { results.nextElement(); if (results.hasMoreElements()) { LOGGER.warn("Matched multiple users for the accountName: " + accountName); return false; } return true; } } catch (NamingException e) { return false; } } return false; }
Class
2
public void addHandler(String path, ElementHandler handler) { getDispatchHandler().addHandler(path, handler); }
Base
1
public void existingDocumentFromUITemplateProviderSpecifiedNonTerminal() throws Exception { // current document = xwiki:Main.WebHome DocumentReference documentReference = new DocumentReference("xwiki", Arrays.asList("Main"), "WebHome"); XWikiDocument document = mock(XWikiDocument.class); when(document.getDocumentReference()).thenReturn(documentReference); when(document.isNew()).thenReturn(false); when(document.getLocalReferenceMaxLength()).thenReturn(255); context.setDoc(document); // Submit from the UI spaceReference=X&name=Y&templateProvider=XWiki.MyTemplateProvider String templateProviderFullName = "XWiki.MyTemplateProvider"; String spaceReferenceString = "X"; when(mockRequest.getParameter("spaceReference")).thenReturn(spaceReferenceString); when(mockRequest.getParameter("name")).thenReturn("Y"); when(mockRequest.getParameter("templateprovider")).thenReturn(templateProviderFullName); // Mock 1 existing template provider that creates terminal documents. mockExistingTemplateProviders(templateProviderFullName, new DocumentReference("xwiki", Arrays.asList("XWiki"), "MyTemplateProvider"), Collections.EMPTY_LIST, false); // Run the action String result = action.render(context); // The tests are below this line! // Verify null is returned (this means the response has been returned) assertNull(result); // Note: We are creating the document X.Y.WebHome as non-terminal and using a template, as specified in the // template provider. verify(mockURLFactory).createURL("X.Y", "WebHome", "edit", "template=XWiki.MyTemplate&parent=Main.WebHome&title=Y", null, "xwiki", context); }
Class
2
protected int addFileNames(String[] file) { // This appears to only be used by unit tests for (int i = 0; file != null && i < file.length; i++) { workUnitList.add(new WorkUnit(file[i])); } return size(); }
Base
1
public void corsEmpty() { InputStream is = getClass().getResourceAsStream("/allow-origin3.xml"); PolicyRestrictor restrictor = new PolicyRestrictor(is); assertTrue(restrictor.isCorsAccessAllowed("http://bla.com")); assertTrue(restrictor.isCorsAccessAllowed("http://www.jolokia.org")); assertTrue(restrictor.isCorsAccessAllowed("http://www.consol.de")); }
Compound
4
public void emptyHeadersShouldBeEqual() { final HttpHeadersBase headers1 = newEmptyHeaders(); final HttpHeadersBase headers2 = newEmptyHeaders(); assertThat(headers2).isEqualTo(headers1); assertThat(headers2.hashCode()).isEqualTo(headers1.hashCode()); }
Class
2
public Cipher decrypt() { try { Cipher cipher = Secret.getCipher(ALGORITHM); cipher.init(Cipher.DECRYPT_MODE, getKey()); return cipher; } catch (GeneralSecurityException e) { throw new AssertionError(e); } }
Class
2
public boolean isValid(Object value, ConstraintValidatorContext context) { final ViolationCollector collector = new ViolationCollector(context); context.disableDefaultConstraintViolation(); for (ValidationCaller caller : methodMap.computeIfAbsent(value.getClass(), this::findMethods)) { caller.setValidationObject(value); caller.call(collector); } return !collector.hasViolationOccurred(); }
Class
2
public int encryptWithAd(byte[] ad, byte[] plaintext, int plaintextOffset, byte[] ciphertext, int ciphertextOffset, int length) throws ShortBufferException { int space; if (ciphertextOffset > ciphertext.length) space = 0; else space = ciphertext.length - ciphertextOffset; if (!haskey) { // The key is not set yet - return the plaintext as-is. if (length > space) throw new ShortBufferException(); if (plaintext != ciphertext || plaintextOffset != ciphertextOffset) System.arraycopy(plaintext, plaintextOffset, ciphertext, ciphertextOffset, length); return length; } if (space < 16 || length > (space - 16)) throw new ShortBufferException(); setup(ad); encrypt(plaintext, plaintextOffset, ciphertext, ciphertextOffset, length); poly.update(ciphertext, ciphertextOffset, length); finish(ad, length); System.arraycopy(polyKey, 0, ciphertext, ciphertextOffset + length, 16); return length + 16; }
Base
1
public void onTurnEnded(TurnEndedEvent event) { super.onTurnEnded(event); final String out = event.getTurnSnapshot().getRobots()[0].getOutputStreamSnapshot(); if (out.contains("An error occurred during initialization")) { messagedInitialization = true; } if (out.contains("access denied (java.net.SocketPermission") || out.contains("access denied (\"java.net.SocketPermission\"")) { messagedAccessDenied = true; } }
Class
2
public Operation.OperationResult executeFixedCostOperation( final MessageFrame frame, final EVM evm) { Bytes shiftAmount = frame.popStackItem(); final Bytes value = leftPad(frame.popStackItem()); final boolean negativeNumber = value.get(0) < 0; if (shiftAmount.size() > 4 && (shiftAmount = shiftAmount.trimLeadingZeros()).size() > 4) { frame.pushStackItem(negativeNumber ? ALL_BITS : UInt256.ZERO); } else { final int shiftAmountInt = shiftAmount.toInt(); if (shiftAmountInt >= 256) { frame.pushStackItem(negativeNumber ? ALL_BITS : UInt256.ZERO); } else { // first perform standard shift right. Bytes result = value.shiftRight(shiftAmountInt); // if a negative number, carry through the sign. if (negativeNumber) { final Bytes32 significantBits = ALL_BITS.shiftLeft(256 - shiftAmountInt); result = result.or(significantBits); } frame.pushStackItem(result); } } return successResponse; }
Base
1
public static Document toXml(final List<IBaseDataObject> list) { final Element root = new Element("payload-list"); for (final IBaseDataObject d : list) { final Document doc = toXml(d); root.addContent(doc.detachRootElement()); logger.debug("Adding xml content for " + d.shortName() + " to document"); } final Document doc = new Document(root); return doc; }
Base
1
void plus() { final PathAndQuery res = PathAndQuery.parse("/+?a+b=c+d"); assertThat(res).isNotNull(); assertThat(res.path()).isEqualTo("/+"); assertThat(res.query()).isEqualTo("a+b=c+d"); final PathAndQuery res2 = PathAndQuery.parse("/%2b?a%2bb=c%2bd"); assertThat(res2).isNotNull(); assertThat(res2.path()).isEqualTo("/+"); assertThat(res2.query()).isEqualTo("a%2Bb=c%2Bd"); }
Base
1
public boolean isValidating() { return validating; }
Base
1
void requestResetPassword() throws Exception { when(this.userManager.exists(this.userReference)).thenReturn(true); InternetAddress email = new InternetAddress("[email protected]"); when(this.userProperties.getEmail()).thenReturn(email); BaseObject xObject = mock(BaseObject.class); when(this.userDocument .getXObject(DefaultResetPasswordManager.RESET_PASSWORD_REQUEST_CLASS_REFERENCE, true, this.context)) .thenReturn(xObject); String verificationCode = "abcde1234"; when(this.xWiki.generateRandomString(30)).thenReturn(verificationCode); when(this.localizationManager.getTranslationPlain("xe.admin.passwordReset.versionComment")) .thenReturn("Save verification code 42"); ResetPasswordRequestResponse expectedResult = new DefaultResetPasswordRequestResponse(this.userReference, email, verificationCode); assertEquals(expectedResult, this.resetPasswordManager.requestResetPassword(this.userReference)); verify(xObject).set(DefaultResetPasswordManager.VERIFICATION_PROPERTY, verificationCode, context); verify(this.xWiki).saveDocument(this.userDocument, "Save verification code 42", true, this.context); }
Base
1
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.shiftRight(shiftAmountInt)); } } return successResponse; }
Base
1
public void newDocumentWebHomeTopLevelFromURL() throws Exception { // new document = xwiki:X.WebHome DocumentReference documentReference = new DocumentReference("xwiki", Arrays.asList("X"), "WebHome"); XWikiDocument document = mock(XWikiDocument.class); when(document.getDocumentReference()).thenReturn(documentReference); when(document.isNew()).thenReturn(true); when(document.getLocalReferenceMaxLength()).thenReturn(255); context.setDoc(document); // Run the action String result = action.render(context); // The tests are below this line! // Verify null is returned (this means the response has been returned) assertNull(result); // Note: The title is not "WebHome", but "X" (the space's name) to avoid exposing "WebHome" in the UI. verify(mockURLFactory).createURL("X", "WebHome", "edit", "template=&parent=Main.WebHome&title=X", null, "xwiki", context); }
Class
2
public static void closeSubsequentFS(Path path) { if(path != null && FileSystems.getDefault() != path.getFileSystem()) { IOUtils.closeQuietly(path.getFileSystem()); } }
Base
1
public void testUpdateMapper_serializade_withExpirationDate() { //create a mapper String mapperId = UUID.randomUUID().toString(); String sessionId = UUID.randomUUID().toString().substring(0, 32); PersistentMapper sMapper = new PersistentMapper("mapper-to-persist-until"); PersistedMapper pMapper = mapperDao.persistMapper(sessionId, mapperId, sMapper, 60000); Assert.assertNotNull(pMapper); dbInstance.commitAndCloseSession(); //load the mapper PersistedMapper loadedMapper = mapperDao.loadByMapperId(mapperId); Assert.assertNotNull(loadedMapper); Object objReloaded = XStreamHelper.createXStreamInstance().fromXML(pMapper.getXmlConfiguration()); Assert.assertTrue(objReloaded instanceof PersistentMapper); PersistentMapper sMapperReloaded = (PersistentMapper)objReloaded; Assert.assertEquals("mapper-to-persist-until", sMapperReloaded.getKey()); Assert.assertNotNull(loadedMapper.getExpirationDate()); //update PersistentMapper sMapper2 = new PersistentMapper("mapper-to-update-until"); boolean updated = mapperDao.updateConfiguration(mapperId, sMapper2, 120000); Assert.assertTrue(updated); dbInstance.commitAndCloseSession(); //load the updated mapper PersistedMapper loadedMapper2 = mapperDao.loadByMapperId(mapperId); Assert.assertNotNull(loadedMapper2); Object objReloaded2 = XStreamHelper.createXStreamInstance().fromXML(loadedMapper2.getXmlConfiguration()); Assert.assertTrue(objReloaded2 instanceof PersistentMapper); PersistentMapper sMapperReloaded2 = (PersistentMapper)objReloaded2; Assert.assertEquals("mapper-to-update-until", sMapperReloaded2.getKey()); Assert.assertNotNull(loadedMapper2.getExpirationDate()); }
Base
1
final void set(CharSequence name, String value) { final AsciiString normalizedName = normalizeName(name); requireNonNull(value, "value"); final int h = normalizedName.hashCode(); final int i = index(h); remove0(h, i, normalizedName); add0(h, i, normalizedName, value); }
Class
2
public DefaultFileSystemResourceLoader(String path) { this.baseDirPath = Optional.of(Paths.get(normalize(path))); }
Base
1
protected int getExpectedErrors() { return hasJavaNetURLPermission ? 3 : 2; // Security error must be reported as an error }
Class
2
protected EntityResolver createDefaultEntityResolver(String systemId) { String prefix = null; if ((systemId != null) && (systemId.length() > 0)) { int idx = systemId.lastIndexOf('/'); if (idx > 0) { prefix = systemId.substring(0, idx + 1); } } return new SAXEntityResolver(prefix); }
Base
1
public void accessAllowed() { expect(backend.isRemoteAccessAllowed("localhost","127.0.0.1")).andReturn(true); replay(backend); handler.checkClientIPAccess("localhost","127.0.0.1"); }
Compound
4
public static String decodePath(String path) { if (path.indexOf('%') < 0) { // No need to decoded; not percent-encoded return path; } // Decode percent-encoded characters. // An invalid character is replaced with 0xFF, which will be replaced into '�' by UTF-8 decoder. final int len = path.length(); try (TemporaryThreadLocals tempThreadLocals = TemporaryThreadLocals.acquire()) { final byte[] buf = tempThreadLocals.byteArray(len); int dstLen = 0; for (int i = 0; i < len; i++) { final char ch = path.charAt(i); if (ch != '%') { buf[dstLen++] = (byte) ((ch & 0xFF80) == 0 ? ch : 0xFF); continue; } // Decode a percent-encoded character. final int hexEnd = i + 3; if (hexEnd > len) { // '%' or '%x' (must be followed by two hexadigits) buf[dstLen++] = (byte) 0xFF; break; } final int digit1 = decodeHexNibble(path.charAt(++i)); final int digit2 = decodeHexNibble(path.charAt(++i)); if (digit1 < 0 || digit2 < 0) { // The first or second digit is not hexadecimal. buf[dstLen++] = (byte) 0xFF; } else { buf[dstLen++] = (byte) ((digit1 << 4) | digit2); } } return new String(buf, 0, dstLen, StandardCharsets.UTF_8); } }
Base
1
protected void initOther() throws ServletException { PropertyUtils.addBeanIntrospector( SuppressPropertiesBeanIntrospector.SUPPRESS_CLASS); PropertyUtils.clearDescriptors(); String value = null; value = getServletConfig().getInitParameter("config"); if (value != null) { config = value; } // Backwards compatibility for form beans of Java wrapper classes // Set to true for strict Struts 1.0 compatibility value = getServletConfig().getInitParameter("convertNull"); if ("true".equalsIgnoreCase(value) || "yes".equalsIgnoreCase(value) || "on".equalsIgnoreCase(value) || "y".equalsIgnoreCase(value) || "1".equalsIgnoreCase(value)) { convertNull = true; } if (convertNull) { ConvertUtils.deregister(); ConvertUtils.register(new BigDecimalConverter(null), BigDecimal.class); ConvertUtils.register(new BigIntegerConverter(null), BigInteger.class); ConvertUtils.register(new BooleanConverter(null), Boolean.class); ConvertUtils.register(new ByteConverter(null), Byte.class); ConvertUtils.register(new CharacterConverter(null), Character.class); ConvertUtils.register(new DoubleConverter(null), Double.class); ConvertUtils.register(new FloatConverter(null), Float.class); ConvertUtils.register(new IntegerConverter(null), Integer.class); ConvertUtils.register(new LongConverter(null), Long.class); ConvertUtils.register(new ShortConverter(null), Short.class); } }
Class
2
public static int getStatusCode(HttpURLConnection conn) { try { return conn.getResponseCode(); } catch (IOException e) { throw ErrorUtil .createCommandException("connection to the remote repository host failed: " + e.getMessage()); } }
Base
1
public void testCallbackPost() throws URISyntaxException, IOException, java.text.ParseException { HttpExchange exchange = prepareExchange("http://localhost:8080/jolokia?callback=data", "Content-Type","text/plain; charset=UTF-8", "Origin",null ); // Simple GET method prepareMemoryPostReadRequest(exchange); Headers header = new Headers(); ByteArrayOutputStream out = prepareResponse(handler, exchange, header); handler.doHandle(exchange); assertEquals(header.getFirst("content-type"),"text/javascript; charset=utf-8"); String result = out.toString("utf-8"); assertTrue(result.endsWith("});")); assertTrue(result.startsWith("data({")); assertTrue(result.contains("\"used\"")); assertEquals(header.getFirst("Cache-Control"),"no-cache"); assertEquals(header.getFirst("Pragma"),"no-cache"); SimpleDateFormat rfc1123Format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US); rfc1123Format.setTimeZone(TimeZone.getTimeZone("GMT")); String expires = header.getFirst("Expires"); String date = header.getFirst("Date"); Date parsedExpires = rfc1123Format.parse(expires); Date parsedDate = rfc1123Format.parse(date); assertTrue(parsedExpires.before(parsedDate) || parsedExpires.equals(parsedDate)); Date now = new Date(); assertTrue(parsedExpires.before(now) || parsedExpires.equals(now)); }
Base
1
public boolean isCorsAccessAllowed(String pOrigin) { return cors; }
Compound
4
public void translate(AdventureSettingsPacket packet, GeyserSession session) { boolean isFlying = packet.getSettings().contains(AdventureSetting.FLYING); if (!isFlying && session.getGameMode() == GameMode.SPECTATOR) { // We should always be flying in spectator mode session.sendAdventureSettings(); return; } session.setFlying(isFlying); ClientPlayerAbilitiesPacket abilitiesPacket = new ClientPlayerAbilitiesPacket(isFlying); session.sendDownstreamPacket(abilitiesPacket); if (isFlying && session.getPlayerEntity().getMetadata().getFlags().getFlag(EntityFlag.SWIMMING)) { // Bedrock can fly and swim at the same time? Make sure that can't happen session.setSwimming(false); } }
Class
2
protected DataSource createDataSource() throws SQLException { InitialContext context = null; DataSource source = null; try { context = GeoTools.getInitialContext(); source = (DataSource) context.lookup(datasourceName); } catch (IllegalArgumentException | NoInitialContextException exception) { // Fall back on 'return null' below. } catch (NamingException exception) { registerInto = context; // Fall back on 'return null' below. } return source; }
Class
2
public void addShouldIncreaseAndRemoveShouldDecreaseTheSize() { final HttpHeadersBase headers = newEmptyHeaders(); assertThat(headers.size()).isEqualTo(0); headers.add("name1", "value1", "value2"); assertThat(headers.size()).isEqualTo(2); headers.add("name2", "value3", "value4"); assertThat(headers.size()).isEqualTo(4); headers.add("name3", "value5"); assertThat(headers.size()).isEqualTo(5); headers.remove("name3"); assertThat(headers.size()).isEqualTo(4); headers.remove("name1"); assertThat(headers.size()).isEqualTo(2); headers.remove("name2"); assertThat(headers.size()).isEqualTo(0); assertThat(headers.isEmpty()).isTrue(); }
Class
2
public Controller execute(FolderComponent folderComponent, UserRequest ureq, WindowControl wControl, Translator translator) { VFSContainer currentContainer = folderComponent.getCurrentContainer(); VFSContainer rootContainer = folderComponent.getRootContainer(); if (!VFSManager.exists(currentContainer)) { status = FolderCommandStatus.STATUS_FAILED; showError(translator.translate("FileDoesNotExist")); return null; } status = FolderCommandHelper.sanityCheck(wControl, folderComponent); if (status == FolderCommandStatus.STATUS_FAILED) { return null; } FileSelection selection = new FileSelection(ureq, folderComponent.getCurrentContainerPath()); status = FolderCommandHelper.sanityCheck3(wControl, folderComponent, selection); if (status == FolderCommandStatus.STATUS_FAILED) { return null; } boolean selectionWithContainer = false; List<String> filenames = selection.getFiles(); List<VFSLeaf> leafs = new ArrayList<>(); for (String file : filenames) { VFSItem item = currentContainer.resolve(file); if (item instanceof VFSContainer) { selectionWithContainer = true; } else if (item instanceof VFSLeaf) { leafs.add((VFSLeaf) item); } } if (selectionWithContainer) { if (leafs.isEmpty()) { wControl.setError(getTranslator().translate("send.mail.noFileSelected")); return null; } else { setFormWarning(getTranslator().translate("send.mail.selectionContainsFolder")); } } setFiles(rootContainer, leafs); return this; }
Base
1
public void setUp() throws Exception { context = oldcore.getXWikiContext(); Utils.setComponentManager(oldcore.getMocker()); QueryManager mockSecureQueryManager = oldcore.getMocker().registerMockComponent((Type) QueryManager.class, "secure"); mockTemplateProvidersQuery = mock(Query.class); when(mockSecureQueryManager.createQuery(any(), any())).thenReturn(mockTemplateProvidersQuery); when(mockTemplateProvidersQuery.execute()).thenReturn(Collections.emptyList()); when(oldcore.getMockContextualAuthorizationManager().hasAccess(any(Right.class), any(EntityReference.class))) .thenReturn(true); Provider<DocumentReference> mockDocumentReferenceProvider = oldcore.getMocker().registerMockComponent(DocumentReference.TYPE_PROVIDER); when(mockDocumentReferenceProvider.get()) .thenReturn(new DocumentReference("xwiki", Arrays.asList("Main"), "WebHome")); mockURLFactory = mock(XWikiURLFactory.class); context.setURLFactory(mockURLFactory); action = new CreateAction(); mockRequest = mock(XWikiRequest.class); context.setRequest(mockRequest); mockResponse = mock(XWikiResponse.class); context.setResponse(mockResponse); when(mockRequest.get("type")).thenReturn("plain"); this.oldcore.getMocker().registerMockComponent(ObservationManager.class); }
Class
2
private static ECPublicKey generateECPublicKey(final ECKey.Curve curve) throws Exception { final ECParameterSpec ecParameterSpec = curve.toECParameterSpec(); KeyPairGenerator generator = KeyPairGenerator.getInstance("EC"); generator.initialize(ecParameterSpec); KeyPair keyPair = generator.generateKeyPair(); return (ECPublicKey) keyPair.getPublic(); }
Base
1
public SAXReader(XMLReader xmlReader, boolean validating) { this.xmlReader = xmlReader; this.validating = validating; }
Base
1
public void translate(EmoteListPacket packet, GeyserSession session) { if (session.getConnector().getConfig().getEmoteOffhandWorkaround() == EmoteOffhandWorkaroundOption.NO_EMOTES) { return; } session.refreshEmotes(packet.getPieceIds()); }
Class
2
public EfficiencyStatement getUserEfficiencyStatementByResourceKey(Long resourceKey, Identity identity){ StringBuilder sb = new StringBuilder(256); sb.append("select statement from effstatementstandalone as statement") .append(" where statement.identity.key=:identityKey and statement.resourceKey=:resourceKey"); List<UserEfficiencyStatementStandalone> statement = dbInstance.getCurrentEntityManager() .createQuery(sb.toString(), UserEfficiencyStatementStandalone.class) .setParameter("identityKey", identity.getKey()) .setParameter("resourceKey", resourceKey) .getResultList(); if(statement.isEmpty() || statement.get(0).getStatementXml() == null) { return null; } return (EfficiencyStatement)xstream.fromXML(statement.get(0).getStatementXml()); }
Base
1
public void translate(ServerSpawnPositionPacket packet, GeyserSession session) { SetSpawnPositionPacket spawnPositionPacket = new SetSpawnPositionPacket(); spawnPositionPacket.setBlockPosition(Vector3i.from(packet.getPosition().getX(), packet.getPosition().getY(), packet.getPosition().getZ())); spawnPositionPacket.setSpawnForced(true); spawnPositionPacket.setDimensionId(DimensionUtils.javaToBedrock(session.getDimension())); spawnPositionPacket.setSpawnType(SetSpawnPositionPacket.Type.WORLD_SPAWN); session.sendUpstreamPacket(spawnPositionPacket); }
Class
2
public boolean check(String pArg) { if (patterns == null || patterns.size() == 0) { return true; } for (Pattern pattern : patterns) { if (pattern.matcher(pArg).matches()) { return true; } } return false; }
Compound
4
public int addWorkUnit(WorkUnit workUnit, long fileModificationTimeInMillis, long fileSize) { workUnitList.add(workUnit); if (fileModificationTimeInMillis < oldestFileModificationTime) { oldestFileModificationTime = fileModificationTimeInMillis; } if (fileModificationTimeInMillis > youngestFileModificationTime) { youngestFileModificationTime = fileModificationTimeInMillis; } totalFileSize += fileSize; return size(); }
Base
1
public void setHeadersShouldOnlyOverwriteHeaders() { final HttpHeadersBase headers1 = newEmptyHeaders(); headers1.add("name", "value"); headers1.add("name1", "value1"); final HttpHeadersBase headers2 = newEmptyHeaders(); headers2.add("name", "newvalue"); headers2.add("name2", "value2"); final HttpHeadersBase expected = newEmptyHeaders(); expected.add("name", "newvalue"); expected.add("name1", "value1"); expected.add("name2", "value2"); headers1.set(headers2); assertThat(expected).isEqualTo(headers1); }
Class
2
public void existingDocumentFromUITemplateProviderSpecifiedButOldSpaceTypeButOverridenFromUIToTerminal() 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); when(mockRequest.getParameter("tocreate")).thenReturn("terminal"); // Mock 1 existing template provider mockExistingTemplateProviders(templateProviderFullName, new DocumentReference("xwiki", Arrays.asList("XWiki"), "MyTemplateProvider"), Collections.EMPTY_LIST, null, "space"); // Run the action String result = action.render(context); // The tests are below this line! // Verify null is returned (this means the response has been returned) assertNull(result); // Note: We are creating X.Y as terminal, since it is overriden from the UI, regardless of any backwards // compatibility resolutions. Also using the template extracted from the template provider. verify(mockURLFactory).createURL("X", "Y", "edit", "template=XWiki.MyTemplate&parent=Main.WebHome&title=Y", null, "xwiki", context); }
Class
2
public void translate(CommandBlockUpdatePacket packet, GeyserSession session) { String command = packet.getCommand(); boolean outputTracked = packet.isOutputTracked(); if (packet.isBlock()) { CommandBlockMode mode; switch (packet.getMode()) { case CHAIN: // The green one mode = CommandBlockMode.SEQUENCE; break; case REPEATING: // The purple one mode = CommandBlockMode.AUTO; break; default: // NORMAL, the orange one mode = CommandBlockMode.REDSTONE; break; } boolean isConditional = packet.isConditional(); boolean automatic = !packet.isRedstoneMode(); // Automatic = Always Active option in Java ClientUpdateCommandBlockPacket commandBlockPacket = new ClientUpdateCommandBlockPacket( new Position(packet.getBlockPosition().getX(), packet.getBlockPosition().getY(), packet.getBlockPosition().getZ()), command, mode, outputTracked, isConditional, automatic); session.sendDownstreamPacket(commandBlockPacket); } else { ClientUpdateCommandBlockMinecartPacket commandMinecartPacket = new ClientUpdateCommandBlockMinecartPacket( (int) session.getEntityCache().getEntityByGeyserId(packet.getMinecartRuntimeEntityId()).getEntityId(), command, outputTracked ); session.sendDownstreamPacket(commandMinecartPacket); } }
Class
2
public static Map<String, String> genHeaderMapByRequest(HttpServletRequest request) { Map<String, String> map = new HashMap<>(); AdminTokenVO adminTokenVO = AdminTokenThreadLocal.getUser(); if (adminTokenVO != null) { User user = User.dao.findById(adminTokenVO.getUserId()); map.put("LoginUserName", user.get("userName").toString()); map.put("LoginUserId", adminTokenVO.getUserId() + ""); } map.put("IsLogin", (adminTokenVO != null) + ""); map.put("Current-Locale", I18nUtil.getCurrentLocale()); map.put("Blog-Version", ((Map) JFinal.me().getServletContext().getAttribute("zrlog")).get("version").toString()); if (request != null) { String fullUrl = ZrLogUtil.getFullUrl(request); if (request.getQueryString() != null) { fullUrl = fullUrl + "?" + request.getQueryString(); } if (adminTokenVO != null) { fullUrl = adminTokenVO.getProtocol() + ":" + fullUrl; } map.put("Cookie", request.getHeader("Cookie")); map.put("AccessUrl", "http://127.0.0.1:" + request.getServerPort() + request.getContextPath()); if (request.getHeader("Content-Type") != null) { map.put("Content-Type", request.getHeader("Content-Type")); } map.put("Full-Url", fullUrl); } return map; }
Class
2
public static SecretKey decryptCEK(final SecretKey kek, final byte[] iv, final AuthenticatedCipherText authEncrCEK, final int keyLength, final Provider provider) throws JOSEException { byte[] keyBytes = AESGCM.decrypt(kek, iv, authEncrCEK.getCipherText(), new byte[0], authEncrCEK.getAuthenticationTag(), provider); if (ByteUtils.bitLength(keyBytes) != keyLength) { throw new KeyLengthException("CEK key length mismatch: " + ByteUtils.bitLength(keyBytes) + " != " + keyLength); } return new SecretKeySpec(keyBytes, "AES"); }
Class
2
public OHttpSession getSession(final String iId) { acquireSharedLock(); try { final OHttpSession sess = sessions.get(iId); if (sess != null) sess.updateLastUpdatedOn(); return sess; } finally { releaseSharedLock(); } }
Class
2
public Document read(String systemId) throws DocumentException { InputSource source = new InputSource(systemId); if (this.encoding != null) { source.setEncoding(this.encoding); } return read(source); }
Base
1
public void translate(ServerBlockChangePacket packet, GeyserSession session) { Position pos = packet.getRecord().getPosition(); boolean updatePlacement = session.getConnector().getPlatformType() != PlatformType.SPIGOT && // Spigot simply listens for the block place event session.getConnector().getWorldManager().getBlockAt(session, pos) != packet.getRecord().getBlock(); ChunkUtils.updateBlock(session, packet.getRecord().getBlock(), pos); if (updatePlacement) { this.checkPlace(session, packet); } this.checkInteract(session, packet); }
Class
2
public void doFilter(ServletRequest srequest, ServletResponse response, FilterChain filterChain) throws IOException, ServletException { /* HttpServletRequest request = (HttpServletRequest) srequest; //final String realIp = request.getHeader(X_FORWARDED_FOR); //if (realIp != null) { filterChain.doFilter(new XssHttpServletRequestWrapper(request) { *//** public String getRemoteAddr() { return realIp; } public String getRemoteHost() { return realIp; } **//* }, response); return; //} */ }
Base
1
protected List<String> getRawCommandLine( String executable, String[] arguments ) { List<String> commandLine = new ArrayList<String>(); StringBuilder sb = new StringBuilder(); if ( executable != null ) { String preamble = getExecutionPreamble(); if ( preamble != null ) { sb.append( preamble ); } if ( isQuotedExecutableEnabled() ) { char[] escapeChars = getEscapeChars( isSingleQuotedExecutableEscaped(), isDoubleQuotedExecutableEscaped() ); sb.append( StringUtils.quoteAndEscape( getExecutable(), getExecutableQuoteDelimiter(), escapeChars, getQuotingTriggerChars(), '\\', false ) ); } else { sb.append( getExecutable() ); } } for ( int i = 0; i < arguments.length; i++ ) { if ( sb.length() > 0 ) { sb.append( " " ); } if ( isQuotedArgumentsEnabled() ) { char[] escapeChars = getEscapeChars( isSingleQuotedArgumentEscaped(), isDoubleQuotedArgumentEscaped() ); sb.append( StringUtils.quoteAndEscape( arguments[i], getArgumentQuoteDelimiter(), escapeChars, getQuotingTriggerChars(), getArgumentEscapePattern(), false ) ); } else { sb.append( arguments[i] ); } } commandLine.add( sb.toString() ); return commandLine; }
Base
1
public HtmlElement content(String body) { return content(new TextElement(body)); }
Base
1
void hexadecimal() { assertThat(PathAndQuery.parse("/%")).isNull(); assertThat(PathAndQuery.parse("/%0")).isNull(); assertThat(PathAndQuery.parse("/%0X")).isNull(); assertThat(PathAndQuery.parse("/%X0")).isNull(); }
Base
1
public void existingDocumentFromUITemplateProviderSpecifiedRestrictionExists() throws Exception { // current document = xwiki:Main.WebHome DocumentReference documentReference = new DocumentReference("xwiki", Arrays.asList("Main"), "WebHome"); XWikiDocument document = mock(XWikiDocument.class); when(document.getDocumentReference()).thenReturn(documentReference); when(document.isNew()).thenReturn(false); when(document.getLocalReferenceMaxLength()).thenReturn(255); context.setDoc(document); // Submit from the UI spaceReference=X&name=Y&templateProvider=XWiki.MyTemplateProvider String templateProviderFullName = "XWiki.MyTemplateProvider"; String spaceReferenceString = "X"; when(mockRequest.getParameter("spaceReference")).thenReturn(spaceReferenceString); when(mockRequest.getParameter("name")).thenReturn("Y"); when(mockRequest.getParameter("templateprovider")).thenReturn(templateProviderFullName); // Mock 1 existing template provider that allows usage in target space. mockExistingTemplateProviders(templateProviderFullName, new DocumentReference("xwiki", Arrays.asList("XWiki"), "MyTemplateProvider"), Arrays.asList("X")); // Run the action String result = action.render(context); // The tests are below this line! // Verify null is returned (this means the response has been returned) assertNull(result); // Note1: We are allowed to create anything under space X, be it a terminal or a non-terminal document. // Note2: 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 void testByteSerialization() throws Exception { final IBaseDataObject d = DataObjectFactory.getInstance("abc".getBytes(), "testfile", Form.UNKNOWN); final byte[] bytes = PayloadUtil.serializeToBytes(d); final String s1 = new String(bytes); assertTrue("Serializedion must include data from payload", s1.indexOf("abc") > -1); }
Base
1
private void checkUserReference(UserReference userReference) throws ResetPasswordException { if (!this.userManager.exists(userReference)) { String exceptionMessage = this.localizationManager.getTranslationPlain("xe.admin.passwordReset.error.noUser", userReference.toString()); throw new ResetPasswordException(exceptionMessage); } // FIXME: This check shouldn't be needed if we'd have the proper API to determine which kind of // authentication is used. if (!(userReference instanceof DocumentUserReference)) { throw new ResetPasswordException("Only user having a page on the wiki can reset their password."); } }
Base
1
public void iteratorSetShouldFail() { final HttpHeadersBase headers = newEmptyHeaders(); headers.add("name1", "value1", "value2", "value3"); headers.add("name2", "value4"); assertThat(headers.size()).isEqualTo(4); assertThatThrownBy(() -> headers.iterator().next().setValue("")) .isInstanceOf(UnsupportedOperationException.class); }
Class
2
public void handle(String target, HttpServletRequest request, HttpServletResponse response, boolean[] isHandled) { //便于Wappalyzer读取 response.addHeader("X-ZrLog", BlogBuildInfoUtil.getVersion()); boolean isPluginPath = false; for (String path : pluginHandlerPaths) { if (target.startsWith(path)) { isPluginPath = true; } } if (isPluginPath) { try { Map.Entry<AdminTokenVO, User> entry = adminTokenService.getAdminTokenVOUserEntry(request); if (entry != null) { adminTokenService.setAdminToken(entry.getValue(), entry.getKey().getSessionId(), entry.getKey().getProtocol(), request, response); } if (target.startsWith("/admin/plugins/")) { try { adminPermission(target, request, response); } catch (IOException | InstantiationException e) { LOGGER.error(e); } } else if (target.startsWith("/plugin/") || target.startsWith("/p/")) { try { visitorPermission(target, request, response); } catch (IOException | InstantiationException e) { LOGGER.error(e); } } } finally { isHandled[0] = true; } } else { this.next.handle(target, request, response, isHandled); } }
Class
2
public void testSetContentFromFile() throws Exception { TestHttpData test = new TestHttpData("test", UTF_8, 0); try { File tmpFile = File.createTempFile(UUID.randomUUID().toString(), ".tmp"); tmpFile.deleteOnExit(); FileOutputStream fos = new FileOutputStream(tmpFile); byte[] bytes = new byte[4096]; PlatformDependent.threadLocalRandom().nextBytes(bytes); try { fos.write(bytes); fos.flush(); } finally { fos.close(); } test.setContent(tmpFile); ByteBuf buf = test.getByteBuf(); assertEquals(buf.readerIndex(), 0); assertEquals(buf.writerIndex(), bytes.length); assertArrayEquals(bytes, test.get()); assertArrayEquals(bytes, ByteBufUtil.getBytes(buf)); } finally { //release the ByteBuf test.delete(); } }
Base
1
public OutputStream getOutputStream(boolean append) { return null; }
Base
1
public void shouldCloneFromRemoteRepo() { assertThat(clientRepo.listFiles().length > 0, is(true)); }
Class
2
protected int addFileNames(List<String> list) { // This appears to only be used by unit tests and the copy // constructor for (String file : list) { workUnitList.add(new WorkUnit(file)); } return size(); }
Base
1