code
stringlengths 12
2.05k
| label_name
stringclasses 5
values | label
int64 0
4
|
---|---|---|
public static IRubyObject from_document(ThreadContext context, IRubyObject klazz, IRubyObject document) {
XmlDocument doc = ((XmlDocument) ((XmlNode) document).document(context));
RubyArray errors = (RubyArray) doc.getInstanceVariable("@errors");
if (!errors.isEmpty()) {
throw ((XmlSyntaxError) errors.first()).toThrowable();
}
DOMSource source = new DOMSource(doc.getDocument());
IRubyObject uri = doc.url(context);
if (!uri.isNil()) {
source.setSystemId(uri.convertToString().asJavaString());
}
return getSchema(context, (RubyClass)klazz, source);
} | Base | 1 |
public PersistentTask createTask(String name, Serializable task,
Identity creator, OLATResource resource, String resSubPath, Date scheduledDate) {
PersistentTask ptask = new PersistentTask();
Date currentDate = new Date();
ptask.setCreationDate(currentDate);
ptask.setLastModified(currentDate);
ptask.setScheduledDate(scheduledDate);
ptask.setName(name);
ptask.setCreator(creator);
ptask.setResource(resource);
ptask.setResSubPath(resSubPath);
ptask.setStatus(TaskStatus.newTask);
ptask.setTask(xstream.toXML(task));
dbInstance.getCurrentEntityManager().persist(ptask);
return ptask;
} | Base | 1 |
public void render(HtmlRenderer renderer) {
if (isArtifactsDeleted || isEmpty()) {
HtmlElement element = p().content("Artifacts for this job instance are unavailable as they may have been <a href='" +
CurrentGoCDVersion.docsUrl("configuration/delete_artifacts.html") +
"' target='blank'>purged by Go</a> or deleted externally. "
+ "Re-run the stage or job to generate them again.");
element.render(renderer);
}
for (DirectoryEntry entry : this) {
entry.toHtml().render(renderer);
}
} | Base | 1 |
public static void main(
String[] args)
{
Security.addProvider(new BouncyCastleProvider());
runTest(new ECDSA5Test());
} | Base | 1 |
public void translate(ShowCreditsPacket packet, GeyserSession session) {
if (packet.getStatus() == ShowCreditsPacket.Status.END_CREDITS) {
ClientRequestPacket javaRespawnPacket = new ClientRequestPacket(ClientRequest.RESPAWN);
session.sendDownstreamPacket(javaRespawnPacket);
}
} | 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 Path getFilePath(String path) {
return baseDirPath.map(dir -> dir.resolve(path)).orElseGet(() -> Paths.get(path));
} | Base | 1 |
List<Modification> findRecentModifications(int count) {
// Currently impossible to check modifications on a remote repository.
InMemoryStreamConsumer consumer = inMemoryConsumer();
bombUnless(pull(consumer), "Failed to run hg pull command: " + consumer.getAllOutput());
CommandLine hg = hg("log", "--limit", String.valueOf(count), "-b", branch, "--style", templatePath());
return new HgModificationSplitter(execute(hg)).modifications();
} | Class | 2 |
public void translate(MobEquipmentPacket packet, GeyserSession session) {
if (!session.isSpawned() || packet.getHotbarSlot() > 8 ||
packet.getContainerId() != ContainerId.INVENTORY || session.getPlayerInventory().getHeldItemSlot() == packet.getHotbarSlot()) {
// For the last condition - Don't update the slot if the slot is the same - not Java Edition behavior and messes with plugins such as Grief Prevention
return;
}
// Send book update before switching hotbar slot
session.getBookEditCache().checkForSend();
session.getPlayerInventory().setHeldItemSlot(packet.getHotbarSlot());
ClientPlayerChangeHeldItemPacket changeHeldItemPacket = new ClientPlayerChangeHeldItemPacket(packet.getHotbarSlot());
session.sendDownstreamPacket(changeHeldItemPacket);
if (session.isSneaking() && session.getPlayerInventory().getItemInHand().getJavaId() == session.getItemMappings().getStoredItems().shield().getJavaId()) {
// Activate shield since we are already sneaking
// (No need to send a release item packet - Java doesn't do this when swapping items)
// Required to do it a tick later or else it doesn't register
session.getConnector().getGeneralThreadPool().schedule(() -> session.sendDownstreamPacket(new ClientPlayerUseItemPacket(Hand.MAIN_HAND)),
50, TimeUnit.MILLISECONDS);
}
// Java sends a cooldown indicator whenever you switch an item
CooldownUtils.sendCooldown(session);
// Update the interactive tag, if an entity is present
if (session.getMouseoverEntity() != null) {
InteractiveTagManager.updateTag(session, session.getMouseoverEntity());
}
} | Class | 2 |
public void testUpdateMapper_serializade() {
//create a mapper
String mapperId = UUID.randomUUID().toString();
String sessionId = UUID.randomUUID().toString().substring(0, 32);
PersistentMapper sMapper = new PersistentMapper("mapper-to-persist-bis");
PersistedMapper pMapper = mapperDao.persistMapper(sessionId, mapperId, sMapper, -1);
Assert.assertNotNull(pMapper);
dbInstance.commitAndCloseSession();
//load the mapper
PersistedMapper loadedMapper = mapperDao.loadByMapperId(mapperId);
Assert.assertNotNull(loadedMapper);
Object objReloaded = XStreamHelper.createXStreamInstance().fromXML(pMapper.getXmlConfiguration());
Assert.assertTrue(objReloaded instanceof PersistentMapper);
PersistentMapper sMapperReloaded = (PersistentMapper)objReloaded;
Assert.assertEquals("mapper-to-persist-bis", sMapperReloaded.getKey());
//update
PersistentMapper sMapper2 = new PersistentMapper("mapper-to-update");
boolean updated = mapperDao.updateConfiguration(mapperId, sMapper2, -1);
Assert.assertTrue(updated);
dbInstance.commitAndCloseSession();
//load the updated mapper
PersistedMapper loadedMapper2 = mapperDao.loadByMapperId(mapperId);
Assert.assertNotNull(loadedMapper2);
Object objReloaded2 = XStreamHelper.createXStreamInstance().fromXML(loadedMapper2.getXmlConfiguration());
Assert.assertTrue(objReloaded2 instanceof PersistentMapper);
PersistentMapper sMapperReloaded2 = (PersistentMapper)objReloaded2;
Assert.assertEquals("mapper-to-update", sMapperReloaded2.getKey());
} | Base | 1 |
void ampersand() {
final PathAndQuery res = PathAndQuery.parse("/&?a=1&a=2&b=3");
assertThat(res).isNotNull();
assertThat(res.path()).isEqualTo("/&");
assertThat(res.query()).isEqualTo("a=1&a=2&b=3");
// '%26' in a query string should never be decoded into '&'.
final PathAndQuery res2 = PathAndQuery.parse("/%26?a=1%26a=2&b=3");
assertThat(res2).isNotNull();
assertThat(res2.path()).isEqualTo("/&");
assertThat(res2.query()).isEqualTo("a=1%26a=2&b=3");
} | Base | 1 |
protected Details authenticate(String username, String password) throws AuthenticationException {
Details u = loadUserByUsername(username);
if (!u.isPasswordCorrect(password))
throw new BadCredentialsException("Failed to login as "+username);
return u;
} | Class | 2 |
protected void handleResponse(HttpRequest<?> request, MutableHttpResponse<?> response) {
HttpHeaders headers = request.getHeaders();
Optional<String> originHeader = headers.getOrigin();
originHeader.ifPresent(requestOrigin -> {
Optional<CorsOriginConfiguration> optionalConfig = getConfiguration(requestOrigin);
if (optionalConfig.isPresent()) {
CorsOriginConfiguration config = optionalConfig.get();
if (CorsUtil.isPreflightRequest(request)) {
Optional<HttpMethod> result = headers.getFirst(ACCESS_CONTROL_REQUEST_METHOD, HttpMethod.class);
setAllowMethods(result.get(), response);
Optional<List> allowedHeaders = headers.get(ACCESS_CONTROL_REQUEST_HEADERS, Argument.of(List.class, String.class));
allowedHeaders.ifPresent(val ->
setAllowHeaders(val, response)
);
setMaxAge(config.getMaxAge(), response);
}
setOrigin(requestOrigin, response);
setVary(response);
setExposeHeaders(config.getExposedHeaders(), response);
setAllowCredentials(config, response);
}
});
} | Class | 2 |
public static AsciiString of(AsciiString name) {
final AsciiString lowerCased = name.toLowerCase();
final AsciiString cached = map.get(lowerCased);
return cached != null ? cached : lowerCased;
} | Class | 2 |
public void testContains() {
final HttpHeadersBase headers = newEmptyHeaders();
headers.addLong("long", Long.MAX_VALUE);
assertThat(headers.containsLong("long", Long.MAX_VALUE)).isTrue();
assertThat(headers.containsLong("long", Long.MIN_VALUE)).isFalse();
headers.addInt("int", Integer.MIN_VALUE);
assertThat(headers.containsInt("int", Integer.MIN_VALUE)).isTrue();
assertThat(headers.containsInt("int", Integer.MAX_VALUE)).isFalse();
headers.addDouble("double", Double.MAX_VALUE);
assertThat(headers.containsDouble("double", Double.MAX_VALUE)).isTrue();
assertThat(headers.containsDouble("double", Double.MIN_VALUE)).isFalse();
headers.addFloat("float", Float.MAX_VALUE);
assertThat(headers.containsFloat("float", Float.MAX_VALUE)).isTrue();
assertThat(headers.containsFloat("float", Float.MIN_VALUE)).isFalse();
final long millis = System.currentTimeMillis();
headers.addTimeMillis("millis", millis);
assertThat(headers.containsTimeMillis("millis", millis)).isTrue();
// This test doesn't work on midnight, January 1, 1970 UTC
assertThat(headers.containsTimeMillis("millis", 0)).isFalse();
headers.addObject("object", "Hello World");
assertThat(headers.containsObject("object", "Hello World")).isTrue();
assertThat(headers.containsObject("object", "")).isFalse();
headers.add("name", "value");
assertThat(headers.contains("name", "value")).isTrue();
assertThat(headers.contains("name", "value1")).isFalse();
} | Class | 2 |
public static boolean saveLinkList(HashMap<String, PortletInstitution> portletMap){
XStream xstream = XStreamHelper.createXStreamInstance();
xstream.alias("LinksPortlet", Map.class);
xstream.alias(ELEM_LINK, PortletLink.class);
xstream.alias(ELEM_INSTITUTION, PortletInstitution.class);
xstream.aliasAttribute(PortletInstitution.class, ATTR_INSTITUTION_NAME, ATTR_INSTITUTION_NAME);
String output = xstream.toXML(portletMap);
XStreamHelper.writeObject(xstream, fxConfXStreamFile, portletMap);
return (output.length() != 0);
} | Base | 1 |
public static XStream createXStreamInstanceForDBObjects() {
return new EnhancedXStream(true);
} | Base | 1 |
final protected CommandExecutionResult executeArg(TimingDiagram diagram, LineLocation location, RegexResult arg) {
final String compact = arg.get("COMPACT", 0);
final String code = arg.get("CODE", 0);
String full = arg.get("FULL", 0);
if (full == null) {
full = code;
}
final TimingStyle type = TimingStyle.valueOf(arg.get("TYPE", 0).toUpperCase());
return diagram.createRobustConcise(code, full, type, compact != null);
} | Base | 1 |
public void testCopy() throws Exception {
HttpHeadersBase headers = newEmptyHeaders();
headers.addLong("long", Long.MAX_VALUE);
headers.addInt("int", Integer.MIN_VALUE);
headers.addDouble("double", Double.MAX_VALUE);
headers.addFloat("float", Float.MAX_VALUE);
final long millis = System.currentTimeMillis();
headers.addTimeMillis("millis", millis);
headers.addObject("object", "Hello World");
headers.add("name", "value");
final HttpHeadersBase oldHeaders = headers;
headers = newEmptyHeaders();
headers.add(oldHeaders);
assertThat(headers.containsLong("long", Long.MAX_VALUE)).isTrue();
assertThat(headers.containsLong("long", Long.MIN_VALUE)).isFalse();
assertThat(headers.containsInt("int", Integer.MIN_VALUE)).isTrue();
assertThat(headers.containsInt("int", Integer.MAX_VALUE)).isFalse();
assertThat(headers.containsDouble("double", Double.MAX_VALUE)).isTrue();
assertThat(headers.containsDouble("double", Double.MIN_VALUE)).isFalse();
assertThat(headers.containsFloat("float", Float.MAX_VALUE)).isTrue();
assertThat(headers.containsFloat("float", Float.MIN_VALUE)).isFalse();
assertThat(headers.containsTimeMillis("millis", millis)).isTrue();
// This test doesn't work on midnight, January 1, 1970 UTC
assertThat(headers.containsTimeMillis("millis", 0)).isFalse();
assertThat(headers.containsObject("object", "Hello World")).isTrue();
assertThat(headers.containsObject("object", "")).isFalse();
assertThat(headers.contains("name", "value")).isTrue();
assertThat(headers.contains("name", "value1")).isFalse();
} | Class | 2 |
public void addViolation(String propertyName, String key, String message) {
violationOccurred = true;
String messageTemplate = escapeEl(message);
context.buildConstraintViolationWithTemplate(messageTemplate)
.addPropertyNode(propertyName)
.addBeanNode().inIterable().atKey(key)
.addConstraintViolation();
} | Class | 2 |
private void initConfigMocks(String[] pInitParams, String[] pContextParams,String pLogRegexp, Class<? extends Exception> pExceptionClass) {
config = createMock(ServletConfig.class);
context = createMock(ServletContext.class);
String[] params = pInitParams != null ? Arrays.copyOf(pInitParams,pInitParams.length + 2) : new String[2];
params[params.length - 2] = ConfigKey.DEBUG.getKeyValue();
params[params.length - 1] = "true";
HttpTestUtil.prepareServletConfigMock(config,params);
HttpTestUtil.prepareServletContextMock(context, pContextParams);
expect(config.getServletContext()).andReturn(context).anyTimes();
expect(config.getServletName()).andReturn("jolokia").anyTimes();
if (pExceptionClass != null) {
context.log(find(pLogRegexp),isA(pExceptionClass));
} else {
if (pLogRegexp != null) {
context.log(find(pLogRegexp));
} else {
context.log((String) anyObject());
}
}
context.log((String) anyObject());
expectLastCall().anyTimes();
context.log(find("TestDetector"),isA(RuntimeException.class));
} | Compound | 4 |
public void testGetShellCommandLineBash()
throws Exception
{
Commandline cmd = new Commandline( new BourneShell() );
cmd.setExecutable( "/bin/echo" );
cmd.addArguments( new String[] {
"hello world"
} );
String[] shellCommandline = cmd.getShellCommandline();
assertEquals( "Command line size", 3, shellCommandline.length );
assertEquals( "/bin/sh", shellCommandline[0] );
assertEquals( "-c", shellCommandline[1] );
String expectedShellCmd = "/bin/echo \'hello world\'";
if ( Os.isFamily( Os.FAMILY_WINDOWS ) )
{
expectedShellCmd = "\\bin\\echo \'hello world\'";
}
assertEquals( expectedShellCmd, shellCommandline[2] );
} | Base | 1 |
public void setCharacterStream() throws Exception {
String exmplar = "<x>value</x>";
SQLXML pgSQLXML = con.createSQLXML();
Writer writer = pgSQLXML.setCharacterStream();
writer.write(exmplar);
PreparedStatement preparedStatement = con.prepareStatement("insert into xmltab values (?)");
preparedStatement.setSQLXML(1,pgSQLXML);
preparedStatement.execute();
Statement statement = con.createStatement();
ResultSet rs = statement.executeQuery("select * from xmltab");
assertTrue(rs.next());
SQLXML result = rs.getSQLXML(1);
assertNotNull(result);
assertEquals(exmplar, result.getString());
} | Base | 1 |
protected ObjectStreamClass readClassDescriptor()
throws IOException, ClassNotFoundException {
int type = read();
if (type < 0) {
throw new EOFException();
}
switch (type) {
case ThrowableObjectOutputStream.TYPE_EXCEPTION:
return ObjectStreamClass.lookup(Exception.class);
case ThrowableObjectOutputStream.TYPE_STACKTRACEELEMENT:
return ObjectStreamClass.lookup(StackTraceElement.class);
case ThrowableObjectOutputStream.TYPE_FAT_DESCRIPTOR:
return super.readClassDescriptor();
case ThrowableObjectOutputStream.TYPE_THIN_DESCRIPTOR:
String className = readUTF();
Class<?> clazz = loadClass(className);
return ObjectStreamClass.lookup(clazz);
default:
throw new StreamCorruptedException(
"Unexpected class descriptor type: " + type);
}
} | Class | 2 |
protected void configureReader(XMLReader reader, DefaultHandler handler)
throws DocumentException {
// configure lexical handling
SAXHelper.setParserProperty(reader, SAX_LEXICALHANDLER, handler);
// try alternate property just in case
SAXHelper.setParserProperty(reader, SAX_LEXICAL_HANDLER, handler);
// register the DeclHandler
if (includeInternalDTDDeclarations || includeExternalDTDDeclarations) {
SAXHelper.setParserProperty(reader, SAX_DECL_HANDLER, handler);
}
// string interning
SAXHelper.setParserFeature(reader, SAX_STRING_INTERNING,
isStringInternEnabled());
try {
// configure validation support
reader.setFeature("http://xml.org/sax/features/validation",
isValidating());
if (errorHandler != null) {
reader.setErrorHandler(errorHandler);
} else {
reader.setErrorHandler(handler);
}
} catch (Exception e) {
if (isValidating()) {
throw new DocumentException("Validation not supported for"
+ " XMLReader: " + reader, e);
}
}
} | Base | 1 |
private void sendAllJSON(HttpExchange pExchange, ParsedUri pParsedUri, JSONAware pJson) throws IOException {
OutputStream out = null;
try {
Headers headers = pExchange.getResponseHeaders();
if (pJson != null) {
headers.set("Content-Type", getMimeType(pParsedUri) + "; charset=utf-8");
String json = pJson.toJSONString();
String callback = pParsedUri.getParameter(ConfigKey.CALLBACK.getKeyValue());
String content = callback == null ? json : callback + "(" + json + ");";
byte[] response = content.getBytes("UTF8");
pExchange.sendResponseHeaders(200,response.length);
out = pExchange.getResponseBody();
out.write(response);
} else {
headers.set("Content-Type", "text/plain");
pExchange.sendResponseHeaders(200,-1);
}
} finally {
if (out != null) {
// Always close in order to finish the request.
// Otherwise the thread blocks.
out.close();
}
}
} | Base | 1 |
public Optional<URL> getResource(String path) {
Path filePath = getFilePath(normalize(path));
if (Files.exists(filePath) && Files.isReadable(filePath) && !Files.isDirectory(filePath)) {
try {
URL url = filePath.toUri().toURL();
return Optional.of(url);
} catch (MalformedURLException e) {
}
}
return Optional.empty();
} | Base | 1 |
public void translate(CommandRequestPacket packet, GeyserSession session) {
String command = packet.getCommand().replace("/", "");
CommandManager commandManager = GeyserConnector.getInstance().getCommandManager();
if (session.getConnector().getPlatformType() == PlatformType.STANDALONE && command.trim().startsWith("geyser ") && commandManager.getCommands().containsKey(command.split(" ")[1])) {
commandManager.runCommand(session, command);
} else {
String message = packet.getCommand().trim();
if (MessageTranslator.isTooLong(message, session)) {
return;
}
ClientChatPacket chatPacket = new ClientChatPacket(message);
session.sendDownstreamPacket(chatPacket);
}
} | Class | 2 |
public void testEqualsInsertionOrderSameHeaderName() {
final HttpHeadersBase h1 = newEmptyHeaders();
h1.add("a", "b");
h1.add("a", "c");
final HttpHeadersBase h2 = newEmptyHeaders();
h2.add("a", "c");
h2.add("a", "b");
assertThat(h1).isNotEqualTo(h2);
} | Class | 2 |
public void complexExample() throws Exception {
assertThat(ConstraintViolations.format(validator.validate(new ComplexExample())))
.containsExactlyInAnyOrder(
FAILED_RESULT + "1",
FAILED_RESULT + "2",
FAILED_RESULT + "3"
);
assertThat(TestLoggerFactory.getAllLoggingEvents())
.isEmpty();
} | Class | 2 |
public String resolveDriverClassName(DriverClassNameResolveRequest request) {
return driverResources.resolveSqlDriverNameFromJar(request.getJdbcDriverFileUrl());
} | Class | 2 |
default OptionalLong contentLength() {
Optional<Long> optional = getFirst(HttpHeaders.CONTENT_LENGTH, Long.class);
return optional.map(OptionalLong::of).orElseGet(OptionalLong::empty);
} | Class | 2 |
protected final boolean loadMore() throws IOException
{
if (_inputStream != null) {
_currInputProcessed += _inputEnd;
int count = _inputStream.read(_inputBuffer, 0, _inputBuffer.length);
if (count > 0) {
_inputPtr = 0;
_inputEnd = count;
return true;
}
// End of input
_closeInput();
// Should never return 0, so let's fail
if (count == 0) {
throw new IOException("InputStream.read() returned 0 characters when trying to read "+_inputBuffer.length+" bytes");
}
}
return false;
} | Base | 1 |
public void handle(HttpExchange pExchange) throws IOException {
if (requestHandler == null) {
throw new IllegalStateException("Handler not yet started");
}
JSONAware json = null;
URI uri = pExchange.getRequestURI();
ParsedUri parsedUri = new ParsedUri(uri,context);
try {
// Check access policy
InetSocketAddress address = pExchange.getRemoteAddress();
requestHandler.checkClientIPAccess(address.getHostName(),address.getAddress().getHostAddress());
String method = pExchange.getRequestMethod();
// Dispatch for the proper HTTP request method
if ("GET".equalsIgnoreCase(method)) {
setHeaders(pExchange);
json = executeGetRequest(parsedUri);
} else if ("POST".equalsIgnoreCase(method)) {
setHeaders(pExchange);
json = executePostRequest(pExchange, parsedUri);
} else if ("OPTIONS".equalsIgnoreCase(method)) {
performCorsPreflightCheck(pExchange);
} else {
throw new IllegalArgumentException("HTTP Method " + method + " is not supported.");
}
} catch (Throwable exp) {
json = requestHandler.handleThrowable(
exp instanceof RuntimeMBeanException ? ((RuntimeMBeanException) exp).getTargetException() : exp);
} finally {
sendResponse(pExchange,parsedUri,json);
}
} | Compound | 4 |
public void appendText(String text) {
if (text == null) {
return;
}
String previous = this.binding.textinput.getText().toString();
if (UIHelper.isLastLineQuote(previous)) {
text = '\n' + text;
} else if (previous.length() != 0 && !Character.isWhitespace(previous.charAt(previous.length() - 1))) {
text = " " + text;
}
this.binding.textinput.append(text);
} | Class | 2 |
void setPaths(final String s) {
try {
final ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(s.getBytes("8859_1")));
this.paths = (WorkBundle) ois.readObject();
} catch (Exception e) {
logger.error("Cannot deserialize WorkBundle using {} bytes", s.length(), e);
throw new IllegalArgumentException("Cannot deserialize WorkBundle");
}
} | Base | 1 |
public String invokeServletAndReturnAsString(String url, XWikiContext xwikiContext)
{
HttpServletRequest servletRequest = xwikiContext.getRequest();
HttpServletResponse servletResponse = xwikiContext.getResponse();
try {
return IncludeServletAsString.invokeServletAndReturnAsString(url, servletRequest, servletResponse);
} catch (Exception e) {
LOGGER.warn("Exception including url: " + url, e);
return "Exception including \"" + url + "\", see logs for details.";
}
} | Class | 2 |
public boolean loginValidate(String userName, String password, String email) {
String sql = "select * from voter_table where voter_name=? and password=? and email=?";
try {
ps = DbUtil.getConnection().prepareStatement(sql);
ps.setString(1, userName);
ps.setString(2, password);
ps.setString(3, email);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
return true;
}
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
return false;
} | Variant | 0 |
public boolean isMetadataFileValid(OLATResource videoResource) {
VFSContainer baseContainer = FileResourceManager.getInstance().getFileResourceRootImpl(videoResource);
VFSLeaf metaDataFile = (VFSLeaf) baseContainer.resolve(FILENAME_VIDEO_METADATA_XML);
try {
VideoMetadata meta = (VideoMetadata) XStreamHelper.readObject(XStreamHelper.createXStreamInstance(), metaDataFile);
return meta != null;
} catch (Exception e) {
return false;
}
} | Base | 1 |
void getGadgets() throws Exception
{
assertEquals(new ArrayList<>(), this.defaultGadgetSource.getGadgets(testSource, macroTransformationContext));
BaseObject gadgetObject1 = mock(BaseObject.class);
when(xWikiDocument.getXObjects(gadgetClassReference)).thenReturn(Collections.singletonList(gadgetObject1));
when(gadgetObject1.getOwnerDocument()).thenReturn(ownerDocument);
when(gadgetObject1.getStringValue("title")).thenReturn("Gadget 1");
when(gadgetObject1.getLargeStringValue("content")).thenReturn("Some content");
when(gadgetObject1.getStringValue("position")).thenReturn("0");
when(gadgetObject1.getNumber()).thenReturn(42);
List<Gadget> gadgets = this.defaultGadgetSource.getGadgets(testSource, macroTransformationContext);
assertEquals(1, gadgets.size());
Gadget gadget = gadgets.get(0);
assertEquals("Gadget 1", gadget.getTitle().get(0).toString());
assertEquals("Some content", gadget.getContent().get(0).toString());
assertEquals("42", gadget.getId());
} | Base | 1 |
public String resolveSqlDriverNameFromJar(String driverFileUrl) {
String tempFilePath = "temp/" + UUID.randomUUID() + ".jar";
File driverFile = doDownload(driverFileUrl, tempFilePath);
String className = doResolveSqlDriverNameFromJar(driverFile);
try {
Files.deleteIfExists(driverFile.toPath());
} catch (IOException e) {
log.error("delete driver error " + tempFilePath, e);
}
return className;
} | Class | 2 |
public void translate(RespawnPacket packet, GeyserSession session) {
if (packet.getState() == RespawnPacket.State.CLIENT_READY) {
// Previously we only sent the respawn packet before the server finished loading
// The message included was 'Otherwise when immediate respawn is on the client never loads'
// But I assume the new if statement below fixes that problem
RespawnPacket respawnPacket = new RespawnPacket();
respawnPacket.setRuntimeEntityId(0);
respawnPacket.setPosition(Vector3f.ZERO);
respawnPacket.setState(RespawnPacket.State.SERVER_READY);
session.sendUpstreamPacket(respawnPacket);
if (session.isSpawned()) {
// Client might be stuck; resend spawn information
PlayerEntity entity = session.getPlayerEntity();
if (entity == null) return;
SetEntityDataPacket entityDataPacket = new SetEntityDataPacket();
entityDataPacket.setRuntimeEntityId(entity.getGeyserId());
entityDataPacket.getMetadata().putAll(entity.getMetadata());
session.sendUpstreamPacket(entityDataPacket);
MovePlayerPacket movePlayerPacket = new MovePlayerPacket();
movePlayerPacket.setRuntimeEntityId(entity.getGeyserId());
movePlayerPacket.setPosition(entity.getPosition());
movePlayerPacket.setRotation(entity.getBedrockRotation());
movePlayerPacket.setMode(MovePlayerPacket.Mode.RESPAWN);
session.sendUpstreamPacket(movePlayerPacket);
}
ClientRequestPacket javaRespawnPacket = new ClientRequestPacket(ClientRequest.RESPAWN);
session.sendDownstreamPacket(javaRespawnPacket);
}
} | Class | 2 |
public void testMatchOperations() {
JWKMatcher matcher = new JWKMatcher.Builder().keyOperations(new LinkedHashSet<>(Arrays.asList(KeyOperation.SIGN, KeyOperation.VERIFY))).build();
assertTrue(matcher.matches(new RSAKey.Builder(new Base64URL("n"), new Base64URL("e")).keyID("1")
.keyOperations(new HashSet<>(Arrays.asList(KeyOperation.SIGN, KeyOperation.VERIFY))).build()));
assertFalse(matcher.matches(new ECKey.Builder(ECKey.Curve.P_256, new Base64URL("x"), new Base64URL("y")).keyID("2").build()));
assertEquals("key_ops=[sign, verify]", matcher.toString());
} | Base | 1 |
public void existingDocumentFromUITemplateProviderSpecifiedTerminalOverridenFromUIToNonTerminal() throws Exception
{
// current document = xwiki:Main.WebHome
DocumentReference documentReference = new DocumentReference("xwiki", Arrays.asList("Main"), "WebHome");
XWikiDocument document = mock(XWikiDocument.class);
when(document.getDocumentReference()).thenReturn(documentReference);
when(document.isNew()).thenReturn(false);
when(document.getLocalReferenceMaxLength()).thenReturn(255);
context.setDoc(document);
// Submit from the UI spaceReference=X&name=Y&templateProvider=XWiki.MyTemplateProvider
String templateProviderFullName = "XWiki.MyTemplateProvider";
String spaceReferenceString = "X";
when(mockRequest.getParameter("spaceReference")).thenReturn(spaceReferenceString);
when(mockRequest.getParameter("name")).thenReturn("Y");
when(mockRequest.getParameter("templateprovider")).thenReturn(templateProviderFullName);
when(mockRequest.getParameter("tocreate")).thenReturn("nonterminal");
// Mock 1 existing template provider that creates terminal documents.
mockExistingTemplateProviders(templateProviderFullName,
new DocumentReference("xwiki", Arrays.asList("XWiki"), "MyTemplateProvider"), Collections.EMPTY_LIST, true);
// Run the action
String result = action.render(context);
// The tests are below this line!
// Verify null is returned (this means the response has been returned)
assertNull(result);
// Note: We are creating the document X.Y.WebHome as non-terminal, even if the template provider says otherwise.
// Also using a template, as specified in the template provider.
verify(mockURLFactory).createURL("X.Y", "WebHome", "edit",
"template=XWiki.MyTemplate&parent=Main.WebHome&title=Y", null, "xwiki", context);
} | Class | 2 |
public 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;
} | Class | 2 |
static XmlSchema createSchemaInstance(ThreadContext context, RubyClass klazz, Source source) {
Ruby runtime = context.getRuntime();
XmlRelaxng xmlRelaxng = (XmlRelaxng) NokogiriService.XML_RELAXNG_ALLOCATOR.allocate(runtime, klazz);
xmlRelaxng.setInstanceVariable("@errors", runtime.newEmptyArray());
try {
Schema schema = xmlRelaxng.getSchema(source, context);
xmlRelaxng.setVerifier(schema.newVerifier());
return xmlRelaxng;
} catch (VerifierConfigurationException ex) {
throw context.getRuntime().newRuntimeError("Could not parse document: " + ex.getMessage());
}
} | Base | 1 |
private void initializeVelocity() {
if (velocityEngine == null) {
velocityEngine = new VelocityEngine();
Properties props = new Properties();
props.setProperty(RuntimeConstants.RUNTIME_LOG, "startup_wizard_vel.log");
// Linux requires setting logging properties to initialize Velocity Context.
props.setProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM_CLASS,
"org.apache.velocity.runtime.log.CommonsLogLogChute");
props.setProperty(CommonsLogLogChute.LOGCHUTE_COMMONS_LOG_NAME, "initial_wizard_velocity");
// so the vm pages can import the header/footer
props.setProperty(RuntimeConstants.RESOURCE_LOADER, "class");
props.setProperty("class.resource.loader.description", "Velocity Classpath Resource Loader");
props.setProperty("class.resource.loader.class",
"org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
try {
velocityEngine.init(props);
}
catch (Exception e) {
log.error("velocity init failed, because: " + e);
}
}
} | Base | 1 |
public final HColor getBackColor(ISkinParam skinParam, Style style) {
if (colors == null || colors.getColor(ColorType.BACK) == null) {
if (UseStyle.useBetaStyle() == false)
return HColorUtils.COL_D7E0F2;
return style.value(PName.BackGroundColor).asColor(skinParam.getThemeStyle(), skinParam.getIHtmlColorSet());
}
return colors.getColor(ColorType.BACK);
} | Base | 1 |
private void updateStatus() {
if (config.getHIDMode() == 0) {
config.setNetworkStatus(false);
EditorActivity.stopNetworkSocketService(this);
ipButton.setVisibility(View.GONE);
ipStatusDivider.setVisibility(View.GONE);
if (config.getUSBStatus()) {
statusText.setText(R.string.config_status_usb_on);
statusImage.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.ic_usb));
} else {
statusText.setText(R.string.config_status_usb_off);
statusImage.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.ic_usb_off));
}
} else if (config.getHIDMode() == 1) {
EditorActivity.startNetworkSocketService(this);
ipButton.setVisibility(View.VISIBLE);
ipStatusDivider.setVisibility(View.VISIBLE);
if (config.getNetworkStatus()) {
statusText.setText(R.string.config_status_net_on);
statusImage.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.ic_net));
} else {
statusText.setText(R.string.config_status_net_off);
statusImage.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.ic_net_off));
}
EditorActivity.updateNotification(this);
}
} | Class | 2 |
public AccessControlList getAccessControlList(String mediaPackageId) throws NotFoundException,
SearchServiceDatabaseException {
EntityManager em = null;
try {
em = emf.createEntityManager();
SearchEntity entity = getSearchEntity(mediaPackageId, em);
if (entity == null) {
throw new NotFoundException("Could not found media package with ID " + mediaPackageId);
}
if (entity.getAccessControl() == null) {
return null;
} else {
return AccessControlParser.parseAcl(entity.getAccessControl());
}
} catch (NotFoundException e) {
throw e;
} catch (Exception e) {
logger.error("Could not retrieve ACL {}: {}", mediaPackageId, e.getMessage());
throw new SearchServiceDatabaseException(e);
} finally {
em.close();
}
} | Class | 2 |
protected DataSource createDataSource(Map<String, ?> params, SQLDialect dialect)
throws IOException {
String jndiName = (String) JNDI_REFNAME.lookUp(params);
if (jndiName == null) throw new IOException("Missing " + JNDI_REFNAME.description);
Context ctx = null;
DataSource ds = null;
try {
ctx = GeoTools.getInitialContext();
} catch (NamingException e) {
throw new RuntimeException(e);
}
try {
ds = (DataSource) ctx.lookup(jndiName);
} catch (NamingException e1) {
// check if the user did not specify "java:comp/env"
// and this code is running in a J2EE environment
try {
if (jndiName.startsWith(J2EERootContext) == false) {
ds = (DataSource) ctx.lookup(J2EERootContext + jndiName);
// success --> issue a waring
Logger.getLogger(this.getClass().getName())
.log(
Level.WARNING,
"Using "
+ J2EERootContext
+ jndiName
+ " instead of "
+ jndiName
+ " would avoid an unnecessary JNDI lookup");
}
} catch (NamingException e2) {
// do nothing, was only a try
}
}
if (ds == null) throw new IOException("Cannot find JNDI data source: " + jndiName);
else return ds;
} | Class | 2 |
private String clean(String svg) {
svg = svg.toLowerCase().replaceAll("\\s", "");
if (svg.contains("<script>"))
return EMPTY_SVG;
if (svg.contains("</script>"))
return EMPTY_SVG;
if (svg.contains("<foreignobject"))
return EMPTY_SVG;
if (svg.contains("</foreignobject>"))
return EMPTY_SVG;
return svg;
} | Base | 1 |
public void renderHead(IHeaderResponse response) {
super.renderHead(response);
response.render(JavaScriptHeaderItem.forReference(new MarkdownResourceReference()));
String encodedAttachmentSupport;
if (getAttachmentSupport() != null) {
encodedAttachmentSupport = Base64.encodeBase64String(SerializationUtils.serialize(getAttachmentSupport()));
encodedAttachmentSupport = StringUtils.deleteWhitespace(encodedAttachmentSupport);
encodedAttachmentSupport = StringEscapeUtils.escapeEcmaScript(encodedAttachmentSupport);
encodedAttachmentSupport = "'" + encodedAttachmentSupport + "'";
} else {
encodedAttachmentSupport = "undefined";
}
String callback = ajaxBehavior.getCallbackFunction(explicit("action"), explicit("param1"), explicit("param2"),
explicit("param3")).toString();
String autosaveKey = getAutosaveKey();
if (autosaveKey != null)
autosaveKey = "'" + JavaScriptEscape.escapeJavaScript(autosaveKey) + "'";
else
autosaveKey = "undefined";
String script = String.format("onedev.server.markdown.onDomReady('%s', %s, %d, %s, %d, %b, %b, '%s', %s);",
container.getMarkupId(),
callback,
ATWHO_LIMIT,
encodedAttachmentSupport,
getAttachmentSupport()!=null?getAttachmentSupport().getAttachmentMaxSize():0,
getUserMentionSupport() != null,
getReferenceSupport() != null,
JavaScriptEscape.escapeJavaScript(ProjectNameValidator.PATTERN.pattern()),
autosaveKey);
response.render(OnDomReadyHeaderItem.forScript(script));
script = String.format("onedev.server.markdown.onLoad('%s');", container.getMarkupId());
response.render(OnLoadHeaderItem.forScript(script));
} | Base | 1 |
public Mapper retrieveMapperById(String mapperId) {
List<PersistedMapper> mappers = dbInstance.getCurrentEntityManager()
.createNamedQuery("loadMapperByKey", PersistedMapper.class)
.setParameter("mapperId", mapperId)
.getResultList();
PersistedMapper pm = mappers.isEmpty() ? null : mappers.get(0);
if(pm != null && StringHelper.containsNonWhitespace(pm.getXmlConfiguration())) {
String configuration = pm.getXmlConfiguration();
Object obj = XStreamHelper.createXStreamInstance().fromXML(configuration);
if(obj instanceof Mapper) {
return (Mapper)obj;
}
}
return null;
} | Base | 1 |
private Secret(String value) {
this.value = value;
} | Class | 2 |
protected static String unifyQuotes( String path )
{
if ( path == null )
{
return null;
}
if ( path.indexOf( " " ) == -1 && path.indexOf( "'" ) != -1 && path.indexOf( "\"" ) == -1 )
{
return StringUtils.escape( path );
}
return StringUtils.quoteAndEscape( path, '\"', BASH_QUOTING_TRIGGER_CHARS );
} | Base | 1 |
protected void afterFeaturesReceived() throws SecurityRequiredException, NotConnectedException, InterruptedException {
StartTls startTlsFeature = getFeature(StartTls.ELEMENT, StartTls.NAMESPACE);
if (startTlsFeature != null) {
if (startTlsFeature.required() && config.getSecurityMode() == SecurityMode.disabled) {
notifyConnectionError(new SecurityRequiredByServerException());
return;
}
if (config.getSecurityMode() != ConnectionConfiguration.SecurityMode.disabled) {
sendNonza(new StartTls());
}
}
// If TLS is required but the server doesn't offer it, disconnect
// from the server and throw an error. First check if we've already negotiated TLS
// and are secure, however (features get parsed a second time after TLS is established).
if (!isSecureConnection() && startTlsFeature == null
&& getConfiguration().getSecurityMode() == SecurityMode.required) {
throw new SecurityRequiredByClientException();
}
if (getSASLAuthentication().authenticationSuccessful()) {
// If we have received features after the SASL has been successfully completed, then we
// have also *maybe* received, as it is an optional feature, the compression feature
// from the server.
maybeCompressFeaturesReceived.reportSuccess();
}
} | Class | 2 |
public <T extends JiffleRuntime> T getRuntimeInstance(Class<T> baseClass) throws
it.geosolutions.jaiext.jiffle.JiffleException {
RuntimeModel model = RuntimeModel.get(baseClass);
if (model == null) {
throw new it.geosolutions.jaiext.jiffle.JiffleException(baseClass.getName() +
" does not implement a required Jiffle runtime interface");
}
return (T) createRuntimeInstance(model, baseClass, false);
} | Base | 1 |
public static Secret decrypt(String data) {
if(data==null) return null;
try {
byte[] in = Base64.decode(data.toCharArray());
Secret s = tryDecrypt(KEY.decrypt(), in);
if (s!=null) return s;
// try our historical key for backward compatibility
Cipher cipher = getCipher("AES");
cipher.init(Cipher.DECRYPT_MODE, getLegacyKey());
return tryDecrypt(cipher, in);
} catch (GeneralSecurityException e) {
return null;
} catch (UnsupportedEncodingException e) {
throw new Error(e); // impossible
} catch (IOException e) {
return null;
}
} | Class | 2 |
protected Response attachToPost(Message mess, String filename, InputStream file, HttpServletRequest request) {
Identity identity = getIdentity(request);
if(identity == null) {
return Response.serverError().status(Status.UNAUTHORIZED).build();
} else if (!identity.equalsByPersistableKey(mess.getCreator())) {
if(mess.getModifier() == null || !identity.equalsByPersistableKey(mess.getModifier())) {
return Response.serverError().status(Status.UNAUTHORIZED).build();
}
}
VFSContainer container = fom.getMessageContainer(mess.getForum().getKey(), mess.getKey());
VFSItem item = container.resolve(filename);
VFSLeaf attachment = null;
if(item == null) {
attachment = container.createChildLeaf(filename);
} else {
filename = VFSManager.rename(container, filename);
if(filename == null) {
return Response.serverError().status(Status.NOT_ACCEPTABLE).build();
}
attachment = container.createChildLeaf(filename);
}
try(OutputStream out = attachment.getOutputStream(false)) {
IOUtils.copy(file, out);
} catch (IOException e) {
return Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build();
} finally {
FileUtils.closeSafely(file);
}
return Response.ok().build();
} | Base | 1 |
public void testToString() {
HttpHeadersBase headers = newEmptyHeaders();
headers.add("name1", "value1");
headers.add("name1", "value2");
headers.add("name2", "value3");
assertThat(headers.toString()).isEqualTo("[name1=value1, name1=value2, name2=value3]");
headers = newEmptyHeaders();
headers.add("name1", "value1");
headers.add("name2", "value2");
headers.add("name3", "value3");
assertThat(headers.toString()).isEqualTo("[name1=value1, name2=value2, name3=value3]");
headers = newEmptyHeaders();
headers.add("name1", "value1");
assertThat(headers.toString()).isEqualTo("[name1=value1]");
headers = newEmptyHeaders();
headers.endOfStream(true);
headers.add("name1", "value1");
assertThat(headers.toString()).isEqualTo("[EOS, name1=value1]");
headers = newEmptyHeaders();
assertThat(headers.toString()).isEqualTo("[]");
headers = newEmptyHeaders();
headers.endOfStream(true);
assertThat(headers.toString()).isEqualTo("[EOS]");
} | Class | 2 |
public void setHeadersShouldClearAndOverwrite() {
final HttpHeadersBase headers1 = newEmptyHeaders();
headers1.add("name", "value");
final HttpHeadersBase headers2 = newEmptyHeaders();
headers2.add("name", "newvalue");
headers2.add("name1", "value1");
headers1.set(headers2);
assertThat(headers2).isEqualTo(headers1);
} | Class | 2 |
public int decryptWithAd(byte[] ad, byte[] ciphertext,
int ciphertextOffset, byte[] plaintext, int plaintextOffset,
int length) throws ShortBufferException, BadPaddingException {
int space;
if (ciphertextOffset > ciphertext.length)
space = 0;
else
space = ciphertext.length - ciphertextOffset;
if (length > space)
throw new ShortBufferException();
if (plaintextOffset > plaintext.length)
space = 0;
else
space = plaintext.length - plaintextOffset;
if (!haskey) {
// The key is not set yet - return the ciphertext as-is.
if (length > space)
throw new ShortBufferException();
if (plaintext != ciphertext || plaintextOffset != ciphertextOffset)
System.arraycopy(ciphertext, ciphertextOffset, plaintext, plaintextOffset, length);
return length;
}
if (length < 16)
Noise.throwBadTagException();
int dataLen = length - 16;
if (dataLen > space)
throw new ShortBufferException();
setup(ad);
ghash.update(ciphertext, ciphertextOffset, dataLen);
ghash.pad(ad != null ? ad.length : 0, dataLen);
ghash.finish(enciv, 0, 16);
int temp = 0;
for (int index = 0; index < 16; ++index)
temp |= (hashKey[index] ^ enciv[index] ^ ciphertext[ciphertextOffset + dataLen + index]);
if ((temp & 0xFF) != 0)
Noise.throwBadTagException();
encryptCTR(ciphertext, ciphertextOffset, plaintext, plaintextOffset, dataLen);
return dataLen;
} | Base | 1 |
public 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 boolean isValid(String value, ConstraintValidatorContext context) {
long longValue = 0;
boolean failed = false;
String errorMessage = "";
try {
longValue = Long.parseLong(value);
} catch (NumberFormatException ex) {
failed = true;
errorMessage = String.format("Invalid integer value: '%s'", value);
}
if (!failed && longValue < 0) {
failed = true;
errorMessage = String.format("Expected positive integer value, got: '%s'", value);
}
if (!failed) {
return true;
}
LOG.warn(errorMessage);
context.buildConstraintViolationWithTemplate(errorMessage).addConstraintViolation();
return false;
} | Class | 2 |
public int size() {
return ByteUtils.bitLength(k.decode());
} | Class | 2 |
public void preflightCheckNegative() {
String origin = "http://bla.com";
String headers ="X-Data: Test";
expect(backend.isCorsAccessAllowed(origin)).andReturn(false);
replay(backend);
Map<String,String> ret = handler.handleCorsPreflightRequest(origin, headers);
assertNull(ret.get("Access-Control-Allow-Origin"));
} | Compound | 4 |
private void decodeTest()
{
EllipticCurve curve = new EllipticCurve(
new ECFieldFp(new BigInteger("6277101735386680763835789423207666416083908700390324961279")), // q
new BigInteger("fffffffffffffffffffffffffffffffefffffffffffffffc", 16), // a
new BigInteger("64210519e59c80e70fa7e9ab72243049feb8deecc146b9b1", 16)); // b
ECPoint p = ECPointUtil.decodePoint(curve, Hex.decode("03188da80eb03090f67cbf20eb43a18800f4ff0afd82ff1012"));
if (!p.getAffineX().equals(new BigInteger("188da80eb03090f67cbf20eb43a18800f4ff0afd82ff1012", 16)))
{
fail("x uncompressed incorrectly");
}
if (!p.getAffineY().equals(new BigInteger("7192b95ffc8da78631011ed6b24cdd573f977a11e794811", 16)))
{
fail("y uncompressed incorrectly");
}
} | Base | 1 |
public List<Entry> search(final String filter, final Object[] filterArgs, final int maxResultCount) {
return search(filter, filterArgs, resultWrapper -> (Entry) resultWrapper.getResult(), maxResultCount);
} | Class | 2 |
public static String getRealIp(HttpServletRequest request) {
//bae env
if (ZrLogUtil.isBae() && request.getHeader("clientip") != null) {
return request.getHeader("clientip");
}
String ip = request.getHeader("X-forwarded-for");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("X-Real-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
return ip;
} | Base | 1 |
public void testPseudoHeadersWithClearDoesNotLeak() {
final HttpHeadersBase headers = newHttp2Headers();
assertThat(headers.isEmpty()).isFalse();
headers.clear();
assertThat(headers.isEmpty()).isTrue();
// Combine 2 headers together, make sure pseudo headers stay up front.
headers.add("name1", "value1");
headers.scheme("nothing");
verifyPseudoHeadersFirst(headers);
final HttpHeadersBase other = newEmptyHeaders();
other.add("name2", "value2");
other.authority("foo");
verifyPseudoHeadersFirst(other);
headers.add(other);
verifyPseudoHeadersFirst(headers);
// Make sure the headers are what we expect them to be, and no leaking behind the scenes.
assertThat(headers.size()).isEqualTo(4);
assertThat(headers.get("name1")).isEqualTo("value1");
assertThat(headers.get("name2")).isEqualTo("value2");
assertThat(headers.scheme()).isEqualTo("nothing");
assertThat(headers.authority()).isEqualTo("foo");
} | Class | 2 |
private void switchToConversation(Conversation conversation, String text, boolean asQuote, String nick, boolean pm) {
Intent intent = new Intent(this, ConversationsActivity.class);
intent.setAction(ConversationsActivity.ACTION_VIEW_CONVERSATION);
intent.putExtra(ConversationsActivity.EXTRA_CONVERSATION, conversation.getUuid());
if (text != null) {
intent.putExtra(Intent.EXTRA_TEXT, text);
if (asQuote) {
intent.putExtra(ConversationsActivity.EXTRA_AS_QUOTE, true);
}
}
if (nick != null) {
intent.putExtra(ConversationsActivity.EXTRA_NICK, nick);
intent.putExtra(ConversationsActivity.EXTRA_IS_PRIVATE_MESSAGE, pm);
}
intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
} | Class | 2 |
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException
{
// GAE can't serve dot prefixed folders
String uri = request.getRequestURI().replace("/.", "/");
if (uri.toLowerCase().contains(".json"))
{
response.setContentType("application/json");
}
// Serve whatever was requested from .well-known
try (InputStream in = getServletContext().getResourceAsStream(uri))
{
if (in == null)
{
response.sendError(404);
return;
}
byte[] buffer = new byte[8192];
int count;
while ((count = in.read(buffer)) > 0)
{
response.getOutputStream().write(buffer, 0, count);
}
response.getOutputStream().flush();
response.getOutputStream().close();
}
} | Base | 1 |
public static void ensurePointOnCurve(final ECPublicKey ephemeralPublicKey, final ECPrivateKey privateKey)
throws JOSEException {
// Ensure the following is met:
// (y^2) mod p = (x^3 + ax + b) mod p
ECParameterSpec ecParameterSpec = privateKey.getParams();
EllipticCurve curve = ecParameterSpec.getCurve();
ECPoint point = ephemeralPublicKey.getW();
BigInteger x = point.getAffineX();
BigInteger y = point.getAffineY();
BigInteger a = curve.getA();
BigInteger b = curve.getB();
BigInteger p = ((ECFieldFp) curve.getField()).getP();
BigInteger leftSide = (y.pow(2)).mod(p);
BigInteger rightSide = (x.pow(3).add(a.multiply(x)).add(b)).mod(p);
if (! leftSide.equals(rightSide)) {
throw new JOSEException("Invalid ephemeral public key: Point not on expected curve");
}
} | Base | 1 |
protected HtmlRenderable htmlBody() {
return sequence(
HtmlElement.div(cssClass("dir-container")).content(
HtmlElement.span(cssClass("directory")).content(
HtmlElement.a(onclick("BuildDetail.tree_navigator(this)"))
.content(getFileName())
)
),
HtmlElement.div(cssClass("subdir-container"), style("display:none"))
.content(subDirectory)
);
} | Base | 1 |
public String extractCorsOrigin(String pOrigin) {
if (pOrigin != null) {
// Prevent HTTP response splitting attacks
String origin = pOrigin.replaceAll("[\\n\\r]*","");
if (backendManager.isCorsAccessAllowed(origin)) {
return "null".equals(origin) ? "*" : origin;
} else {
return null;
}
}
return null;
} | Compound | 4 |
private int _readAndWriteBytes(OutputStream out, int total) throws IOException
{
int left = total;
while (left > 0) {
int avail = _inputEnd - _inputPtr;
if (_inputPtr >= _inputEnd) {
loadMoreGuaranteed();
avail = _inputEnd - _inputPtr;
}
int count = Math.min(avail, left);
out.write(_inputBuffer, _inputPtr, count);
_inputPtr += count;
left -= count;
}
_tokenIncomplete = false;
return total;
} | Base | 1 |
public void newDocumentFromURLWhenNoType() throws Exception
{
// No type has been set by the user
when(mockRequest.get("type")).thenReturn(null);
// 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);
// 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)
assertEquals("create", result);
} | Class | 2 |
protected BigInteger[] derDecode(
byte[] encoding)
throws IOException
{
ByteArrayInputStream bIn = new ByteArrayInputStream(encoding);
ASN1InputStream aIn = new ASN1InputStream(bIn);
ASN1Sequence s = (ASN1Sequence)aIn.readObject();
BigInteger[] sig = new BigInteger[2];
sig[0] = ((ASN1Integer)s.getObjectAt(0)).getValue();
sig[1] = ((ASN1Integer)s.getObjectAt(1)).getValue();
return sig;
} | Base | 1 |
protected void initUpgradesHistories() {
File upgradesDir = new File(WebappHelper.getUserDataRoot(), SYSTEM_DIR);
File upgradesHistoriesFile = new File(upgradesDir, INSTALLED_UPGRADES_XML);
if (upgradesHistoriesFile.exists()) {
upgradesHistories = (Map<String, UpgradeHistoryData>)upgradesXStream.fromXML(upgradesHistoriesFile);
} else {
if (upgradesHistories == null) {
upgradesHistories = new HashMap<>();
}
needsUpgrade = false; //looks like a new install, no upgrade necessary
log.info("This looks like a new install or dropped data, will not do any upgrades.");
createUpgradeData();
}
} | Base | 1 |
public FromSkinparamToStyle(String key) {
if (key.contains("<<")) {
final StringTokenizer st = new StringTokenizer(key, "<>");
this.key = st.nextToken();
this.stereo = st.hasMoreTokens() ? st.nextToken() : null;
} else {
this.key = key;
this.stereo = null;
}
} | Base | 1 |
Randoms() {
random = new Random();
Date date = new Date();
random.setSeed(date.getTime());
} | Class | 2 |
public void testUpdateUser() throws Exception {
Set<JpaRole> authorities = new HashSet<JpaRole>();
authorities.add(new JpaRole("ROLE_ASTRO_101_SPRING_2011_STUDENT", org1));
JpaUser user = new JpaUser("user1", "pass1", org1, provider.getName(), true, authorities);
provider.addUser(user);
User loadUser = provider.loadUser("user1");
assertNotNull(loadUser);
authorities.add(new JpaRole("ROLE_ASTRO_101_SPRING_2013_STUDENT", org1));
String newPassword = "newPassword";
JpaUser updateUser = new JpaUser(user.getUsername(), newPassword, org1, provider.getName(), true, authorities);
User loadUpdatedUser = provider.updateUser(updateUser);
// User loadUpdatedUser = provider.loadUser(user.getUsername());
assertNotNull(loadUpdatedUser);
assertEquals(user.getUsername(), loadUpdatedUser.getUsername());
assertEquals(PasswordEncoder.encode(newPassword, user.getUsername()), loadUpdatedUser.getPassword());
assertEquals(authorities.size(), loadUpdatedUser.getRoles().size());
updateUser = new JpaUser("unknown", newPassword, org1, provider.getName(), true, authorities);
try {
provider.updateUser(updateUser);
fail("Should throw a NotFoundException");
} catch (NotFoundException e) {
assertTrue("User not found.", true);
}
} | Class | 2 |
public void doIconSize( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
String qs = req.getQueryString();
if(qs==null || !ICON_SIZE.matcher(qs).matches())
throw new ServletException();
Cookie cookie = new Cookie("iconSize", qs);
cookie.setMaxAge(/* ~4 mo. */9999999); // #762
rsp.addCookie(cookie);
String ref = req.getHeader("Referer");
if(ref==null) ref=".";
rsp.sendRedirect2(ref);
} | Base | 1 |
protected boolean isProbablePrime(BigInteger x)
{
/*
* Primes class for FIPS 186-4 C.3 primality checking
*/
return !Primes.hasAnySmallFactors(x) && Primes.isMRProbablePrime(x, param.getRandom(), iterations);
} | Class | 2 |
public DefaultFileSystemResourceLoader(File baseDirPath) {
this.baseDirPath = Optional.of(baseDirPath.toPath());
} | Base | 1 |
private void parseAttributesForKnownElements(Map<String, List<Entry>> subdirs, Node desc) {
// NOTE: NamedNodeMap does not have any particular order...
NamedNodeMap attributes = desc.getAttributes();
for (Node attr : asIterable(attributes)) {
if (!XMP.ELEMENTS.contains(attr.getNamespaceURI())) {
continue;
}
List<Entry> dir = subdirs.get(attr.getNamespaceURI());
if (dir == null) {
dir = new ArrayList<Entry>();
subdirs.put(attr.getNamespaceURI(), dir);
}
dir.add(new XMPEntry(attr.getNamespaceURI() + attr.getLocalName(), attr.getLocalName(), attr.getNodeValue()));
}
} | Base | 1 |
public void testMatchOperationsNotSpecifiedOrSign() {
JWKMatcher matcher = new JWKMatcher.Builder().keyOperations(KeyOperation.SIGN, null).build();
assertTrue(matcher.matches(new RSAKey.Builder(new Base64URL("n"), new Base64URL("e")).keyID("1")
.keyOperations(new HashSet<>(Collections.singletonList(KeyOperation.SIGN))).build()));
assertTrue(matcher.matches(new ECKey.Builder(ECKey.Curve.P_256, new Base64URL("x"), new Base64URL("y")).keyID("2").build()));
assertFalse(matcher.matches(new ECKey.Builder(ECKey.Curve.P_256, new Base64URL("x"), new Base64URL("y")).keyID("3")
.keyOperations(new HashSet<>(Collections.singletonList(KeyOperation.ENCRYPT))).build()));
assertEquals("key_ops=[sign, null]", matcher.toString());
} | Base | 1 |
public Optional<InputStream> getResourceAsStream(String path) {
Path filePath = getFilePath(normalize(path));
try {
return Optional.of(Files.newInputStream(filePath));
} catch (IOException e) {
return Optional.empty();
}
} | Base | 1 |
public void newDocumentFromURL() 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);
// 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", "edit", "template=&parent=Main.WebHome&title=Y", null, "xwiki",
context);
} | Class | 2 |
public static String compileMustache(Map<String, Object> context, String template) {
if (context == null || StringUtils.isBlank(template)) {
return "";
}
Writer writer = new StringWriter();
try {
Mustache.compiler().escapeHTML(false).emptyStringIsFalse(true).compile(template).execute(context, writer);
} finally {
try {
writer.close();
} catch (IOException e) {
logger.error(null, e);
}
}
return writer.toString();
} | Base | 1 |
public void testPrivateKeyParsingSHA256()
throws IOException, ClassNotFoundException
{
XMSSMTParameters params = new XMSSMTParameters(20, 10, new SHA256Digest());
XMSSMT mt = new XMSSMT(params, new SecureRandom());
mt.generateKeys();
byte[] privateKey = mt.exportPrivateKey();
byte[] publicKey = mt.exportPublicKey();
mt.importState(privateKey, publicKey);
assertTrue(Arrays.areEqual(privateKey, mt.exportPrivateKey()));
} | Base | 1 |
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// to get values from the login page
// HttpSession session=request.getSession();
PrintWriter out = response.getWriter();
int min = 100000;
int max = 999999;
otp = 5432;
Random r = new Random();
otp = r.nextInt(max - min) + min;
String userName = request.getParameter("uname");
String password = sha.getSHA(request.getParameter("pass"));
String vemail = request.getParameter("vmail");
String recipient = vemail;
String subject = "otp verification";
String content = "your otp is: " + otp;
// System.out.print(recipient);
String resultMessage = "";
// validation
if (voterDao.loginValidate(userName, password, vemail)) {
// to display the name of logged-in person in home page
HttpSession session = request.getSession();
session.setAttribute("username", userName);
try {
EmailSend.sendEmail(host, port, user, pass, recipient, subject, content);
} catch (MessagingException e) {
e.printStackTrace();
resultMessage = "There were an error: " + e.getMessage();
} finally {
RequestDispatcher rd = request.getRequestDispatcher("OTP.jsp");
rd.include(request, response);
out.println("<script type=\"text/javascript\">");
out.println("alert('" + resultMessage + "');");
out.println("</script>");
}
} else {
RequestDispatcher rd = request.getRequestDispatcher("voterlogin.jsp");
request.setAttribute("loginFailMsg", "Invalid Input ! Enter again !!");
// request.setAttribute("forgotPassMsg", "Forgot password??");
rd.include(request, response);
/*
* String forgetpass = request.getParameter("forgotPass"); //
* System.out.println(forgetpass); if (forgetpass == null) { rd =
* request.getRequestDispatcher("resetPassword.jsp"); rd.forward(request,
* response);
*/
}
} | Variant | 0 |
public void translate(SetLocalPlayerAsInitializedPacket packet, GeyserSession session) {
if (session.getPlayerEntity().getGeyserId() == packet.getRuntimeEntityId()) {
if (!session.getUpstream().isInitialized()) {
session.getUpstream().setInitialized(true);
session.login();
for (PlayerEntity entity : session.getEntityCache().getEntitiesByType(PlayerEntity.class)) {
if (!entity.isValid()) {
SkinManager.requestAndHandleSkinAndCape(entity, session, null);
entity.sendPlayer(session);
}
}
// Send Skulls
for (PlayerEntity entity : session.getSkullCache().values()) {
entity.spawnEntity(session);
SkullSkinManager.requestAndHandleSkin(entity, session, (skin) -> {
entity.getMetadata().getFlags().setFlag(EntityFlag.INVISIBLE, false);
entity.updateBedrockMetadata(session);
});
}
}
}
} | Class | 2 |
public void multipleValuesPerNameIteratorWithOtherNames() {
final HttpHeadersBase headers = newEmptyHeaders();
headers.add("name1", "value1");
headers.add("name1", "value2");
headers.add("name2", "value4");
headers.add("name1", "value3");
assertThat(headers.size()).isEqualTo(4);
final List<String> values = ImmutableList.copyOf(headers.valueIterator("name1"));
assertThat(values).containsExactly("value1", "value2", "value3");
final Iterator<String> itr = headers.valueIterator("name2");
assertThat(itr).hasNext();
assertThat(itr.next()).isEqualTo("value4");
assertThat(itr).isExhausted();
} | Class | 2 |
public int encryptWithAd(byte[] ad, byte[] plaintext, int plaintextOffset,
byte[] ciphertext, int ciphertextOffset, int length) throws ShortBufferException {
int space;
if (ciphertextOffset > ciphertext.length)
space = 0;
else
space = ciphertext.length - ciphertextOffset;
if (!haskey) {
// The key is not set yet - return the plaintext as-is.
if (length > space)
throw new ShortBufferException();
if (plaintext != ciphertext || plaintextOffset != ciphertextOffset)
System.arraycopy(plaintext, plaintextOffset, ciphertext, ciphertextOffset, length);
return length;
}
if (space < 16 || length > (space - 16))
throw new ShortBufferException();
setup(ad);
encrypt(plaintext, plaintextOffset, ciphertext, ciphertextOffset, length);
poly.update(ciphertext, ciphertextOffset, length);
finish(ad, length);
System.arraycopy(polyKey, 0, ciphertext, ciphertextOffset + length, 16);
return length + 16;
} | Base | 1 |
public void translate(ServerUpdateViewPositionPacket packet, GeyserSession session) {
if (!session.isSpawned() && session.getLastChunkPosition() == null) {
ChunkUtils.updateChunkPosition(session, Vector3i.from(packet.getChunkX() << 4, 64, packet.getChunkZ() << 4));
}
} | Class | 2 |
public AuthorizationCodeTokenRequest newTokenRequest(String authorizationCode) {
return new AuthorizationCodeTokenRequest(transport, jsonFactory,
new GenericUrl(tokenServerEncodedUrl), authorizationCode).setClientAuthentication(
clientAuthentication).setRequestInitializer(requestInitializer).setScopes(scopes);
} | Class | 2 |
public ResponseEntity<Resource> fetch(@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).body(file);
} | 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 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.