code
stringlengths
12
2.05k
label_name
stringclasses
5 values
label
int64
0
4
public void existingDocumentFromUITemplateProviderSpecifiedRestrictionExistsOnParentSpace() throws Exception { // current document = xwiki:Main.WebHome DocumentReference documentReference = new DocumentReference("xwiki", Arrays.asList("Main"), "WebHome"); XWikiDocument document = mock(XWikiDocument.class); when(document.getDocumentReference()).thenReturn(documentReference); when(document.isNew()).thenReturn(false); when(document.getLocalReferenceMaxLength()).thenReturn(255); context.setDoc(document); // Submit from the UI spaceReference=X.Y.Z&name=W&templateProvider=XWiki.MyTemplateProvider String templateProviderFullName = "XWiki.MyTemplateProvider"; String spaceReferenceString = "X.Y.Z"; when(mockRequest.getParameter("spaceReference")).thenReturn(spaceReferenceString); when(mockRequest.getParameter("name")).thenReturn("W"); when(mockRequest.getParameter("templateprovider")).thenReturn(templateProviderFullName); // Mock 1 existing template provider that allows usage in one of the target space's parents (top level in this // case). 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 or its children, be it a terminal or a non-terminal // document // Note2: We are creating X.Y.Z.W and using the template extracted from the template provider. verify(mockURLFactory).createURL("X.Y.Z.W", "WebHome", "edit", "template=XWiki.MyTemplate&parent=Main.WebHome&title=W", null, "xwiki", context); }
Class
2
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(false); if (session == null) { AccessControlContext acc = AccessController.getContext(); Subject subject = Subject.getSubject(acc); if (subject == null) { Helpers.doForbidden(response); return; } session = request.getSession(true); session.setAttribute("subject", subject); } else { Subject subject = (Subject) session.getAttribute("subject"); if (subject == null) { session.invalidate(); Helpers.doForbidden(response); return; } } String encoding = request.getHeader("Accept-Encoding"); boolean supportsGzip = (encoding != null && encoding.toLowerCase().indexOf("gzip") > -1); SessionTerminal st = (SessionTerminal) session.getAttribute("terminal"); if (st == null || st.isClosed()) { st = new SessionTerminal(getCommandProcessor(), getThreadIO()); session.setAttribute("terminal", st); } String str = request.getParameter("k"); String f = request.getParameter("f"); String dump = st.handle(str, f != null && f.length() > 0); if (dump != null) { if (supportsGzip) { response.setHeader("Content-Encoding", "gzip"); response.setHeader("Content-Type", "text/html"); try { GZIPOutputStream gzos = new GZIPOutputStream(response.getOutputStream()); gzos.write(dump.getBytes()); gzos.close(); } catch (IOException ie) { LOG.info("Exception writing response: ", ie); } } else { response.getOutputStream().write(dump.getBytes()); } } }
Compound
4
private static boolean pathContainsDoubleDots(Bytes path) { final int length = path.length; byte b0 = 0; byte b1 = 0; byte b2 = '/'; for (int i = 1; i < length; i++) { final byte b3 = path.data[i]; if (b3 == '/' && b2 == '.' && b1 == '.' && b0 == '/') { return true; } b0 = b1; b1 = b2; b2 = b3; } return b0 == '/' && b1 == '.' && b2 == '.'; }
Base
1
public void iterateEmptyHeadersShouldThrow() { final Iterator<Map.Entry<AsciiString, String>> iterator = newEmptyHeaders().iterator(); assertThat(iterator.hasNext()).isFalse(); iterator.next(); }
Class
2
public static final Binder fromPath(Path path) throws IOException { try(InputStream inStream = Files.newInputStream(path)) { return (Binder)myStream.fromXML(inStream); } catch (Exception e) { log.error("Cannot import this map: " + path, e); return null; } }
Base
1
private void populateAuthCacheInAllPeers(AuthorizationContext authContext) throws Throwable { // send a GET request to the ExampleService factory to populate auth cache on each peer. // since factory is not OWNER_SELECTION service, request goes to the specified node. for (VerificationHost peer : this.host.getInProcessHostMap().values()) { peer.setAuthorizationContext(authContext); // based on the role created in test, all users have access to ExampleService this.host.sendAndWaitExpectSuccess( Operation.createGet(UriUtils.buildStatsUri(peer, ExampleService.FACTORY_LINK))); } this.host.waitFor("Timeout waiting for correct auth cache state", () -> checkCacheInAllPeers(authContext.getToken(), true)); }
Class
2
public void testWrapMemoryMapped() throws Exception { File file = File.createTempFile("netty-test", "tmp"); FileChannel output = null; FileChannel input = null; ByteBuf b1 = null; ByteBuf b2 = null; try { output = new RandomAccessFile(file, "rw").getChannel(); byte[] bytes = new byte[1024]; PlatformDependent.threadLocalRandom().nextBytes(bytes); output.write(ByteBuffer.wrap(bytes)); input = new RandomAccessFile(file, "r").getChannel(); ByteBuffer m = input.map(FileChannel.MapMode.READ_ONLY, 0, input.size()); b1 = buffer(m); ByteBuffer dup = m.duplicate(); dup.position(2); dup.limit(4); b2 = buffer(dup); Assert.assertEquals(b2, b1.slice(2, 2)); } finally { if (b1 != null) { b1.release(); } if (b2 != null) { b2.release(); } if (output != null) { output.close(); } if (input != null) { input.close(); } file.delete(); } }
Base
1
private File tempFile() throws IOException { String newpostfix; String diskFilename = getDiskFilename(); if (diskFilename != null) { newpostfix = '_' + diskFilename; } else { newpostfix = getPostfix(); } File tmpFile; if (getBaseDirectory() == null) { // create a temporary file tmpFile = File.createTempFile(getPrefix(), newpostfix); } else { tmpFile = File.createTempFile(getPrefix(), newpostfix, new File( getBaseDirectory())); } if (deleteOnExit()) { // See https://github.com/netty/netty/issues/10351 DeleteFileOnExitHook.add(tmpFile.getPath()); } return tmpFile; }
Base
1
public void iteratorShouldReturnAllNameValuePairs() { final HttpHeadersBase headers1 = newEmptyHeaders(); headers1.add("name1", "value1", "value2"); headers1.add("name2", "value3"); headers1.add("name3", "value4", "value5", "value6"); headers1.add("name1", "value7", "value8"); assertThat(headers1.size()).isEqualTo(8); final HttpHeadersBase headers2 = newEmptyHeaders(); for (Map.Entry<AsciiString, String> entry : headers1) { headers2.add(entry.getKey(), entry.getValue()); } assertThat(headers2).isEqualTo(headers1); }
Class
2
public void testRejectECJWKWithUnsupportedCurve() throws Exception { KeyPair keyPair = createUnsupportedECKeyPair(); ECPublicKey ecPublicKey = (ECPublicKey)keyPair.getPublic(); ECPrivateKey ecPrivateKey = (ECPrivateKey)keyPair.getPrivate(); ECKey ecJWK = new ECKey.Builder(new ECKey.Curve("P-224"), ecPublicKey).privateKey(ecPrivateKey).build(); try { new ECDHEncrypter(ecJWK); fail(); } catch (JOSEException e) { // ok } try { new ECDHDecrypter(ecJWK); fail(); } catch (JOSEException e) { // ok } }
Base
1
protected StyleSignatureBasic getStyleSignature() { return StyleSignatureBasic.of(SName.root, SName.element, SName.timingDiagram, SName.binary); }
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
private String getTitleQTI12(QuestionItemImpl item) { try { VFSLeaf leaf = qpoolService.getRootLeaf(item); Item xmlItem = QTIEditHelper.readItemXml(leaf); return xmlItem.getTitle(); } catch (NullPointerException e) { log.warn("Cannot read files from dir: " + item.getDirectory()); } return null; }
Base
1
public PlayerBinary(String code, ISkinParam skinParam, TimingRuler ruler, boolean compact) { super(code, skinParam, ruler, compact); this.style = getStyleSignature().getMergedStyle(skinParam.getCurrentStyleBuilder()); this.suggestedHeight = 30; }
Base
1
DefaultResetPasswordRequestResponse(UserReference reference, InternetAddress userEmail, String verificationCode) { this.userReference = reference; this.userEmail = userEmail; this.verificationCode = verificationCode; }
Base
1
public Map<String, FileEntry> generatorCode(TableDetails tableDetails, String tablePrefix, Map<String, String> customProperties, List<TemplateFile> templateFiles) { Map<String, FileEntry> map = new HashMap<>(templateFiles.size()); // 模板渲染 Map<String, Object> context = GenUtils.getContext(tableDetails, tablePrefix, customProperties); for (TemplateFile templateFile : templateFiles) { FileEntry fileEntry = new FileEntry(); fileEntry.setType(templateFile.getType()); // 替换路径中的占位符 String filename = StrUtil.format(templateFile.getFilename(), context); fileEntry.setFilename(filename); String parentFilePath = GenUtils.evaluateRealPath(templateFile.getParentFilePath(), context); fileEntry.setParentFilePath(parentFilePath); // 如果是文件 if (TemplateEntryTypeEnum.FILE.getType().equals(fileEntry.getType())) { fileEntry.setFilePath(GenUtils.concatFilePath(parentFilePath, filename)); // 文件内容渲染 TemplateEngineTypeEnum engineTypeEnum = TemplateEngineTypeEnum.of(templateFile.getEngineType()); String content = templateEngineDelegator.render(engineTypeEnum, templateFile.getContent(), context); fileEntry.setContent(content); } else { String currentPath = GenUtils.evaluateRealPath(templateFile.getFilename(), context); fileEntry.setFilePath(GenUtils.concatFilePath(parentFilePath, currentPath)); } map.put(fileEntry.getFilePath(), fileEntry); } return map; }
Class
2
void validSaveNewTranslation() throws Exception { when(mockForm.getLanguage()).thenReturn("fr"); when(mockClonedDocument.getTranslatedDocument("fr", this.context)).thenReturn(mockClonedDocument); when(mockClonedDocument.getDocumentReference()).thenReturn(new DocumentReference("xwiki", "My", "Page")); when(mockClonedDocument.getStore()).thenReturn(this.oldcore.getMockStore()); when(xWiki.getStore()).thenReturn(this.oldcore.getMockStore()); context.put("ajax", true); when(xWiki.isMultiLingual(this.context)).thenReturn(true); when(mockRequest.getParameter("previousVersion")).thenReturn("1.1"); when(mockRequest.getParameter("isNew")).thenReturn("true"); assertFalse(saveAction.save(this.context)); assertEquals(new Version("1.1"), this.context.get("SaveAction.savedObjectVersion")); verify(this.xWiki).checkSavingDocument(eq(USER_REFERENCE), any(XWikiDocument.class), eq(""), eq(false), eq(this.context)); verify(this.xWiki).saveDocument(any(XWikiDocument.class), eq(""), eq(false), eq(this.context)); }
Class
2
public boolean loginValidate(String userName, String password) { String sql = "select * from admin_table where admin_name=? and password=?"; try { ps=DbUtil.getConnection().prepareStatement(sql); ps.setString(1, userName); ps.setString(2,password); ResultSet rs =ps.executeQuery(); if (rs.next()) { return true; } } catch (SQLException | ClassNotFoundException e) { e.printStackTrace(); } return false; }
Variant
0
protected String getCorsDomain(String referer, String userAgent) { String dom = null; if (referer != null && referer.toLowerCase() .matches("https?://([a-z0-9,-]+[.])*draw[.]io/.*")) { dom = referer.toLowerCase().substring(0, referer.indexOf(".draw.io/") + 8); } else if (referer != null && referer.toLowerCase() .matches("https?://([a-z0-9,-]+[.])*diagrams[.]net/.*")) { dom = referer.toLowerCase().substring(0, referer.indexOf(".diagrams.net/") + 13); } else if (referer != null && referer.toLowerCase() .matches("https?://([a-z0-9,-]+[.])*quipelements[.]com/.*")) { dom = referer.toLowerCase().substring(0, referer.indexOf(".quipelements.com/") + 17); } // Enables Confluence/Jira proxy via referer or hardcoded user-agent (for old versions) // UA refers to old FF on macOS so low risk and fixes requests from existing servers else if ((referer != null && referer.equals("draw.io Proxy Confluence Server")) || (userAgent != null && userAgent.equals( "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.12; rv:50.0) Gecko/20100101 Firefox/50.0"))) { dom = ""; } return dom; }
Base
1
public void testSetNullHeaderValue() { final HttpHeadersBase headers = newEmptyHeaders(); headers.set("test", (String) null); }
Class
2
public static AlgorithmMode resolveAlgorithmMode(final JWEAlgorithm alg) throws JOSEException { if (alg.equals(JWEAlgorithm.ECDH_ES)) { return AlgorithmMode.DIRECT; } else if (alg.equals(JWEAlgorithm.ECDH_ES_A128KW) || alg.equals(JWEAlgorithm.ECDH_ES_A192KW) || alg.equals(JWEAlgorithm.ECDH_ES_A256KW)) { return AlgorithmMode.KW; } else { throw new JOSEException(AlgorithmSupportMessage.unsupportedJWEAlgorithm( alg, ECDHCryptoProvider.SUPPORTED_ALGORITHMS)); } }
Base
1
public void install( String displayName, String description, String[] dependencies, String account, String password, String config) throws URISyntaxException { String javaHome = System.getProperty("java.home"); String javaBinary = javaHome + "\\bin\\java.exe"; File jar = new File(WindowsService.class.getProtectionDomain().getCodeSource().getLocation().toURI()); String command = javaBinary + " -Duser.dir=\"" + jar.getParentFile().getAbsolutePath() + "\"" + " -jar \"" + jar.getAbsolutePath() + "\"" + " --service \"" + config + "\""; StringBuilder dep = new StringBuilder(); if (dependencies != null) { for (String s : dependencies) { dep.append(s); dep.append("\0"); } } dep.append("\0"); SERVICE_DESCRIPTION desc = new SERVICE_DESCRIPTION(); desc.lpDescription = description; SC_HANDLE serviceManager = openServiceControlManager(null, Winsvc.SC_MANAGER_ALL_ACCESS); if (serviceManager != null) { SC_HANDLE service = ADVAPI_32.CreateService(serviceManager, serviceName, displayName, Winsvc.SERVICE_ALL_ACCESS, WinNT.SERVICE_WIN32_OWN_PROCESS, WinNT.SERVICE_AUTO_START, WinNT.SERVICE_ERROR_NORMAL, command, null, null, dep.toString(), account, password); if (service != null) { ADVAPI_32.ChangeServiceConfig2(service, Winsvc.SERVICE_CONFIG_DESCRIPTION, desc); ADVAPI_32.CloseServiceHandle(service); } ADVAPI_32.CloseServiceHandle(serviceManager); } }
Base
1
public RechnungCostEditTablePanel(final String id) { super(id); feedbackPanel = new FeedbackPanel("feedback"); ajaxComponents.register(feedbackPanel); add(feedbackPanel); this.form = new Form<AbstractRechnungsPositionDO>("form"); add(form); rows = new RepeatingView("rows"); form.add(rows); }
Compound
4
public boolean isValid(Integer value, ConstraintValidatorContext context) { if (proxyManager.get(value) != null) { return true; } String errorMessage = String.format("No proxy server found for specified port %d", value); LOG.warn(errorMessage); context.buildConstraintViolationWithTemplate(errorMessage).addPropertyNode(PARAM_NAME).addConstraintViolation(); return false; }
Class
2
public void translate(MapInfoRequestPacket packet, GeyserSession session) { long mapId = packet.getUniqueMapId(); ClientboundMapItemDataPacket mapPacket = session.getStoredMaps().remove(mapId); if (mapPacket != null) { // Delay the packet 100ms to prevent the client from ignoring the packet GeyserConnector.getInstance().getGeneralThreadPool().schedule(() -> session.sendUpstreamPacket(mapPacket), 100, TimeUnit.MILLISECONDS); } }
Class
2
void relative() { assertThat(PathAndQuery.parse("foo")).isNull(); }
Base
1
protected SAXContentHandler createContentHandler(XMLReader reader) { return new SAXContentHandler(getDocumentFactory(), dispatchHandler); }
Base
1
public void testSetSelfIsNoOp() { final HttpHeadersBase headers = newEmptyHeaders(); headers.add("name", "value"); headers.set(headers); assertThat(headers.size()).isEqualTo(1); }
Class
2
public void testGetBytesAndSetBytesWithFileChannel() throws IOException { File file = File.createTempFile("file-channel", ".tmp"); RandomAccessFile randomAccessFile = null; try { randomAccessFile = new RandomAccessFile(file, "rw"); FileChannel channel = randomAccessFile.getChannel(); // channelPosition should never be changed long channelPosition = channel.position(); byte[] bytes = {'a', 'b', 'c', 'd'}; int len = bytes.length; ByteBuf buffer = newBuffer(len); buffer.resetReaderIndex(); buffer.resetWriterIndex(); buffer.writeBytes(bytes); int oldReaderIndex = buffer.readerIndex(); assertEquals(len, buffer.getBytes(oldReaderIndex, channel, 10, len)); assertEquals(oldReaderIndex, buffer.readerIndex()); assertEquals(channelPosition, channel.position()); ByteBuf buffer2 = newBuffer(len); buffer2.resetReaderIndex(); buffer2.resetWriterIndex(); int oldWriterIndex = buffer2.writerIndex(); assertEquals(buffer2.setBytes(oldWriterIndex, channel, 10, len), len); assertEquals(channelPosition, channel.position()); assertEquals(oldWriterIndex, buffer2.writerIndex()); assertEquals('a', buffer2.getByte(oldWriterIndex)); assertEquals('b', buffer2.getByte(oldWriterIndex + 1)); assertEquals('c', buffer2.getByte(oldWriterIndex + 2)); assertEquals('d', buffer2.getByte(oldWriterIndex + 3)); buffer.release(); buffer2.release(); } finally { if (randomAccessFile != null) { randomAccessFile.close(); } file.delete(); } }
Base
1
protected void traceLdapEnv(Properties env) { if (trace) { Properties tmp = new Properties(); tmp.putAll(env); String credentials = tmp.getProperty(Context.SECURITY_CREDENTIALS); String bindCredential = tmp.getProperty(BIND_CREDENTIAL); if (credentials != null && credentials.length() > 0) tmp.setProperty(Context.SECURITY_CREDENTIALS, "***"); if (bindCredential != null && bindCredential.length() > 0) tmp.setProperty(BIND_CREDENTIAL, "***"); log.trace("Logging into LDAP server, env=" + tmp.toString()); } }
Class
2
private void initAndSaveDocument(XWikiContext context, XWikiDocument newDocument, String title, String template, String parent) throws XWikiException { XWiki xwiki = context.getWiki(); // Set the locale and default locale, considering that we're creating the original version of the document // (not a translation). newDocument.setLocale(Locale.ROOT); if (newDocument.getDefaultLocale() == Locale.ROOT) { newDocument.setDefaultLocale(xwiki.getLocalePreference(context)); } // Copy the template. readFromTemplate(newDocument, template, context); // Set the parent field. if (!StringUtils.isEmpty(parent)) { DocumentReference parentReference = this.currentmixedReferenceResolver.resolve(parent); newDocument.setParentReference(parentReference); } // Set the document title if (title != null) { newDocument.setTitle(title); } // Set the author and creator. DocumentReference currentUserReference = context.getUserReference(); newDocument.setAuthorReference(currentUserReference); newDocument.setCreatorReference(currentUserReference); // Make sure the user is allowed to make this modification xwiki.checkSavingDocument(currentUserReference, newDocument, context); xwiki.saveDocument(newDocument, context); }
Class
2
public void setSetContentFromFileExceptionally() throws Exception { final long maxSize = 4; DiskFileUpload f1 = new DiskFileUpload("file5", "file5", "application/json", null, null, 0); f1.setMaxSize(maxSize); try { f1.setContent(Unpooled.wrappedBuffer(new byte[(int) maxSize])); File originalFile = f1.getFile(); assertNotNull(originalFile); assertEquals(maxSize, originalFile.length()); assertEquals(maxSize, f1.length()); byte[] bytes = new byte[8]; PlatformDependent.threadLocalRandom().nextBytes(bytes); File tmpFile = File.createTempFile(UUID.randomUUID().toString(), ".tmp"); tmpFile.deleteOnExit(); FileOutputStream fos = new FileOutputStream(tmpFile); try { fos.write(bytes); fos.flush(); } finally { fos.close(); } try { f1.setContent(tmpFile); fail("should not reach here!"); } catch (IOException e) { assertNotNull(f1.getFile()); assertEquals(originalFile, f1.getFile()); assertEquals(maxSize, f1.length()); } } finally { f1.delete(); } }
Base
1
private CallbackHandler getCallbackHandler( @UnderInitialization(WrappedFactory.class) LibPQFactory this, Properties info) throws PSQLException { // Determine the callback handler CallbackHandler cbh; String sslpasswordcallback = PGProperty.SSL_PASSWORD_CALLBACK.get(info); if (sslpasswordcallback != null) { try { cbh = (CallbackHandler) ObjectFactory.instantiate(sslpasswordcallback, info, false, null); } catch (Exception e) { throw new PSQLException( GT.tr("The password callback class provided {0} could not be instantiated.", sslpasswordcallback), PSQLState.CONNECTION_FAILURE, e); } } else { cbh = new ConsoleCallbackHandler(PGProperty.SSL_PASSWORD.get(info)); } return cbh; }
Class
2
public static boolean isAbsolute(String url) { if (url.startsWith("//")) // //www.domain.com/start { return true; } if (url.startsWith("/")) // /somePage.html { return false; } boolean result = false; try { URI uri = new URI(url); result = uri.isAbsolute(); } catch (URISyntaxException e) {} //Ignore return result; }
Base
1
protected void runTeardown() { Assert.assertTrue("HTTP connection is not allowed", messagedAccessDenied); }
Class
2
public void setXMLReader(XMLReader reader) { this.xmlReader = reader; }
Base
1
public String findFilter( String url_suffix ) { if( url_suffix == null ) { throw new IllegalArgumentException( "The url_suffix must not be null." ); } CaptureType type = em.find( CaptureType.class, url_suffix ); if( type != null ) { return type.getCaptureFilter(); } return null; }
Class
2
default boolean contains(String name) { return get(name, Object.class).isPresent(); }
Class
2
public int getPosition() { if ( realPos == -1 ) { realPos = ( getExecutable() == null ? 0 : 1 ); for ( int i = 0; i < position; i++ ) { Arg arg = (Arg) arguments.elementAt( i ); realPos += arg.getParts().length; } } return realPos; }
Base
1
private String tryRewrite(String s) throws IOException, InvalidKeyException { if (s.length()<24) return s; // Encrypting "" in Secret produces 24-letter characters, so this must be the minimum length if (!isBase64(s)) return s; // decode throws IOException if the input is not base64, and this is also a very quick way to filter byte[] in; try { in = Base64.decode(s.toCharArray()); } catch (IOException e) { return s; // not a valid base64 } cipher.init(Cipher.DECRYPT_MODE, key); Secret sec = Secret.tryDecrypt(cipher, in); if(sec!=null) // matched return sec.getEncryptedValue(); // replace by the new encrypted value else // not encrypted with the legacy key. leave it unmodified return s; }
Class
2
public void translate(ServerEntityAttachPacket packet, GeyserSession session) { Entity holderId; if (packet.getEntityId() == session.getPlayerEntity().getEntityId()) { holderId = session.getPlayerEntity(); } else { holderId = session.getEntityCache().getEntityByJavaId(packet.getEntityId()); if (holderId == null) { return; } } Entity attachedToId; if (packet.getAttachedToId() == session.getPlayerEntity().getEntityId()) { attachedToId = session.getPlayerEntity(); } else { attachedToId = session.getEntityCache().getEntityByJavaId(packet.getAttachedToId()); if ((attachedToId == null || packet.getAttachedToId() == 0)) { // Is not being leashed holderId.getMetadata().getFlags().setFlag(EntityFlag.LEASHED, false); holderId.getMetadata().put(EntityData.LEASH_HOLDER_EID, -1L); holderId.updateBedrockMetadata(session); EntityEventPacket eventPacket = new EntityEventPacket(); eventPacket.setRuntimeEntityId(holderId.getGeyserId()); eventPacket.setType(EntityEventType.REMOVE_LEASH); eventPacket.setData(0); session.sendUpstreamPacket(eventPacket); return; } } holderId.getMetadata().getFlags().setFlag(EntityFlag.LEASHED, true); holderId.getMetadata().put(EntityData.LEASH_HOLDER_EID, attachedToId.getGeyserId()); holderId.updateBedrockMetadata(session); }
Class
2
protected TestPolicy(Policy.ParseContext parseContext) throws PolicyException { super(parseContext); }
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 static ResourceEvaluation evaluate(File file, String filename) { ResourceEvaluation eval = new ResourceEvaluation(); try { ImsManifestFileFilter visitor = new ImsManifestFileFilter(); Path fPath = PathUtils.visit(file, filename, visitor); if(visitor.hasManifest()) { Path realManifestPath = visitor.getManifestPath(); Path manifestPath = fPath.resolve(realManifestPath); RootSearcher rootSearcher = new RootSearcher(); Files.walkFileTree(fPath, rootSearcher); if(rootSearcher.foundRoot()) { manifestPath = rootSearcher.getRoot().resolve(IMS_MANIFEST); } else { manifestPath = fPath.resolve(IMS_MANIFEST); } Document doc = IMSLoader.loadIMSDocument(manifestPath); if(validateImsManifest(doc)) { if(visitor.hasEditorTreeModel()) { XMLScanner scanner = new XMLScanner(); scanner.scan(visitor.getEditorTreeModelPath()); eval.setValid(!scanner.hasEditorTreeModelMarkup()); } else { eval.setValid(true); } } else { eval.setValid(false); } } else { eval.setValid(false); } PathUtils.closeSubsequentFS(fPath); } catch (IOException | IllegalArgumentException e) { log.error("", e); eval.setValid(false); } return eval; }
Base
1
private byte[] decodeAndInflate(String encodedRequest) throws SAMLException { byte[] bytes = Base64.getMimeDecoder().decode(encodedRequest); Inflater inflater = new Inflater(true); inflater.setInput(bytes); inflater.finished(); try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] result = new byte[bytes.length]; while (!inflater.finished()) { int length = inflater.inflate(result); if (length > 0) { baos.write(result, 0, length); } } return baos.toByteArray(); } catch (DataFormatException e) { throw new SAMLException("Invalid AuthnRequest. Inflating the bytes failed.", e); } }
Base
1
public void testOfCharSequence() { // Should produce a lower-cased AsciiString. assertThat((Object) HttpHeaderNames.of("Foo")).isEqualTo(AsciiString.of("foo")); // Should reuse known header name instances. assertThat((Object) HttpHeaderNames.of("date")).isSameAs(HttpHeaderNames.DATE); }
Class
2
public User getUser() { return user; }
Class
2
public boolean isAvailable() { try { GeoTools.getInitialContext(); return true; } catch (Exception e) { return false; } }
Class
2
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { Path relativeDir = source.relativize(dir); final Path dirToCreate = Paths.get(destDir.toString(), relativeDir.toString()); if(!dirToCreate.toFile().exists()) { Files.createDirectory(dirToCreate); } return FileVisitResult.CONTINUE; }
Base
1
public Document read(Reader reader, String systemId) throws DocumentException { InputSource source = new InputSource(reader); source.setSystemId(systemId); if (this.encoding != null) { source.setEncoding(this.encoding); } return read(source); }
Base
1
public Controller execute(FolderComponent fc, UserRequest ureq, WindowControl wContr, Translator trans) { this.translator = trans; this.folderComponent = fc; this.fileSelection = new FileSelection(ureq, fc.getCurrentContainerPath()); VFSContainer currentContainer = folderComponent.getCurrentContainer(); List<String> lockedFiles = hasLockedFiles(currentContainer, fileSelection); if (lockedFiles.isEmpty()) { String msg = trans.translate("del.confirm") + "<p>" + fileSelection.renderAsHtml() + "</p>"; // create dialog controller dialogCtr = activateYesNoDialog(ureq, trans.translate("del.header"), msg, dialogCtr); } else { String msg = FolderCommandHelper.renderLockedMessageAsHtml(trans, lockedFiles); List<String> buttonLabels = Collections.singletonList(trans.translate("ok")); lockedFiledCtr = activateGenericDialog(ureq, trans.translate("lock.title"), msg, buttonLabels, lockedFiledCtr); } return this; }
Base
1
public DropFileContainer(final String id, final String mimeType) { super(id); this.mimeType = mimeType; main = new WebMarkupContainer("main"); add(main); }
Compound
4
private <P extends T> void translate0(GeyserSession session, PacketTranslator<P> translator, P packet) { if (session.isClosed()) { return; } try { translator.translate(packet, session); } catch (Throwable ex) { GeyserConnector.getInstance().getLogger().error(LanguageUtils.getLocaleStringLog("geyser.network.translator.packet.failed", packet.getClass().getSimpleName()), ex); ex.printStackTrace(); } }
Class
2
public static boolean isAbsolute(String url) { if (url.startsWith("//")) // //www.domain.com/start { return true; } if (url.startsWith("/")) // /somePage.html { return false; } boolean result = false; try { URI uri = new URI(url); result = uri.isAbsolute(); } catch (URISyntaxException e) {} //Ignore return result; }
Base
1
public void encodeByteArrayDeepInJson() throws JSONException { JSONObject data = new JSONObject("{a: \"hi\", b: {}, c: {a: \"bye\", b: {}}}"); data.getJSONObject("b").put("why", new byte[3]); data.getJSONObject("c").getJSONObject("b").put("a", new byte[6]); Packet<JSONObject> packet = new Packet<>(Parser.BINARY_EVENT); packet.data = data; packet.id = 999; packet.nsp = "/deep"; Helpers.testBin(packet); }
Base
1
public Controller execute(FolderComponent folderComponent, UserRequest ureq, WindowControl wControl, Translator trans) { VFSContainer currentContainer = folderComponent.getCurrentContainer(); 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; } if(selection.getFiles().isEmpty()) { status = FolderCommandStatus.STATUS_FAILED; wControl.setWarning(trans.translate("warning.file.selection.empty")); return null; } MediaResource mr = new ZipMediaResource(currentContainer, selection); ureq.getDispatchResult().setResultingMediaResource(mr); return null; }
Base
1
public void setShouldOverWritePreviousValue() { final HttpHeadersBase headers = newEmptyHeaders(); headers.set("name", "value1"); headers.set("name", "value2"); assertThat(headers.size()).isEqualTo(1); assertThat(headers.getAll("name").size()).isEqualTo(1); assertThat(headers.getAll("name").get(0)).isEqualTo("value2"); assertThat(headers.get("name")).isEqualTo("value2"); }
Class
2
public UploadFileResponse getCloudUrl(String contextPath, String uri, String finalFilePath, HttpServletRequest request) { UploadFileResponse uploadFileResponse = new UploadFileResponse(); // try push to cloud Map<String, String[]> map = new HashMap<>(); map.put("fileInfo", new String[]{finalFilePath + "," + uri}); map.put("name", new String[]{"uploadService"}); String url; try { List<Map> urls = HttpUtil.getInstance().sendGetRequest(Constants.pluginServer + "/service", map , new HttpJsonArrayHandle<Map>(), PluginHelper.genHeaderMapByRequest(request)).getT(); if (urls != null && !urls.isEmpty()) { url = (String) urls.get(0).get("url"); if (!url.startsWith("https://") && !url.startsWith("http://")) { String tUrl = url; if (!url.startsWith("/")) { tUrl = "/" + url; } url = contextPath + tUrl; } } else { url = contextPath + uri; } } catch (Exception e) { url = contextPath + uri; LOGGER.error(e); } uploadFileResponse.setUrl(url); return uploadFileResponse; }
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 void testQuoteWorkingDirectoryAndExecutable_WDPathWithSingleQuotes() { Shell sh = newShell(); sh.setWorkingDirectory( "/usr/local/'something else'" ); sh.setExecutable( "chmod" ); String executable = StringUtils.join( sh.getShellCommandLine( new String[]{} ).iterator(), " " ); assertEquals( "/bin/sh -c cd \"/usr/local/\'something else\'\" && chmod", executable ); }
Base
1
private static String bytesToHex(byte[] bytes, int length) { String out = ""; for (int j = 0; j < length; j++) { int v = bytes[j] & 0xFF; out += hexArray[v >>> 4]; out += hexArray[v & 0x0F]; out += " "; } return out; }
Base
1
public void translate(ServerEntityRotationPacket packet, GeyserSession session) { Entity entity = session.getEntityCache().getEntityByJavaId(packet.getEntityId()); if (packet.getEntityId() == session.getPlayerEntity().getEntityId()) { entity = session.getPlayerEntity(); } if (entity == null) return; entity.updateRotation(session, packet.getYaw(), packet.getPitch(), packet.isOnGround()); }
Class
2
protected XMLReader installXMLFilter(XMLReader reader) { XMLFilter filter = getXMLFilter(); if (filter != null) { // find the root XMLFilter XMLFilter root = filter; while (true) { XMLReader parent = root.getParent(); if (parent instanceof XMLFilter) { root = (XMLFilter) parent; } else { break; } } root.setParent(reader); return filter; } return reader; }
Base
1
public static void zipFolderAPKTool(String srcFolder, String destZipFile) throws Exception { try (FileOutputStream fileWriter = new FileOutputStream(destZipFile); ZipOutputStream zip = new ZipOutputStream(fileWriter)){ addFolderToZipAPKTool("", srcFolder, zip); zip.flush(); } }
Base
1
private static boolean nameContainsForbiddenSequence(String name) { boolean result = false; if (name != null) { name = name.toLowerCase(); result = name.startsWith(".") || name.contains("../") || name.contains("..\\") || name.startsWith("/") || name.startsWith("\\") || name.endsWith("/") || name.contains("..%2f") || name.contains("..%5c") || name.startsWith("%2f") || name.startsWith("%5c") || name.endsWith("%2f") || name.contains("..\\u002f") || name.contains("..\\u005c") || name.startsWith("\\u002f") || name.startsWith("\\u005c") || name.endsWith("\\u002f") ; } return result; }
Base
1
public void privateMsgInMuc(Conversation conversation, String nick) { switchToConversation(conversation, null, false, nick, true); }
Class
2
public void delete(String databaseType) { Path path = Paths.get(driverFilePath(driverBaseDirectory, databaseType)); try { Files.deleteIfExists(path); } catch (IOException e) { log.error("delete driver error " + databaseType, e); } }
Class
2
private void saveToFile(VFSLeaf glossaryFile, List<GlossaryItem> glossaryItemArr) { // cdata-tags should be used instead of strings, overwrite writer. glossaryItemArr = removeEmptyGlossaryItems(glossaryItemArr); XStreamHelper.writeObject(xstreamWriter, glossaryFile, glossaryItemArr); }
Base
1
public static File createTempFile(String prefix, String suffix, File directory) throws IOException { if (javaVersion() >= 7) { if (directory == null) { return Files.createTempFile(prefix, suffix).toFile(); } return Files.createTempFile(directory.toPath(), prefix, suffix).toFile(); } if (directory == null) { return File.createTempFile(prefix, suffix); } File file = File.createTempFile(prefix, suffix, directory); // Try to adjust the perms, if this fails there is not much else we can do... file.setReadable(false, false); file.setReadable(true, true); return file; }
Base
1
public void translate(ServerSetSlotPacket packet, GeyserSession session) { if (packet.getWindowId() == 255) { //cursor GeyserItemStack newItem = GeyserItemStack.from(packet.getItem()); session.getPlayerInventory().setCursor(newItem, session); InventoryUtils.updateCursor(session); return; } //TODO: support window id -2, should update player inventory Inventory inventory = InventoryUtils.getInventory(session, packet.getWindowId()); if (inventory == null) return; inventory.setStateId(packet.getStateId()); InventoryTranslator translator = session.getInventoryTranslator(); if (translator != null) { if (session.getCraftingGridFuture() != null) { session.getCraftingGridFuture().cancel(false); } session.setCraftingGridFuture(session.scheduleInEventLoop(() -> updateCraftingGrid(session, packet, inventory, translator), 150, TimeUnit.MILLISECONDS)); GeyserItemStack newItem = GeyserItemStack.from(packet.getItem()); if (packet.getWindowId() == 0 && !(translator instanceof PlayerInventoryTranslator)) { // In rare cases, the window ID can still be 0 but Java treats it as valid session.getPlayerInventory().setItem(packet.getSlot(), newItem, session); InventoryTranslator.PLAYER_INVENTORY_TRANSLATOR.updateSlot(session, session.getPlayerInventory(), packet.getSlot()); } else { inventory.setItem(packet.getSlot(), newItem, session); translator.updateSlot(session, inventory, packet.getSlot()); } } }
Class
2
public void accessDenied() { expect(backend.isRemoteAccessAllowed("localhost","127.0.0.1")).andReturn(false); replay(backend); handler.checkClientIPAccess("localhost","127.0.0.1"); }
Compound
4
public void newDocumentFromURLTemplateProviderSpecifiedButNotAllowed() throws Exception { // new document = xwiki:X.Y DocumentReference documentReference = new DocumentReference("Y", new SpaceReference("X", new WikiReference("xwiki"))); XWikiDocument document = mock(XWikiDocument.class); when(document.getDocumentReference()).thenReturn(documentReference); when(document.isNew()).thenReturn(true); when(document.getLocalReferenceMaxLength()).thenReturn(255); context.setDoc(document); // Specifying a template provider in the URL: templateprovider=XWiki.MyTemplateProvider String templateProviderFullName = "XWiki.MyTemplateProvider"; when(mockRequest.getParameter("templateprovider")).thenReturn(templateProviderFullName); // Mock 1 existing template provider mockExistingTemplateProviders(templateProviderFullName, new DocumentReference("xwiki", Arrays.asList("XWiki"), "MyTemplateProvider"), Arrays.asList("AnythingButX")); // Run the action String result = action.render(context); // The tests are below this line! // Verify that the create template is rendered, so the UI is displayed for the user to see the error. assertEquals("create", result); // Check that the exception is properly set in the context for the UI to display. XWikiException exception = (XWikiException) this.oldcore.getScriptContext().getAttribute("createException"); assertNotNull(exception); assertEquals(XWikiException.ERROR_XWIKI_APP_TEMPLATE_NOT_AVAILABLE, exception.getCode()); // We should not get this far so no redirect should be done, just the template will be rendered. verify(mockURLFactory, never()).createURL(any(), any(), any(), any(), any(), any(), any(XWikiContext.class)); }
Class
2
public void translate(PositionTrackingDBClientRequestPacket packet, GeyserSession session) { PositionTrackingDBServerBroadcastPacket broadcastPacket = new PositionTrackingDBServerBroadcastPacket(); broadcastPacket.setTrackingId(packet.getTrackingId()); // Fetch the stored Loadstone LoadstoneTracker.LoadstonePos pos = LoadstoneTracker.getPos(packet.getTrackingId()); // If we don't have data for that ID tell the client its not found if (pos == null) { broadcastPacket.setAction(PositionTrackingDBServerBroadcastPacket.Action.NOT_FOUND); session.sendUpstreamPacket(broadcastPacket); return; } broadcastPacket.setAction(PositionTrackingDBServerBroadcastPacket.Action.UPDATE); // Build the nbt data for the update NbtMapBuilder builder = NbtMap.builder(); builder.putInt("dim", DimensionUtils.javaToBedrock(pos.getDimension())); builder.putString("id", String.format("%08X", packet.getTrackingId())); builder.putByte("version", (byte) 1); // Not sure what this is for builder.putByte("status", (byte) 0); // Not sure what this is for // Build the position for the update IntList posList = new IntArrayList(); posList.add(pos.getX()); posList.add(pos.getY()); posList.add(pos.getZ()); builder.putList("pos", NbtType.INT, posList); broadcastPacket.setTag(builder.build()); session.sendUpstreamPacket(broadcastPacket); }
Class
2
public static void copyDb( String jdbcDriverSource, String usernameSource, String passwordSource, String jdbcUrlSource, String jdbcDriverTarget, String usernameTarget, String passwordTarget, String jdbcUrlTarget, List<String> includeDbObjects, List<String> excludeDbObjects, List<String> valuePatterns, List<String> valueReplacements, PrintStream out ) throws ServiceException { { DBOBJECTS.clear(); List<String> tableNames = new ArrayList<String>(); try { tableNames = DbSchemaUtils.getTableNames(); } catch (Exception e) { new ServiceException(e).log(); } for(String tableName : tableNames) { if( tableName.indexOf("_") > 0 && tableName.indexOf("_TOBJ_") < 0 && tableName.indexOf("_JOIN_") < 0 && !tableName.endsWith("_") ) { DBOBJECTS.add(tableName); } } } try { // Source connection Class.forName(jdbcDriverSource); Properties props = new Properties(); props.put("user", usernameSource); props.put("password", passwordSource); Connection connSource = DriverManager.getConnection(jdbcUrlSource, props); connSource.setAutoCommit(true); // Target connection Class.forName(jdbcDriverTarget); props = new Properties(); props.put("user", usernameTarget); props.put("password", passwordTarget); Connection connTarget = DriverManager.getConnection(jdbcUrlTarget, props); connTarget.setAutoCommit(true); CopyDb.copyNamespace( connSource, connTarget, filterDbObjects( DBOBJECTS, includeDbObjects, excludeDbObjects ), valuePatterns, valueReplacements, out ); } catch (Exception e) { throw new ServiceException(e); } out.println(); out.println("!!! DONE !!!"); }
Base
1
protected StyleSignatureBasic getStyleSignature() { if (type == TimingStyle.CONCISE) return StyleSignatureBasic.of(SName.root, SName.element, SName.timingDiagram, SName.concise); if (type == TimingStyle.ROBUST) return StyleSignatureBasic.of(SName.root, SName.element, SName.timingDiagram, SName.robust); throw new IllegalStateException(); }
Base
1
public void translate(NetworkStackLatencyPacket packet, GeyserSession session) { long pingId; // so apparently, as of 1.16.200 // PS4 divides the network stack latency timestamp FOR US!!! // WTF if (session.getClientData().getDeviceOs().equals(DeviceOs.PS4)) { pingId = packet.getTimestamp(); } else { pingId = packet.getTimestamp() / 1000; } // negative timestamps are used as hack to fix the url image loading bug if (packet.getTimestamp() > 0) { if (session.getConnector().getConfig().isForwardPlayerPing()) { ClientKeepAlivePacket keepAlivePacket = new ClientKeepAlivePacket(pingId); session.sendDownstreamPacket(keepAlivePacket); } return; } // Hack to fix the url image loading bug UpdateAttributesPacket attributesPacket = new UpdateAttributesPacket(); attributesPacket.setRuntimeEntityId(session.getPlayerEntity().getGeyserId()); AttributeData attribute = session.getPlayerEntity().getAttributes().get(GeyserAttributeType.EXPERIENCE_LEVEL); if (attribute != null) { attributesPacket.setAttributes(Collections.singletonList(attribute)); } else { attributesPacket.setAttributes(Collections.singletonList(GeyserAttributeType.EXPERIENCE_LEVEL.getAttribute(0))); } session.getConnector().getGeneralThreadPool().schedule( () -> session.sendUpstreamPacket(attributesPacket), 500, TimeUnit.MILLISECONDS); }
Class
2
public SymbolContext getContext(ISkinParam skinParam, Style style) { return new SymbolContext(getBackColor(skinParam, style), getLineColor(skinParam, style)) .withStroke(new UStroke(1.5)); }
Base
1
public BCXMSSMTPrivateKey(PrivateKeyInfo keyInfo) throws IOException { XMSSMTKeyParams keyParams = XMSSMTKeyParams.getInstance(keyInfo.getPrivateKeyAlgorithm().getParameters()); this.treeDigest = keyParams.getTreeDigest().getAlgorithm(); XMSSPrivateKey xmssMtPrivateKey = XMSSPrivateKey.getInstance(keyInfo.parsePrivateKey()); try { XMSSMTPrivateKeyParameters.Builder keyBuilder = new XMSSMTPrivateKeyParameters .Builder(new XMSSMTParameters(keyParams.getHeight(), keyParams.getLayers(), DigestUtil.getDigest(treeDigest))) .withIndex(xmssMtPrivateKey.getIndex()) .withSecretKeySeed(xmssMtPrivateKey.getSecretKeySeed()) .withSecretKeyPRF(xmssMtPrivateKey.getSecretKeyPRF()) .withPublicSeed(xmssMtPrivateKey.getPublicSeed()) .withRoot(xmssMtPrivateKey.getRoot()); if (xmssMtPrivateKey.getBdsState() != null) { keyBuilder.withBDSState((BDSStateMap)XMSSUtil.deserialize(xmssMtPrivateKey.getBdsState())); } this.keyParams = keyBuilder.build(); } catch (ClassNotFoundException e) { throw new IOException("ClassNotFoundException processing BDS state: " + e.getMessage()); } }
Base
1
public void testCreateHttpUrlConnection() { HttpURLConnection conn; // Test without proxy conn = createHttpUrlConnection(convertToUrl(TEST_URL), "", 0, "", ""); Assert.assertNotNull(conn); // Test with the proxy conn = createHttpUrlConnection(convertToUrl(TEST_URL), "http://localhost", 9090, "testUser", "testPassword"); Assert.assertNotNull(conn); }
Base
1
public void failingExample() throws Exception { assertThat(ConstraintViolations.format(validator.validate(new FailingExample()))) .containsExactlyInAnyOrder(FAILED_RESULT); assertThat(TestLoggerFactory.getAllLoggingEvents()) .isEmpty(); }
Class
2
private void checkParams() throws Exception { if (vi == null) { throw new Exception("no layers defined."); } if (vi.length > 1) { for (int i = 0; i < vi.length - 1; i++) { if (vi[i] >= vi[i + 1]) { throw new Exception( "v[i] has to be smaller than v[i+1]"); } } } else { throw new Exception( "Rainbow needs at least 1 layer, such that v1 < v2."); } }
Base
1
public int encryptWithAd(byte[] ad, byte[] plaintext, int plaintextOffset, byte[] ciphertext, int ciphertextOffset, int length) throws ShortBufferException { int space; if (ciphertextOffset > ciphertext.length) space = 0; else space = ciphertext.length - ciphertextOffset; if (!haskey) { // The key is not set yet - return the plaintext as-is. if (length > space) throw new ShortBufferException(); if (plaintext != ciphertext || plaintextOffset != ciphertextOffset) System.arraycopy(plaintext, plaintextOffset, ciphertext, ciphertextOffset, length); return length; } if (space < 16 || length > (space - 16)) throw new ShortBufferException(); setup(ad); 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
default Optional<String> findFirst(CharSequence name) { return getFirst(name, String.class); }
Class
2
public static void beforeClass() throws IOException { final Random r = new Random(); for (int i = 0; i < BYTES.length; i++) { BYTES[i] = (byte) r.nextInt(255); } tmp = File.createTempFile("netty-traffic", ".tmp"); tmp.deleteOnExit(); FileOutputStream out = null; try { out = new FileOutputStream(tmp); out.write(BYTES); out.flush(); } catch (IOException e) { throw new RuntimeException(e); } finally { if (out != null) { try { out.close(); } catch (IOException e) { // ignore } } } }
Base
1
public static int version() { return 1202204; }
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 (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 equals(Object obj) { if (obj == this) { return true; } if (obj instanceof ClassPathResource) { ClassPathResource otherRes = (ClassPathResource) obj; ClassLoader thisLoader = this.classLoader; ClassLoader otherLoader = otherRes.classLoader; return (this.path.equals(otherRes.path) && thisLoader.equals(otherLoader) && this.clazz.equals(otherRes.clazz)); } return false; }
Base
1
public ProductServletConfigurator(ServerConfig serverConfig, ShiroFilter shiroFilter, GitFilter gitFilter, GitPreReceiveCallback preReceiveServlet, GitPostReceiveCallback postReceiveServlet, WicketServlet wicketServlet, WebSocketManager webSocketManager, AttachmentUploadServlet attachmentUploadServlet, ServletContainer jerseyServlet) { this.serverConfig = serverConfig; this.shiroFilter = shiroFilter; this.gitFilter = gitFilter; this.preReceiveServlet = preReceiveServlet; this.postReceiveServlet = postReceiveServlet; this.wicketServlet = wicketServlet; this.webSocketManager = webSocketManager; this.jerseyServlet = jerseyServlet; this.attachmentUploadServlet = attachmentUploadServlet; }
Base
1
void colon() { assertThat(PathAndQuery.parse("/:")).isNotNull(); assertThat(PathAndQuery.parse("/:/")).isNotNull(); assertThat(PathAndQuery.parse("/a/:")).isNotNull(); assertThat(PathAndQuery.parse("/a/:/")).isNotNull(); }
Base
1
public void testPseudoHeadersWithRemovePreservesPseudoIterationOrder() { final HttpHeadersBase headers = newHttp2Headers(); final HttpHeadersBase nonPseudoHeaders = newEmptyHeaders(); for (Map.Entry<AsciiString, String> entry : headers) { if (entry.getKey().isEmpty() || entry.getKey().charAt(0) != ':' && !nonPseudoHeaders.contains(entry.getKey())) { nonPseudoHeaders.add(entry.getKey(), entry.getValue()); } } assertThat(nonPseudoHeaders.isEmpty()).isFalse(); // Remove all the non-pseudo headers and verify for (Map.Entry<AsciiString, String> nonPseudoHeaderEntry : nonPseudoHeaders) { assertThat(headers.remove(nonPseudoHeaderEntry.getKey())).isTrue(); verifyPseudoHeadersFirst(headers); verifyAllPseudoHeadersPresent(headers); } // Add back all non-pseudo headers for (Map.Entry<AsciiString, String> nonPseudoHeaderEntry : nonPseudoHeaders) { headers.add(nonPseudoHeaderEntry.getKey(), "goo"); verifyPseudoHeadersFirst(headers); verifyAllPseudoHeadersPresent(headers); } }
Class
2
public String getSHA(String password) { try { // Static getInstance method is called with hashing SHA MessageDigest md = MessageDigest.getInstance("SHA-256"); // digest() method called // to calculate message digest of an input // and return array of byte byte[] messageDigest = md.digest(password.getBytes()); // Convert byte array into signum representation BigInteger no = new BigInteger(1, messageDigest); // Convert message digest into hex value String hashPass = no.toString(16); while (hashPass.length() < 32) { hashPass = "0" + hashPass; } return hashPass; // For specifying wrong message digest algorithms } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return null; } }
Variant
0
public SAXReader(XMLReader xmlReader) { this.xmlReader = xmlReader; }
Base
1
protected void onStart() { super.onStart(); Intent intent = getIntent(); intent.putExtra( SettingsActivity.SP_FEED_LIST_LAYOUT, mPrefs.getString(SettingsActivity.SP_FEED_LIST_LAYOUT, "0") ); setResult(RESULT_OK,intent); }
Base
1
public ExitCode runWithoutHelp(CommandRunnerParams params) throws IOException, InterruptedException { if (saveFilename != null && loadFilename != null) { params.getConsole().printErrorText("Can't use both --load and --save"); return ExitCode.COMMANDLINE_ERROR; } if (saveFilename != null) { invalidateChanges(params); RemoteDaemonicParserState state = params.getParser().storeParserState(params.getCell()); try (FileOutputStream fos = new FileOutputStream(saveFilename); ZipOutputStream zipos = new ZipOutputStream(fos)) { zipos.putNextEntry(new ZipEntry("parser_data")); try (ObjectOutputStream oos = new ObjectOutputStream(zipos)) { oos.writeObject(state); } } } else if (loadFilename != null) { try (FileInputStream fis = new FileInputStream(loadFilename); ZipInputStream zipis = new ZipInputStream(fis)) { ZipEntry entry = zipis.getNextEntry(); Preconditions.checkState(entry.getName().equals("parser_data")); try (ObjectInputStream ois = new ObjectInputStream(zipis)) { RemoteDaemonicParserState state; try { state = (RemoteDaemonicParserState) ois.readObject(); } catch (ClassNotFoundException e) { params.getConsole().printErrorText("Invalid file format"); return ExitCode.COMMANDLINE_ERROR; } params.getParser().restoreParserState(state, params.getCell()); } } invalidateChanges(params); ParserConfig configView = params.getBuckConfig().getView(ParserConfig.class); if (configView.isParserCacheMutationWarningEnabled()) { params .getConsole() .printErrorText( params .getConsole() .getAnsi() .asWarningText( "WARNING: Buck injected a parser state that may not match the local state.")); } } return ExitCode.SUCCESS; }
Base
1
final protected SymbolContext getContext() { if (UseStyle.useBetaStyle() == false) return getContextLegacy(); final Style style = getStyleSignature().getMergedStyle(skinParam.getCurrentStyleBuilder()); final HColor lineColor = style.value(PName.LineColor).asColor(skinParam.getThemeStyle(), skinParam.getIHtmlColorSet()); final HColor backgroundColor = style.value(PName.BackGroundColor).asColor(skinParam.getThemeStyle(), skinParam.getIHtmlColorSet()); return new SymbolContext(backgroundColor, lineColor).withStroke(getStroke()); }
Base
1
public String render(String templateContent, Map<String, Object> context) { VelocityContext velocityContext = new VelocityContext(context); try (StringWriter sw = new StringWriter()) { Velocity.evaluate(velocityContext, sw, "velocityTemplateEngine", templateContent); return sw.toString(); } catch (Exception ex) { throw new TemplateRenderException(ex); } }
Class
2
public String list(Model model, // TODO model should no longer be injected @RequestParam(required = false, defaultValue = "FILENAME") SortBy sortBy, @RequestParam(required = false, defaultValue = "false") boolean desc, @RequestParam(required = false) String base) throws IOException, TemplateException { securityCheck(base); Path currentFolder = loggingPath(base); List<FileEntry> files = getFileProvider(currentFolder).getFileEntries(currentFolder); List<FileEntry> sortedFiles = sortFiles(files, sortBy, desc); model.addAttribute("sortBy", sortBy); model.addAttribute("desc", desc); model.addAttribute("files", sortedFiles); model.addAttribute("currentFolder", currentFolder.toAbsolutePath().toString()); model.addAttribute("base", base != null ? URLEncoder.encode(base, "UTF-8") : ""); model.addAttribute("parent", getParent(currentFolder)); model.addAttribute("stylesheets", stylesheets); return FreeMarkerTemplateUtils.processTemplateIntoString(freemarkerConfig.getTemplate("logview.ftl"), model); }
Base
1
private final void servlet31(HttpServletRequest request) { try { for(Part part:request.getParts()) { if(part.getContentType() != null && (StringHelper.containsNonWhitespace(part.getSubmittedFileName()) || !part.getContentType().startsWith("text/plain"))) { contentType = part.getContentType(); filename = part.getSubmittedFileName(); if(filename != null) { filename = UUID.randomUUID().toString().replace("-", "") + "_" + filename; } else { filename = "upload-" + UUID.randomUUID().toString().replace("-", ""); } file = new File(WebappHelper.getTmpDir(), filename); part.write(file.getAbsolutePath()); file = new File(WebappHelper.getTmpDir(), filename); } else { String value = IOUtils.toString(part.getInputStream(), request.getCharacterEncoding()); fields.put(part.getName(), value); } try { part.delete(); } catch (Exception e) { //we try (tomcat doesn't send exception but undertow) } } } catch (IOException | ServletException e) { log.error("", e); } }
Base
1
public void saveCustomConfigAndCompileCSS(Map<String, Map<String, Object>> customConfig, CourseEnvironment courseEnvironment){ VFSContainer themeBase = null; VFSContainer base = null; base = (VFSContainer) courseEnvironment.getCourseBaseContainer().resolve(CourseLayoutHelper.LAYOUT_COURSE_SUBFOLDER); if (base == null) { base = courseEnvironment.getCourseBaseContainer().createChildContainer(CourseLayoutHelper.LAYOUT_COURSE_SUBFOLDER); } themeBase = (VFSContainer) base.resolve("/" + CourseLayoutHelper.CONFIG_KEY_CUSTOM); if (themeBase == null) { themeBase = base.createChildContainer(CourseLayoutHelper.CONFIG_KEY_CUSTOM); } VFSLeaf configTarget = (VFSLeaf) themeBase.resolve(CUSTOM_CONFIG_XML); if (configTarget == null) { configTarget = themeBase.createChildLeaf(CUSTOM_CONFIG_XML); } XStream xStream = XStreamHelper.createXStreamInstance(); xStream.toXML(customConfig, configTarget.getOutputStream(false)); // compile the css-files StringBuilder sbMain = new StringBuilder(); StringBuilder sbIFrame = new StringBuilder(); for (Entry<String, Map<String, Object>> iterator : customConfig.entrySet()) { String type = iterator.getKey(); Map<String, Object> elementConfig = iterator.getValue(); AbstractLayoutElement configuredLayEl = createLayoutElementByType(type, elementConfig); sbIFrame.append(configuredLayEl.getCSSForIFrame()); sbMain.append(configuredLayEl.getCSSForMain()); } // attach line for logo, if there is any to cssForMain: appendLogoPart(sbMain, themeBase); VFSLeaf mainFile = (VFSLeaf) themeBase.resolve(MAIN_CSS); if (mainFile == null) mainFile = themeBase.createChildLeaf(MAIN_CSS); VFSLeaf iFrameFile = (VFSLeaf) themeBase.resolve(IFRAME_CSS); if (iFrameFile == null) iFrameFile = themeBase.createChildLeaf(IFRAME_CSS); FileUtils.save(mainFile.getOutputStream(false), sbMain.toString(), "utf-8"); FileUtils.save(iFrameFile.getOutputStream(false), sbIFrame.toString(), "utf-8"); }
Base
1
public UserCause(User user, String message) { super(hudson.slaves.Messages._SlaveComputer_DisconnectedBy( user!=null ? user.getId() : Jenkins.ANONYMOUS.getName(), message != null ? " : " + message : "" )); this.user = user; }
Class
2