code
stringlengths
12
2.05k
label_name
stringclasses
5 values
label
int64
0
4
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { String secret = getSecret(); Key key = new SecretKeySpec(Decoders.BASE64.decode(secret), getSignatureAlgorithm().getJcaName()); Jwt jwt = Jwts.parser(). setSigningKey(key). parse((String) token.getPrincipal()); Map<String, Serializable> principal = getPrincipal(jwt); return new SimpleAuthenticationInfo(principal, ((String) token.getCredentials()).toCharArray(), getName()); }
Base
1
protected void switchToConversation(Contact contact, String body) { Conversation conversation = xmppConnectionService .findOrCreateConversation(contact.getAccount(), contact.getJid(), false, true); switchToConversation(conversation, body); }
Class
2
private void testGeneration() throws Exception { // // ECDSA generation test // byte[] data = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 }; Signature s = Signature.getInstance("ECDSA", "BC"); KeyPairGenerator g = KeyPairGenerator.getInstance("ECDSA", "BC"); EllipticCurve curve = new EllipticCurve( new ECFieldFp(new BigInteger("883423532389192164791648750360308885314476597252960362792450860609699839")), // q new BigInteger("7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc", 16), // a new BigInteger("6b016c3bdcf18941d0d654921475ca71a9db2fb27d1d37796185c2942c0a", 16)); // b ECParameterSpec ecSpec = new ECParameterSpec( curve, ECPointUtil.decodePoint(curve, Hex.decode("020ffa963cdca8816ccc33b8642bedf905c3d358573d3f27fbbd3b3cb9aaaf")), // G new BigInteger("883423532389192164791648750360308884807550341691627752275345424702807307"), // n 1); // h g.initialize(ecSpec, new SecureRandom()); KeyPair p = g.generateKeyPair(); PrivateKey sKey = p.getPrivate(); PublicKey vKey = p.getPublic(); s.initSign(sKey); s.update(data); byte[] sigBytes = s.sign(); s = Signature.getInstance("ECDSA", "BC"); s.initVerify(vKey); s.update(data); if (!s.verify(sigBytes)) { fail("ECDSA verification failed"); } testKeyFactory((ECPublicKey)vKey, (ECPrivateKey)sKey); testSerialise((ECPublicKey)vKey, (ECPrivateKey)sKey); }
Base
1
public void testSelectByUse() { JWKSelector selector = new JWKSelector(new JWKMatcher.Builder().keyUse(KeyUse.ENCRYPTION).build()); List<JWK> keyList = new ArrayList<>(); keyList.add(new RSAKey.Builder(new Base64URL("n"), new Base64URL("e")).keyID("1").keyUse(KeyUse.ENCRYPTION).build()); keyList.add(new ECKey.Builder(ECKey.Curve.P_256, new Base64URL("x"), new Base64URL("y")).keyID("2").build()); JWKSet jwkSet = new JWKSet(keyList); List<JWK> matches = selector.select(jwkSet); RSAKey key1 = (RSAKey)matches.get(0); assertEquals(KeyType.RSA, key1.getKeyType()); assertEquals(KeyUse.ENCRYPTION, key1.getKeyUse()); assertEquals("1", key1.getKeyID()); assertEquals(1, matches.size()); }
Base
1
public void translate(ServerPlaySoundPacket packet, GeyserSession session) { String packetSound; if (packet.getSound() instanceof BuiltinSound) { packetSound = ((BuiltinSound) packet.getSound()).getName(); } else if (packet.getSound() instanceof CustomSound) { packetSound = ((CustomSound) packet.getSound()).getName(); } else { session.getConnector().getLogger().debug("Unknown sound packet, we were unable to map this. " + packet.toString()); return; } SoundMapping soundMapping = Registries.SOUNDS.get(packetSound.replace("minecraft:", "")); String playsound; if (soundMapping == null || soundMapping.getPlaysound() == null) { // no mapping session.getConnector().getLogger() .debug("[PlaySound] Defaulting to sound server gave us for " + packet.toString()); playsound = packetSound.replace("minecraft:", ""); } else { playsound = soundMapping.getPlaysound(); } PlaySoundPacket playSoundPacket = new PlaySoundPacket(); playSoundPacket.setSound(playsound); playSoundPacket.setPosition(Vector3f.from(packet.getX(), packet.getY(), packet.getZ())); playSoundPacket.setVolume(packet.getVolume()); playSoundPacket.setPitch(packet.getPitch()); session.sendUpstreamPacket(playSoundPacket); }
Class
2
private ByteArrayOutputStream initRequestResponseMocks(String callback,Runnable requestSetup,Runnable responseSetup) throws IOException { request = createMock(HttpServletRequest.class); response = createMock(HttpServletResponse.class); setNoCacheHeaders(response); expect(request.getParameter(ConfigKey.CALLBACK.getKeyValue())).andReturn(callback); requestSetup.run(); responseSetup.run(); class MyServletOutputStream extends ServletOutputStream { ByteArrayOutputStream baos; public void write(int b) throws IOException { baos.write(b); } public void setBaos(ByteArrayOutputStream baos){ this.baos = baos; } } ByteArrayOutputStream baos = new ByteArrayOutputStream(); MyServletOutputStream sos = new MyServletOutputStream(); sos.setBaos(baos); expect(response.getOutputStream()).andReturn(sos); return baos; }
Base
1
public static AsciiString of(CharSequence name) { if (name instanceof AsciiString) { return of((AsciiString) name); } final String lowerCased = Ascii.toLowerCase(requireNonNull(name, "name")); final AsciiString cached = map.get(lowerCased); return cached != null ? cached : AsciiString.cached(lowerCased); }
Class
2
public void resetHandlers() { getDispatchHandler().resetHandlers(); }
Base
1
public boolean isStringInternEnabled() { return stringInternEnabled; }
Base
1
public ResponseEntity<Resource> download(@PathVariable String key) { LitemallStorage litemallStorage = litemallStorageService.findByKey(key); if (key == null) { ResponseEntity.notFound(); } String type = litemallStorage.getType(); MediaType mediaType = MediaType.parseMediaType(type); Resource file = storageService.loadAsResource(key); if (file == null) { ResponseEntity.notFound(); } return ResponseEntity.ok().contentType(mediaType).header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.getFilename() + "\"").body(file); }
Base
1
public static SSLSocketFactory getSslSocketFactory(Properties info) throws PSQLException { String classname = PGProperty.SSL_FACTORY.get(info); if (classname == null || "org.postgresql.ssl.jdbc4.LibPQFactory".equals(classname) || "org.postgresql.ssl.LibPQFactory".equals(classname)) { return new LibPQFactory(info); } try { return (SSLSocketFactory) ObjectFactory.instantiate(classname, info, true, PGProperty.SSL_FACTORY_ARG.get(info)); } catch (Exception e) { throw new PSQLException( GT.tr("The SSLSocketFactory class provided {0} could not be instantiated.", classname), PSQLState.CONNECTION_FAILURE, e); } }
Class
2
public int checkSessionsValidity() { int expired = 0; acquireExclusiveLock(); try { final long now = System.currentTimeMillis(); Entry<String, OHttpSession> s; for (Iterator<Map.Entry<String, OHttpSession>> it = sessions.entrySet().iterator(); it.hasNext();) { s = it.next(); if (now - s.getValue().getUpdatedOn() > expirationTime) { // REMOVE THE SESSION it.remove(); expired++; } } } finally { releaseExclusiveLock(); } return expired; }
Class
2
public void getLogFile(@PathVariable("filename") String fileName, HttpServletResponse response) throws Exception { InputStream inputStream = null; try { //Validate/Sanitize user input filename using a standard library, prevent from path traversal String logFileName = getFilePath() + File.separator + FilenameUtils.getName(fileName); File fileToDownload = new File(logFileName); inputStream = new FileInputStream(fileToDownload); response.setContentType("application/force-download"); response.setHeader("Content-Disposition", "attachment; filename=" + fileName); IOUtils.copy(inputStream, response.getOutputStream()); response.flushBuffer(); } catch (Exception e) { logger.debug("Request could not be completed at this moment. Please try again."); logger.debug(e.getStackTrace().toString()); throw e; } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { logger.debug(e.getStackTrace().toString()); throw e; } } } }
Base
1
public boolean importWiki(File file, String filename, File targetDirectory) { try { Path path = FileResource.getResource(file, filename); if(path == null) { return false; } Path destDir = targetDirectory.toPath(); Files.walkFileTree(path, new ImportVisitor(destDir)); PathUtils.closeSubsequentFS(path); return true; } catch (IOException e) { log.error("", e); return false; } }
Base
1
public void deleteById(Integer id) { databaseTypeDao.selectOptionalById(id).ifPresent(data -> { if (DatabaseTypes.has(data.getDatabaseType())) { throw DomainErrors.MUST_NOT_MODIFY_SYSTEM_DEFAULT_DATABASE_TYPE.exception(); } databaseTypeDao.deleteById(id); driverResources.delete(data.getDatabaseType()); }); }
Class
2
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 XMLReader getXMLReader() throws SAXException { if (xmlReader == null) { xmlReader = createXMLReader(); } return xmlReader; }
Base
1
private static CharSequenceMap toLowercaseMap(Iterator<? extends CharSequence> valuesIter, int arraySizeHint) { final CharSequenceMap result = new CharSequenceMap(arraySizeHint); while (valuesIter.hasNext()) { final AsciiString lowerCased = HttpHeaderNames.of(valuesIter.next()).toLowerCase(); try { int index = lowerCased.forEachByte(FIND_COMMA); if (index != -1) { int start = 0; do { result.add(lowerCased.subSequence(start, index, false).trim(), EMPTY_STRING); start = index + 1; } while (start < lowerCased.length() && (index = lowerCased.forEachByte(start, lowerCased.length() - start, FIND_COMMA)) != -1); result.add(lowerCased.subSequence(start, lowerCased.length(), false).trim(), EMPTY_STRING); } else { result.add(lowerCased.trim(), EMPTY_STRING); } } catch (Exception e) { // This is not expect to happen because FIND_COMMA never throws but must be caught // because of the ByteProcessor interface. throw new IllegalStateException(e); } } return result; }
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
protected IBaseResource addCommonParams(HttpServletRequest theServletRequest, final HomeRequest theRequest, final ModelMap theModel) { final String serverId = theRequest.getServerIdWithDefault(myConfig); final String serverBase = theRequest.getServerBase(theServletRequest, myConfig); final String serverName = theRequest.getServerName(myConfig); final String apiKey = theRequest.getApiKey(theServletRequest, myConfig); theModel.put("serverId", serverId); theModel.put("base", serverBase); theModel.put("baseName", serverName); theModel.put("apiKey", apiKey); theModel.put("resourceName", defaultString(theRequest.getResource())); theModel.put("encoding", theRequest.getEncoding()); theModel.put("pretty", theRequest.getPretty()); theModel.put("_summary", theRequest.get_summary()); theModel.put("serverEntries", myConfig.getIdToServerName()); return loadAndAddConf(theServletRequest, theRequest, theModel); }
Base
1
public void translate(ServerExplosionPacket packet, GeyserSession session) { for (ExplodedBlockRecord record : packet.getExploded()) { Vector3f pos = Vector3f.from(packet.getX() + record.getX(), packet.getY() + record.getY(), packet.getZ() + record.getZ()); ChunkUtils.updateBlock(session, BlockStateValues.JAVA_AIR_ID, pos.toInt()); } Vector3f pos = Vector3f.from(packet.getX(), packet.getY(), packet.getZ()); // Since bedrock does not play an explosion sound and particles sound, we have to manually do so LevelEventPacket levelEventPacket = new LevelEventPacket(); levelEventPacket.setType(packet.getRadius() >= 2.0f ? LevelEventType.PARTICLE_HUGE_EXPLODE : LevelEventType.PARTICLE_EXPLOSION); levelEventPacket.setData(0); levelEventPacket.setPosition(pos.toFloat()); session.sendUpstreamPacket(levelEventPacket); LevelSoundEventPacket levelSoundEventPacket = new LevelSoundEventPacket(); levelSoundEventPacket.setRelativeVolumeDisabled(false); levelSoundEventPacket.setBabySound(false); levelSoundEventPacket.setExtraData(-1); levelSoundEventPacket.setSound(SoundEvent.EXPLODE); levelSoundEventPacket.setIdentifier(":"); levelSoundEventPacket.setPosition(Vector3f.from(packet.getX(), packet.getY(), packet.getZ())); session.sendUpstreamPacket(levelSoundEventPacket); if (packet.getPushX() > 0f || packet.getPushY() > 0f || packet.getPushZ() > 0f) { SetEntityMotionPacket motionPacket = new SetEntityMotionPacket(); motionPacket.setRuntimeEntityId(session.getPlayerEntity().getGeyserId()); motionPacket.setMotion(Vector3f.from(packet.getPushX(), packet.getPushY(), packet.getPushZ())); session.sendUpstreamPacket(motionPacket); } }
Class
2
protected HtmlRenderable htmlBody() { return HtmlElement.li().content( HtmlElement.span(HtmlAttribute.cssClass("artifact")).content( HtmlElement.a(HtmlAttribute.href(getUrl())) .content(getFileName()) ) ); }
Base
1
void newDocumentInvalidName() throws Exception { when(mockDocument.isNew()).thenReturn(true); DocumentReference documentReference = new DocumentReference("XWiki", "Foo", "Bar"); when(mockDocument.getDocumentReference()).thenReturn(documentReference); when(this.entityNameValidationConfiguration.useValidation()).thenReturn(true); EntityNameValidation entityNameValidation = mock(EntityNameValidation.class); when(this.entityNameValidationManager.getEntityReferenceNameStrategy()).thenReturn(entityNameValidation); when(entityNameValidation.isValid(documentReference)).thenReturn(false); assertTrue(saveAction.save(this.context)); assertEquals("entitynamevalidation.create.invalidname", context.get("message")); assertArrayEquals(new Object[] { "Foo.Bar" }, (Object[]) context.get("messageParameters")); }
Class
2
public ConstraintValidatorContext getContext() { return context; }
Class
2
private static IRegex getRegexConcat() { return RegexConcat.build(CommandBinary.class.getName(), RegexLeaf.start(), // new RegexOptional( // new RegexConcat( // new RegexLeaf("COMPACT", "(compact)"), // RegexLeaf.spaceOneOrMore())), // new RegexLeaf("binary"), // RegexLeaf.spaceOneOrMore(), // new RegexLeaf("FULL", "[%g]([^%g]+)[%g]"), // RegexLeaf.spaceOneOrMore(), // new RegexLeaf("as"), // RegexLeaf.spaceOneOrMore(), // new RegexLeaf("CODE", "([%pLN_.@]+)"), RegexLeaf.end()); }
Base
1
private void ondata(byte[] data) { try { this.decoder.add(data); } catch (DecodingException e) { this.onerror(e); } }
Base
1
private void displayVerificationWarningDialog(final Contact contact, final Invite invite) { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(R.string.verify_omemo_keys); View view = getLayoutInflater().inflate(R.layout.dialog_verify_fingerprints, null); final CheckBox isTrustedSource = view.findViewById(R.id.trusted_source); TextView warning = view.findViewById(R.id.warning); warning.setText(JidDialog.style(this, R.string.verifying_omemo_keys_trusted_source, contact.getJid().asBareJid().toEscapedString(), contact.getDisplayName())); builder.setView(view); builder.setPositiveButton(R.string.confirm, (dialog, which) -> { if (isTrustedSource.isChecked() && invite.hasFingerprints()) { xmppConnectionService.verifyFingerprints(contact, invite.getFingerprints()); } switchToConversation(contact, invite.getBody()); }); builder.setNegativeButton(R.string.cancel, (dialog, which) -> StartConversationActivity.this.finish()); AlertDialog dialog = builder.create(); dialog.setCanceledOnTouchOutside(false); dialog.setOnCancelListener(dialog1 -> StartConversationActivity.this.finish()); dialog.show(); }
Class
2
public EnhancedXStream(boolean export) { super(); if (export) { addDefaultImplementation(PersistentList.class, List.class); addDefaultImplementation(PersistentBag.class, List.class); addDefaultImplementation(PersistentMap.class, Map.class); addDefaultImplementation(PersistentSortedMap.class, Map.class); addDefaultImplementation(PersistentSet.class, Set.class); addDefaultImplementation(PersistentSortedSet.class, Set.class); addDefaultImplementation(ArrayList.class, List.class); registerConverter(new CollectionConverter(getMapper()) { @Override public boolean canConvert(@SuppressWarnings("rawtypes") Class type) { return PersistentList.class == type || PersistentBag.class == type; } }); registerConverter(new MapConverter(getMapper()) { @Override public boolean canConvert(@SuppressWarnings("rawtypes") Class type) { return PersistentMap.class == type; } }); } }
Base
1
public boolean isIgnoreComments() { return ignoreComments; }
Base
1
public String render(TemplateEngineTypeEnum engineType, String templateContent, Map<String, Object> context) { if (StrUtil.isEmpty(templateContent)) { return StrUtil.EMPTY; } TemplateEngine templateEngine = templateEngineMap.get(engineType); Assert.notNull(templateEngine, "未找到对应的模板引擎:{}", engineType); return templateEngine.render(templateContent, context); }
Class
2
public void subValidateFail(ViolationCollector col) { col.addViolation(FAILED+"subclass"); }
Class
2
private String deflateAndEncode(byte[] result) { Deflater deflater = new Deflater(Deflater.DEFLATED, true); deflater.setInput(result); deflater.finish(); byte[] deflatedResult = new byte[result.length]; int length = deflater.deflate(deflatedResult); deflater.end(); byte[] src = Arrays.copyOf(deflatedResult, length); return Base64.getEncoder().encodeToString(src); }
Base
1
private Map<String, Argument<?>> initializeTypeParameters(Argument[] genericTypes) { Map<String, Argument<?>> typeParameters; if (genericTypes != null && genericTypes.length > 0) { typeParameters = new LinkedHashMap<>(genericTypes.length); for (Argument genericType : genericTypes) { typeParameters.put(genericType.getName(), genericType); } } else { typeParameters = Collections.emptyMap(); } return typeParameters; }
Class
2
public void setEncoding(String encoding) { this.encoding = encoding; }
Base
1
public void export(Media media, ManifestBuilder manifest, File mediaArchiveDirectory, Locale locale) { EfficiencyStatement statement = null; if(StringHelper.containsNonWhitespace(media.getContent())) { try { statement = (EfficiencyStatement)myXStream.fromXML(media.getContent()); } catch (Exception e) { log.error("Cannot load efficiency statement from artefact", e); } } if(statement != null) { List<Map<String,Object>> assessmentNodes = statement.getAssessmentNodes(); List<AssessmentNodeData> assessmentNodeList = AssessmentHelper.assessmentNodeDataMapToList(assessmentNodes); SyntheticUserRequest ureq = new SyntheticUserRequest(media.getAuthor(), locale); IdentityAssessmentOverviewController details = new IdentityAssessmentOverviewController(ureq, new WindowControlMocker(), assessmentNodeList); super.exportContent(media, details.getInitialComponent(), null, mediaArchiveDirectory, locale); } }
Base
1
private static void appendHexNibble(StringBuilder buf, int nibble) { if (nibble < 10) { buf.append((char) ('0' + nibble)); } else { buf.append((char) ('A' + nibble - 10)); } }
Base
1
public RainbowParameters(int[] vi) { this.vi = vi; try { checkParams(); } catch (Exception e) { e.printStackTrace(); } }
Base
1
public static void execute(String url, String proxyHost, int proxyPort, String proxyUsername, String proxyPassword, String terminalWidth) { initializeSsl(); HttpURLConnection conn = createHttpUrlConnection(convertToUrl(url), proxyHost, proxyPort, proxyUsername, proxyPassword); conn.setInstanceFollowRedirects(false); setRequestMethod(conn, Utils.RequestMethod.GET); handleResponse(conn, getStatusCode(conn), terminalWidth); Authenticator.setDefault(null); }
Base
1
public void testQuoteWorkingDirectoryAndExecutable() { Shell sh = newShell(); sh.setWorkingDirectory( "/usr/local/bin" ); sh.setExecutable( "chmod" ); String executable = StringUtils.join( sh.getShellCommandLine( new String[]{} ).iterator(), " " ); assertEquals( "/bin/sh -c cd /usr/local/bin && chmod", executable ); }
Base
1
public void configure(ICourse course, CourseNode newNode, ModuleConfiguration moduleConfig) { if(displayType != null && (STCourseNodeEditController.CONFIG_VALUE_DISPLAY_TOC.equals(displayType) || STCourseNodeEditController.CONFIG_VALUE_DISPLAY_PEEKVIEW.equals(displayType) || STCourseNodeEditController.CONFIG_VALUE_DISPLAY_FILE.equals(displayType))) { moduleConfig.setStringValue(STCourseNodeEditController.CONFIG_KEY_DISPLAY_TYPE, displayType); } if(STCourseNodeEditController.CONFIG_VALUE_DISPLAY_FILE.equals(moduleConfig.getStringValue(STCourseNodeEditController.CONFIG_KEY_DISPLAY_TYPE))) { if(in != null && StringHelper.containsNonWhitespace(filename)) { VFSContainer rootContainer = course.getCourseFolderContainer(); VFSLeaf singleFile = (VFSLeaf) rootContainer.resolve("/" + filename); if (singleFile == null) { singleFile = rootContainer.createChildLeaf("/" + filename); } moduleConfig.set(STCourseNodeEditController.CONFIG_KEY_FILE, "/" + filename); OutputStream out = singleFile.getOutputStream(false); FileUtils.copy(in, out); FileUtils.closeSafely(out); FileUtils.closeSafely(in); } else if (StringHelper.containsNonWhitespace(filename)) { VFSContainer rootContainer = course.getCourseFolderContainer(); VFSLeaf singleFile = (VFSLeaf) rootContainer.resolve("/" + filename); if(singleFile != null) { moduleConfig.set(STCourseNodeEditController.CONFIG_KEY_FILE, "/" + filename); } } } }
Base
1
public boolean isIncludeInternalDTDDeclarations() { return includeInternalDTDDeclarations; }
Base
1
private String doResolveSqlDriverNameFromJar(File driverFile) { JarFile jarFile = null; try { jarFile = new JarFile(driverFile); } catch (IOException e) { log.error("resolve driver class name error", e); throw DomainErrors.DRIVER_CLASS_NAME_OBTAIN_ERROR.exception(e.getMessage()); } final JarFile driverJar = jarFile; String driverClassName = jarFile.stream() .filter(entry -> entry.getName().contains("META-INF/services/java.sql.Driver")) .findFirst() .map(entry -> { InputStream stream = null; BufferedReader reader = null; try { stream = driverJar.getInputStream(entry); reader = new BufferedReader(new InputStreamReader(stream)); return reader.readLine(); } catch (IOException e) { log.error("resolve driver class name error", e); throw DomainErrors.DRIVER_CLASS_NAME_OBTAIN_ERROR.exception(e.getMessage()); } finally { IOUtils.closeQuietly(reader, ex -> log.error("close reader error", ex)); } }) .orElseThrow(DomainErrors.DRIVER_CLASS_NAME_OBTAIN_ERROR::exception); IOUtils.closeQuietly(jarFile, ex -> log.error("close jar file error", ex)); return driverClassName; }
Class
2
public void testRenameTo() throws Exception { TestHttpData test = new TestHttpData("test", UTF_8, 0); try { File tmpFile = File.createTempFile(UUID.randomUUID().toString(), ".tmp"); tmpFile.deleteOnExit(); final int totalByteCount = 4096; byte[] bytes = new byte[totalByteCount]; PlatformDependent.threadLocalRandom().nextBytes(bytes); ByteBuf content = Unpooled.wrappedBuffer(bytes); test.setContent(content); boolean succ = test.renameTo(tmpFile); assertTrue(succ); FileInputStream fis = new FileInputStream(tmpFile); try { byte[] buf = new byte[totalByteCount]; int count = 0; int offset = 0; int size = totalByteCount; while ((count = fis.read(buf, offset, size)) > 0) { offset += count; size -= count; if (offset >= totalByteCount || size <= 0) { break; } } assertArrayEquals(bytes, buf); assertEquals(0, fis.available()); } finally { fis.close(); } } finally { //release the ByteBuf in AbstractMemoryHttpData test.delete(); } }
Base
1
public void testMatchType() { JWKMatcher matcher = new JWKMatcher.Builder().keyType(KeyType.RSA).build(); assertTrue(matcher.matches(new RSAKey.Builder(new Base64URL("n"), new Base64URL("e")).keyID("1").build())); assertFalse(matcher.matches(new ECKey.Builder(ECKey.Curve.P_256, new Base64URL("x"), new Base64URL("y")).keyID("2").build())); assertEquals("kty=RSA", matcher.toString()); }
Base
1
public static HColor unlinear(HColor color1, HColor color2, int completion) { if (completion == 0) { return color1; } if (completion == 100) { return color2; } if (color1 instanceof HColorSimple && color2 instanceof HColorSimple) { return HColorSimple.unlinear((HColorSimple) color1, (HColorSimple) color2, completion); } return color1; }
Base
1
public boolean checkUrlParameter(String url) { if (url != null) { try { URL parsedUrl = new URL(url); String protocol = parsedUrl.getProtocol(); String host = parsedUrl.getHost().toLowerCase(); return (protocol.equals("http") || protocol.equals("https")) && !host.endsWith(".internal") && !host.endsWith(".local") && !host.contains("localhost") && !host.startsWith("0.") // 0.0.0.0/8 && !host.startsWith("10.") // 10.0.0.0/8 && !host.startsWith("127.") // 127.0.0.0/8 && !host.startsWith("169.254.") // 169.254.0.0/16 && !host.startsWith("172.16.") // 172.16.0.0/12 && !host.startsWith("172.17.") // 172.16.0.0/12 && !host.startsWith("172.18.") // 172.16.0.0/12 && !host.startsWith("172.19.") // 172.16.0.0/12 && !host.startsWith("172.20.") // 172.16.0.0/12 && !host.startsWith("172.21.") // 172.16.0.0/12 && !host.startsWith("172.22.") // 172.16.0.0/12 && !host.startsWith("172.23.") // 172.16.0.0/12 && !host.startsWith("172.24.") // 172.16.0.0/12 && !host.startsWith("172.25.") // 172.16.0.0/12 && !host.startsWith("172.26.") // 172.16.0.0/12 && !host.startsWith("172.27.") // 172.16.0.0/12 && !host.startsWith("172.28.") // 172.16.0.0/12 && !host.startsWith("172.29.") // 172.16.0.0/12 && !host.startsWith("172.30.") // 172.16.0.0/12 && !host.startsWith("172.31.") // 172.16.0.0/12 && !host.startsWith("192.0.0.") // 192.0.0.0/24 && !host.startsWith("192.168.") // 192.168.0.0/16 && !host.startsWith("198.18.") // 198.18.0.0/15 && !host.startsWith("198.19.") // 198.18.0.0/15 && !host.endsWith(".arpa"); // reverse domain (needed?) } catch (MalformedURLException e) { return false; } } else { return false; } }
Base
1
public void existingDocumentFromUI() throws Exception { // current document = xwiki:Main.WebHome DocumentReference documentReference = new DocumentReference("xwiki", Arrays.asList("Main"), "WebHome"); XWikiDocument document = mock(XWikiDocument.class); when(document.getDocumentReference()).thenReturn(documentReference); when(document.isNew()).thenReturn(false); when(document.getLocalReferenceMaxLength()).thenReturn(255); context.setDoc(document); // Submit from the UI spaceReference=X&name=Y when(mockRequest.getParameter("spaceReference")).thenReturn("X"); when(mockRequest.getParameter("name")).thenReturn("Y"); // Run the action String result = action.render(context); // The tests are below this line! // Verify null is returned (this means the response has been returned) assertNull(result); // Note: We are creating X.Y.WebHome since we default to non-terminal documents. verify(mockURLFactory).createURL("X.Y", "WebHome", "edit", "template=&parent=Main.WebHome&title=Y", null, "xwiki", context); }
Class
2
public PersistedMapper persistMapper(String sessionId, String mapperId, Serializable mapper, int expirationTime) { PersistedMapper m = new PersistedMapper(); m.setMapperId(mapperId); Date currentDate = new Date(); m.setLastModified(currentDate); if(expirationTime > 0) { Calendar cal = Calendar.getInstance(); cal.setTime(currentDate); cal.add(Calendar.SECOND, expirationTime); m.setExpirationDate(cal.getTime()); } m.setOriginalSessionId(sessionId); String configuration = XStreamHelper.createXStreamInstance().toXML(mapper); m.setXmlConfiguration(configuration); dbInstance.getCurrentEntityManager().persist(m); return m; }
Base
1
public void newDocumentButNonTerminalFromURL() throws Exception { // new document = xwiki:X.Y DocumentReference documentReference = new DocumentReference("xwiki", Arrays.asList("X"), "Y"); XWikiDocument document = mock(XWikiDocument.class); when(document.getDocumentReference()).thenReturn(documentReference); when(document.isNew()).thenReturn(true); when(document.getLocalReferenceMaxLength()).thenReturn(255); context.setDoc(document); // Pass the tocreate=nonterminal request parameter when(mockRequest.getParameter("tocreate")).thenReturn("nonterminal"); // 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); verify(mockURLFactory).createURL("X.Y", "WebHome", "edit", "template=&parent=Main.WebHome&title=Y", null, "xwiki", context); }
Class
2
public void testOfAsciiString() { // Should produce a lower-cased AsciiString. final AsciiString mixedCased = AsciiString.of("Foo"); assertThat((Object) HttpHeaderNames.of(mixedCased)).isNotSameAs(mixedCased); assertThat(HttpHeaderNames.of(mixedCased).toString()).isEqualTo("foo"); // Should not produce a new instance for an AsciiString that's already lower-cased. final AsciiString lowerCased = AsciiString.of("foo"); assertThat((Object) HttpHeaderNames.of(lowerCased)).isSameAs(lowerCased); // Should reuse known header name instances. assertThat((Object) HttpHeaderNames.of(AsciiString.of("date"))).isSameAs(HttpHeaderNames.DATE); }
Class
2
public void testCurveCheckNegative_P256_attackPt1() throws Exception { // The malicious JWE contains a public key with order 113 String maliciousJWE = "eyJhbGciOiJFQ0RILUVTK0ExMjhLVyIsImVuYyI6IkExMjhDQkMtSFMyNTYiLCJlcGsiOnsia3R5IjoiRUMiLCJ4IjoiZ1RsaTY1ZVRRN3otQmgxNDdmZjhLM203azJVaURpRzJMcFlrV0FhRkpDYyIsInkiOiJjTEFuakthNGJ6akQ3REpWUHdhOUVQclJ6TUc3ck9OZ3NpVUQta2YzMEZzIiwiY3J2IjoiUC0yNTYifX0.qGAdxtEnrV_3zbIxU2ZKrMWcejNltjA_dtefBFnRh9A2z9cNIqYRWg.pEA5kX304PMCOmFSKX_cEg.a9fwUrx2JXi1OnWEMOmZhXd94-bEGCH9xxRwqcGuG2AMo-AwHoljdsH5C_kcTqlXS5p51OB1tvgQcMwB5rpTxg.72CHiYFecyDvuUa43KKT6w"; JWEObject jweObject = JWEObject.parse(maliciousJWE); ECPublicKey ephemeralPublicKey = jweObject.getHeader().getEphemeralPublicKey().toECPublicKey(); ECPrivateKey privateKey = generateECPrivateKey(ECKey.Curve.P_256); try { ECDH.ensurePointOnCurve(ephemeralPublicKey, privateKey); fail(); } catch (JOSEException e) { assertEquals("Invalid ephemeral public key: Point not on expected curve", e.getMessage()); } }
Base
1
public void testSelectByOperationsNotSpecifiedOrSign() { JWKSelector selector = new JWKSelector(new JWKMatcher.Builder().keyOperations(KeyOperation.SIGN, null).build()); List<JWK> keyList = new ArrayList<>(); keyList.add(new RSAKey.Builder(new Base64URL("n"), new Base64URL("e")).keyID("1") .keyOperations(new HashSet<>(Collections.singletonList(KeyOperation.SIGN))).build()); keyList.add(new ECKey.Builder(ECKey.Curve.P_256, new Base64URL("x"), new Base64URL("y")).keyID("2").build()); keyList.add(new ECKey.Builder(ECKey.Curve.P_256, new Base64URL("x"), new Base64URL("y")).keyID("3") .keyOperations(new HashSet<>(Collections.singletonList(KeyOperation.ENCRYPT))).build()); JWKSet jwkSet = new JWKSet(keyList); List<JWK> matches = selector.select(jwkSet); RSAKey key1 = (RSAKey)matches.get(0); assertEquals(KeyType.RSA, key1.getKeyType()); assertEquals("1", key1.getKeyID()); ECKey key2 = (ECKey)matches.get(1); assertEquals(KeyType.EC, key2.getKeyType()); assertEquals("2", key2.getKeyID()); assertEquals(2, matches.size()); }
Base
1
public static CharSequence createOptimized(String value) { return io.netty.handler.codec.http.HttpHeaders.newEntity(value); }
Class
2
public void newDocumentFromURLTemplateProviderSpecifiedNonTerminalButOverriddenFromUITerminal() throws Exception { // new document = xwiki:X.Y DocumentReference documentReference = new DocumentReference("xwiki", "X", "Y"); XWikiDocument document = mock(XWikiDocument.class); when(document.getDocumentReference()).thenReturn(documentReference); when(document.isNew()).thenReturn(true); when(document.getLocalReferenceMaxLength()).thenReturn(255); context.setDoc(document); // Specifying a template provider in the URL: templateprovider=XWiki.MyTemplateProvider String templateProviderFullName = "XWiki.MyTemplateProvider"; when(mockRequest.getParameter("templateprovider")).thenReturn(templateProviderFullName); when(mockRequest.getParameter("tocreate")).thenReturn("terminal"); // Mock 1 existing template provider 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 as terminal and using a template, as specified in the template // provider. verify(mockURLFactory).createURL("X", "Y", "edit", "template=XWiki.MyTemplate&parent=Main.WebHome&title=Y", null, "xwiki", context); }
Class
2
public void headerMultipleContentLengthValidationShouldPropagate() { LastInboundHandler inboundHandler = new LastInboundHandler(); request.addLong(HttpHeaderNames.CONTENT_LENGTH, 0); request.addLong(HttpHeaderNames.CONTENT_LENGTH, 1); Http2StreamChannel channel = newInboundStream(3, false, inboundHandler); try { inboundHandler.checkException(); fail(); } catch (Exception e) { assertThat(e, CoreMatchers.<Exception>instanceOf(StreamException.class)); } assertNull(inboundHandler.readInbound()); assertFalse(channel.isActive()); }
Base
1
public void performTest() throws Exception { testKeyConversion(); testAdaptiveKeyConversion(); decodeTest(); testECDSA239bitPrime(); testECDSA239bitBinary(); testGeneration(); testKeyPairGenerationWithOIDs(); testNamedCurveParameterPreservation(); testNamedCurveSigning(); testBSI(); testMQVwithHMACOnePass(); testAlgorithmParameters(); }
Base
1
public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException { Integer sc = (Integer) request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE); String msg = (String) request.getAttribute(RequestDispatcher.ERROR_MESSAGE); Throwable err = (Throwable) request.getAttribute(RequestDispatcher.ERROR_EXCEPTION); StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); if (err != null) { err.printStackTrace(pw); } else { pw.println("(none)"); } pw.flush(); // If we are here there was no error servlet, so show the default error page String output = Launcher.RESOURCES.getString("WinstoneResponse.ErrorPage", new String[] { sc + "", (msg == null ? "" : msg), sw.toString(), Launcher.RESOURCES.getString("ServerVersion"), "" + new Date() }); response.setContentLength(output.getBytes(response.getCharacterEncoding()).length); Writer out = response.getWriter(); out.write(output); out.flush(); }
Base
1
protected XMLReader createXMLReader() throws SAXException { return SAXHelper.createXMLReader(isValidating()); }
Base
1
public static int beta() { final int beta = 1; return beta; }
Base
1
private void handle(ServletRequestHandler pReqHandler,HttpServletRequest pReq, HttpServletResponse pResp) throws IOException { JSONAware json = null; try { // Check access policy requestHandler.checkAccess(allowDnsReverseLookup ? pReq.getRemoteHost() : null, pReq.getRemoteAddr(), getOriginOrReferer(pReq)); // Remember the agent URL upon the first request. Needed for discovery updateAgentDetailsIfNeeded(pReq); // Dispatch for the proper HTTP request method json = handleSecurely(pReqHandler, pReq, pResp); } catch (Throwable exp) { json = requestHandler.handleThrowable( exp instanceof RuntimeMBeanException ? ((RuntimeMBeanException) exp).getTargetException() : exp); } finally { setCorsHeader(pReq, pResp); if (json == null) { json = requestHandler.handleThrowable(new Exception("Internal error while handling an exception")); } sendResponse(pResp, pReq, json); } }
Base
1
private final HColor getLineColor(ISkinParam skinParam, Style style) { if (colors == null || colors.getColor(ColorType.LINE) == null) { if (UseStyle.useBetaStyle() == false) return HColorUtils.COL_038048; return style.value(PName.LineColor).asColor(skinParam.getThemeStyle(), skinParam.getIHtmlColorSet()); } return colors.getColor(ColorType.LINE); }
Base
1
static DataSource lookupDataSource(Hints hints) throws FactoryException { Object hint = hints.get(Hints.EPSG_DATA_SOURCE); if (hint instanceof DataSource) { return (DataSource) hint; } else if (hint instanceof String) { String name = (String) hint; InitialContext context; try { context = GeoTools.getInitialContext(); // name = GeoTools.fixName( context, name ); return (DataSource) context.lookup(name); } catch (Exception e) { throw new FactoryException("EPSG_DATA_SOURCE '" + name + "' not found:" + e, e); } } throw new FactoryException("EPSG_DATA_SOURCE must be provided"); }
Class
2
public void setExpirationTime(int expirationTime) { this.expirationTime = expirationTime; }
Class
2
protected String getExecutionPreamble() { if ( getWorkingDirectoryAsString() == null ) { return null; } String dir = getWorkingDirectoryAsString(); StringBuilder sb = new StringBuilder(); sb.append( "cd " ); sb.append( unifyQuotes( dir ) ); sb.append( " && " ); return sb.toString(); }
Base
1
public static Object readObject(XStream xStream, InputStream is) { try(InputStreamReader isr = new InputStreamReader(is, ENCODING);) { return xStream.fromXML(isr); } catch (Exception e) { throw new OLATRuntimeException(XStreamHelper.class, "could not read Object from inputstream: " + is, e); } }
Base
1
public void testDirectContextUsage() throws Exception { assertThat(ConstraintViolations.format(validator.validate(new DirectContextExample()))) .containsExactlyInAnyOrder(FAILED_RESULT); assertThat(TestLoggerFactory.getAllLoggingEvents()) .isEmpty(); }
Class
2
public void cors() { InputStream is = getClass().getResourceAsStream("/allow-origin1.xml"); PolicyRestrictor restrictor = new PolicyRestrictor(is); assertTrue(restrictor.isCorsAccessAllowed("http://bla.com")); assertFalse(restrictor.isCorsAccessAllowed("http://www.jolokia.org")); assertTrue(restrictor.isCorsAccessAllowed("https://www.consol.de")); }
Compound
4
public static void loadBouncyCastle() { new PersistedProperties(event -> { // }); }
Base
1
public boolean isCorsAccessAllowed(String pOrigin) { return corsChecker.check(pOrigin); }
Compound
4
public void switchToConversation(Conversation conversation, String text) { switchToConversation(conversation, text, false, null, false); }
Class
2
public int hashCode() { return new HashCodeBuilder(17, 37) .append(userReference) .append(userEmail) .append(verificationCode) .toHashCode(); }
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
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
public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } DefaultResetPasswordRequestResponse that = (DefaultResetPasswordRequestResponse) o; return new EqualsBuilder() .append(userReference, that.userReference) .append(userEmail, that.userEmail) .append(verificationCode, that.verificationCode) .isEquals(); }
Base
1
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // to get values from the login page String userName = request.getParameter("aname"); String password = sha.getSHA(request.getParameter("pass")); // String password = request.getParameter("pass"); String rememberMe = request.getParameter("remember-me"); // validation if (adminDao.loginValidate(userName, password)) { if (rememberMe != null) { Cookie cookie1 = new Cookie("uname", userName); Cookie cookie2 = new Cookie("pass", password); cookie1.setMaxAge(24 * 60 * 60); cookie2.setMaxAge(24 * 60 * 60); response.addCookie(cookie1); response.addCookie(cookie2); } // to display the name of logged-in person in home page HttpSession session = request.getSession(); session.setAttribute("username", userName); /* * RequestDispatcher rd = * request.getRequestDispatcher("AdminController?actions=admin_list"); * rd.forward(request, response); */ response.sendRedirect("AdminController?actions=admin_list"); } else { RequestDispatcher rd = request.getRequestDispatcher("adminlogin.jsp"); request.setAttribute("loginFailMsg", "Invalid Username or Password !!"); rd.include(request, response); } }
Variant
0
public void translate(ServerDifficultyPacket packet, GeyserSession session) { SetDifficultyPacket setDifficultyPacket = new SetDifficultyPacket(); setDifficultyPacket.setDifficulty(packet.getDifficulty().ordinal()); session.sendUpstreamPacket(setDifficultyPacket); session.getWorldCache().setDifficulty(packet.getDifficulty()); }
Class
2
public String getHeader(String name) { //logger.info("Ineader .. parameter ......."); String value = super.getHeader(name); if (value == null) return null; //logger.info("Ineader RequestWrapper ........... value ...."); return cleanXSS(value); }
Base
1
public Document read(InputStream in) throws DocumentException { InputSource source = new InputSource(in); if (this.encoding != null) { source.setEncoding(this.encoding); } return read(source); }
Base
1
final void addObject(CharSequence name, Object... values) { final AsciiString normalizedName = normalizeName(name); requireNonNull(values, "values"); for (Object v : values) { requireNonNullElement(values, v); addObject(normalizedName, v); } }
Class
2
public Response workspaceClientEnqueue(@FormParam(WorkSpaceAdapter.CLIENT_NAME) String clientName, @FormParam(WorkSpaceAdapter.WORK_BUNDLE_OBJ) String workBundleString) { logger.debug("TPWorker incoming execute! check prio={}", Thread.currentThread().getPriority()); // TODO Doesn't look like anything is actually calling this, should we remove this? final boolean success; try { // Look up the place reference final String nsName = KeyManipulator.getServiceLocation(clientName); final IPickUpSpace place = (IPickUpSpace) Namespace.lookup(nsName); if (place == null) { throw new IllegalArgumentException("No client place found using name " + clientName); } final ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(workBundleString.getBytes("8859_1"))); WorkBundle paths = (WorkBundle) ois.readObject(); success = place.enque(paths); } catch (Exception e) { logger.warn("WorkSpaceClientEnqueWorker exception", e); return Response.serverError().entity("WorkSpaceClientEnqueWorker exception:\n" + e.getMessage()).build(); } if (success) { // old success from WorkSpaceClientEnqueWorker // return WORKER_SUCCESS; return Response.ok().entity("Successful add to the PickUpPlaceClient queue").build(); } else { // old failure from WorkSpaceClientEnqueWorker // return new WorkerStatus(WorkerStatus.FAILURE, "WorkSpaceClientEnqueWorker failed, queue full"); return Response.serverError().entity("WorkSpaceClientEnqueWorker failed, queue full").build(); } }
Base
1
setImmediate(() => { if (!this.pendingPublishRequestCount) { return; } const starving_subscription = this._find_starving_subscription(); if (starving_subscription) { doDebug && debugLog(chalk.bgWhite.red("feeding most late subscription subscriptionId = "), starving_subscription.id); starving_subscription.process_subscription(); } });
Class
2
public UPathHand(UPath source, Random rnd) { final UPath result = new UPath(); Point2D last = new Point2D.Double(); for (USegment segment : source) { final USegmentType type = segment.getSegmentType(); if (type == USegmentType.SEG_MOVETO) { final double x = segment.getCoord()[0]; final double y = segment.getCoord()[1]; result.moveTo(x, y); last = new Point2D.Double(x, y); } else if (type == USegmentType.SEG_CUBICTO) { final double x2 = segment.getCoord()[4]; final double y2 = segment.getCoord()[5]; final HandJiggle jiggle = HandJiggle.create(last, 2.0, rnd); final CubicCurve2D tmp = new CubicCurve2D.Double(last.getX(), last.getY(), segment.getCoord()[0], segment.getCoord()[1], segment.getCoord()[2], segment.getCoord()[3], x2, y2); jiggle.curveTo(tmp); jiggle.appendTo(result); last = new Point2D.Double(x2, y2); } else if (type == USegmentType.SEG_LINETO) { final double x = segment.getCoord()[0]; final double y = segment.getCoord()[1]; final HandJiggle jiggle = new HandJiggle(last.getX(), last.getY(), defaultVariation, rnd); jiggle.lineTo(x, y); for (USegment seg2 : jiggle.toUPath()) { if (seg2.getSegmentType() == USegmentType.SEG_LINETO) { result.lineTo(seg2.getCoord()[0], seg2.getCoord()[1]); } } last = new Point2D.Double(x, y); } else { this.path = source; return; } } this.path = result; this.path.setDeltaShadow(source.getDeltaShadow()); }
Base
1
public void addViolation(String propertyName, Integer index, String message) { violationOccurred = true; String messageTemplate = escapeEl(message); context.buildConstraintViolationWithTemplate(messageTemplate) .addPropertyNode(propertyName) .addBeanNode().inIterable().atIndex(index) .addConstraintViolation(); }
Class
2
public boolean isValid(Object value, ConstraintValidatorContext context) { if (value != null && StringUtils.isNotEmpty(String.valueOf(value))) { return true; } String errorMessage = String.format("Expected not empty value, got '%s'", value); LOG.warn(errorMessage); context.buildConstraintViolationWithTemplate(errorMessage).addConstraintViolation(); return false; }
Class
2
public CreateCommentResponse save(CreateCommentRequest createCommentRequest) { CreateCommentResponse createCommentResponse = new CreateCommentResponse(); if (createCommentRequest.getLogId() != null && createCommentRequest.getComment() != null) { if (isAllowComment(Integer.valueOf(createCommentRequest.getLogId()))) { String comment = Jsoup.clean(createCommentRequest.getComment(), Whitelist.basic()); if (comment.length() > 0 && !ParseUtil.isGarbageComment(comment)) { new Comment().set("userHome", createCommentRequest.getUserHome()) .set("userMail", createCommentRequest.getComment()) .set("userIp", createCommentRequest.getIp()) .set("userName", createCommentRequest.getUserName()) .set("logId", createCommentRequest.getLogId()) .set("userComment", comment) .set("user_agent", createCommentRequest.getUserAgent()) .set("reply_id", createCommentRequest.getReplyId()) .set("commTime", new Date()).set("hide", 1).save(); } else { createCommentResponse.setError(1); createCommentResponse.setMessage(""); } } else { createCommentResponse.setError(1); createCommentResponse.setMessage(""); } } else { createCommentResponse.setError(1); createCommentResponse.setMessage(""); } Log log = new Log().findByIdOrAlias(createCommentRequest.getLogId()); if (log != null) { createCommentResponse.setAlias(log.getStr("alias")); } return createCommentResponse; }
Base
1
public static void unzipFilesToPath(String jarPath, String destinationDir) throws IOException { File file = new File(jarPath); try (JarFile jar = new JarFile(file)) { // fist get all directories, // then make those directory on the destination Path /*for (Enumeration<JarEntry> enums = jar.entries(); enums.hasMoreElements(); ) { JarEntry entry = (JarEntry) enums.nextElement(); String fileName = destinationDir + File.separator + entry.getName(); File f = new File(fileName); if (fileName.endsWith("/")) { f.mkdirs(); } }*/ //now create all files for (Enumeration<JarEntry> enums = jar.entries(); enums.hasMoreElements(); ) { JarEntry entry = enums.nextElement(); String fileName = destinationDir + File.separator + entry.getName(); File f = new File(fileName); if (!f.getCanonicalPath().startsWith(destinationDir)) { System.out.println("Zip Slip exploit detected. Skipping entry " + entry.getName()); continue; } File parent = f.getParentFile(); if (!parent.exists()) { parent.mkdirs(); } if (!fileName.endsWith("/")) { try (InputStream is = jar.getInputStream(entry); FileOutputStream fos = new FileOutputStream(f)) { // write contents of 'is' to 'fos' while (is.available() > 0) { fos.write(is.read()); } } } } } }
Base
1
protected String getContent(SxSource sxSource, FilesystemExportContext exportContext) { String content; // We know we're inside a SX file located at "<S|J>sx/<Space>/<Page>/<s|j>sx<NNN>.<css|js>". Inside this CSS // there can be URLs and we need to ensure that the prefix for these URLs lead to the root of the path, i.e. // 3 levels up ("../../../"). // To make this happen we reuse the Doc Parent Level from FileSystemExportContext to a fixed value of 3. // We also make sure to put back the original value int originalDocParentLevel = exportContext.getDocParentLevel(); try { exportContext.setDocParentLevels(3); content = sxSource.getContent(); } finally { exportContext.setDocParentLevels(originalDocParentLevel); } return content; }
Base
1
public void translate(ServerEntityCollectItemPacket packet, GeyserSession session) { // Collected entity is the other entity Entity collectedEntity = session.getEntityCache().getEntityByJavaId(packet.getCollectedEntityId()); if (collectedEntity == null) return; // Collector is the entity 'picking up' the item Entity collectorEntity; if (packet.getCollectorEntityId() == session.getPlayerEntity().getEntityId()) { collectorEntity = session.getPlayerEntity(); } else { collectorEntity = session.getEntityCache().getEntityByJavaId(packet.getCollectorEntityId()); } if (collectorEntity == null) return; if (collectedEntity instanceof ExpOrbEntity) { // Player just picked up an experience orb LevelEventPacket xpPacket = new LevelEventPacket(); xpPacket.setType(LevelEventType.SOUND_EXPERIENCE_ORB_PICKUP); xpPacket.setPosition(collectedEntity.getPosition()); xpPacket.setData(0); session.sendUpstreamPacket(xpPacket); } else { // Item is being picked up (visual only) TakeItemEntityPacket takeItemEntityPacket = new TakeItemEntityPacket(); takeItemEntityPacket.setRuntimeEntityId(collectorEntity.getGeyserId()); takeItemEntityPacket.setItemRuntimeEntityId(collectedEntity.getGeyserId()); session.sendUpstreamPacket(takeItemEntityPacket); } }
Class
2
public void testAddSelf() { final HttpHeadersBase headers = newEmptyHeaders(); headers.add(headers); }
Class
2
private HColor getColor(ColorParam colorParam, Stereotype stereo) { final ISkinParam skinParam = diagram.getSkinParam(); return rose.getHtmlColor(skinParam, stereo, colorParam); }
Base
1
public static Object instantiate(String classname, Properties info, boolean tryString, @Nullable String stringarg) throws ClassNotFoundException, SecurityException, NoSuchMethodException, IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException { @Nullable Object[] args = {info}; Constructor<?> ctor = null; Class<?> cls = Class.forName(classname); try { ctor = cls.getConstructor(Properties.class); } catch (NoSuchMethodException ignored) { } if (tryString && ctor == null) { try { ctor = cls.getConstructor(String.class); args = new String[]{stringarg}; } catch (NoSuchMethodException ignored) { } } if (ctor == null) { ctor = cls.getConstructor(); args = new Object[0]; } return ctor.newInstance(args); }
Class
2
private DocumentReferenceResolver<String> getCurrentMixedDocumentReferenceResolver() { return Utils.getComponent(DocumentReferenceResolver.TYPE_STRING, CURRENT_MIXED_RESOLVER_HINT); }
Class
2
public void translate(ServerUnloadChunkPacket packet, GeyserSession session) { session.getChunkCache().removeChunk(packet.getX(), packet.getZ()); //Checks if a skull is in an unloaded chunk then removes it Iterator<Vector3i> iterator = session.getSkullCache().keySet().iterator(); while (iterator.hasNext()) { Vector3i position = iterator.next(); if ((position.getX() >> 4) == packet.getX() && (position.getZ() >> 4) == packet.getZ()) { session.getSkullCache().get(position).despawnEntity(session); iterator.remove(); } } // Do the same thing with lecterns iterator = session.getLecternCache().iterator(); while (iterator.hasNext()) { Vector3i position = iterator.next(); if ((position.getX() >> 4) == packet.getX() && (position.getZ() >> 4) == packet.getZ()) { iterator.remove(); } } }
Class
2
public String toString() { if (query == null) { return path; } return path + "?" + query; }
Base
1
public void translate(ServerEntityVelocityPacket packet, GeyserSession session) { Entity entity = session.getEntityCache().getEntityByJavaId(packet.getEntityId()); if (packet.getEntityId() == session.getPlayerEntity().getEntityId()) { entity = session.getPlayerEntity(); } if (entity == null) return; entity.setMotion(Vector3f.from(packet.getMotionX(), packet.getMotionY(), packet.getMotionZ())); if (entity == session.getRidingVehicleEntity() && entity instanceof AbstractHorseEntity) { // Horses for some reason teleport back when a SetEntityMotionPacket is sent while // a player is riding on them. Java clients seem to ignore it anyways. return; } if (entity instanceof ItemEntity) { // Don't bother sending entity motion packets for items // since the client doesn't seem to care return; } SetEntityMotionPacket entityMotionPacket = new SetEntityMotionPacket(); entityMotionPacket.setRuntimeEntityId(entity.getGeyserId()); entityMotionPacket.setMotion(entity.getMotion()); session.sendUpstreamPacket(entityMotionPacket); }
Class
2
private JsonNode yamlStreamToJson(InputStream yamlStream) { Yaml reader = new Yaml(); ObjectMapper mapper = new ObjectMapper(); return mapper.valueToTree(reader.load(yamlStream)); }
Base
1
public void testGetChunk() 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 buf1 = test.getChunk(1024); assertEquals(buf1.readerIndex(), 0); assertEquals(buf1.writerIndex(), 1024); ByteBuf buf2 = test.getChunk(1024); assertEquals(buf2.readerIndex(), 0); assertEquals(buf2.writerIndex(), 1024); assertFalse("Arrays should not be equal", Arrays.equals(ByteBufUtil.getBytes(buf1), ByteBufUtil.getBytes(buf2))); } finally { test.delete(); } }
Base
1
public File loadOrDownload(String databaseType, String driverFileUrl) { String filePath = driverFilePath(driverBaseDirectory, databaseType); Path path = Path.of(filePath); if (Files.exists(path)) { // ignore log.debug("{} already exists, ignore download from {}", filePath, driverFileUrl); return path.toFile(); } return this.doDownload(driverFileUrl, filePath); }
Class
2
public Directory read(final ImageInputStream input) throws IOException { Validate.notNull(input, "input"); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); try { // TODO: Consider parsing using SAX? // TODO: Determine encoding and parse using a Reader... // TODO: Refactor scanner to return inputstream? // TODO: Be smarter about ASCII-NULL termination/padding (the SAXParser aka Xerces DOMParser doesn't like it)... DocumentBuilder builder = factory.newDocumentBuilder(); builder.setErrorHandler(new DefaultHandler()); Document document = builder.parse(new InputSource(IIOUtil.createStreamAdapter(input))); // XMLSerializer serializer = new XMLSerializer(System.err, System.getProperty("file.encoding")); // serializer.serialize(document); String toolkit = getToolkit(document); Node rdfRoot = document.getElementsByTagNameNS(XMP.NS_RDF, "RDF").item(0); NodeList descriptions = document.getElementsByTagNameNS(XMP.NS_RDF, "Description"); return parseDirectories(rdfRoot, descriptions, toolkit); } catch (SAXException e) { throw new IIOException(e.getMessage(), e); } catch (ParserConfigurationException e) { throw new RuntimeException(e); // TODO: Or IOException? } }
Base
1
public void addViolation(String message) { violationOccurred = true; String messageTemplate = escapeEl(message); context.buildConstraintViolationWithTemplate(messageTemplate) .addConstraintViolation(); }
Class
2