Unnamed: 0
int64
0
637
label
int64
0
1
code
stringlengths
24
8.83k
500
1
private <T> void setValidatedValueHandlerToValueContextIfPresent(ValidationContext<?> validationContext, ValueContext<?, T> valueContext, ConstraintMetaData metaData) { if ( metaData.requiresUnwrapping() ) { @SuppressWarnings("unchecked") //we know the handler matches the value type ValidatedValueUnwrappe...
501
1
public boolean getValidateClientProvidedNewSessionId() { return false; }
502
1
protected Object findValue(String expr, Class toType) { if (altSyntax() && toType == String.class) { return TextParseUtil.translateVariables('%', expr, stack); } else { expr = stripExpressionIfAltSyntax(expr); return getStack().findValue(expr, toType, throwException...
503
1
public HttpBinding getBinding() { if (this.binding == null) { this.binding = new AttachmentHttpBinding(); this.binding.setTransferException(isTransferException()); this.binding.setHeaderFilterStrategy(getHeaderFilterStrategy()); } return this.binding; ...
504
1
public HttpBinding getBinding() { if (binding == null) { // create a new binding and use the options from this endpoint binding = new DefaultHttpBinding(); binding.setHeaderFilterStrategy(getHeaderFilterStrategy()); binding.setTransferException(isTransferExcep...
505
1
public void setMaxTrailerSize(int maxTrailerSize) { this.maxTrailerSize = maxTrailerSize; } /** * This field indicates if the protocol is treated as if it is secure. This * normally means https is being used but can be used to fake https e.g * behind a reverse proxy. */
506
1
public void addRecipients(final ExtendedEmailPublisherContext context, final EnvVars env, final Set<InternetAddress> to, final Set<InternetAddress> cc, final Set<InternetAddress> bcc) { final class Debug implements RecipientProviderUtilities.IDebug { private final ExtendedEmailPublisher...
507
1
public void doFilter(ServletRequest filterRequest, ServletResponse filterResponse) throws IOException, ServletException { assertEquals("Invalid method", "POST", ((HttpServletRequest) filterRequest).getMethod()); } };
508
1
public void restorePersistentSettingsTest() throws Exception { logger.info("--> start 2 nodes"); Settings nodeSettings = settingsBuilder() .put("discovery.type", "zen") .put("discovery.zen.ping_timeout", "200ms") .put("discovery.initial_state_timeout",...
509
1
public void init(FilterConfig conf) throws ServletException { if (conf != null && "zookeeper".equals(conf.getInitParameter("signer.secret.provider"))) { SolrZkClient zkClient = (SolrZkClient)conf.getServletContext().getAttribute(KerberosPlugin.DELEGATION_TOKEN_ZK_CLIENT); conf.getServletCont...
510
1
Attributes setPropertiesFromAttributes( StylesheetHandler handler, String rawName, Attributes attributes, ElemTemplateElement target, boolean throwError) throws org.xml.sax.SAXException { XSLTElementDef def = getElemDef(); AttributesImpl undefines = null; boolean isComp...
511
1
public SecurityConstraint [] findSecurityConstraints(Request request, Context context) { ArrayList<SecurityConstraint> results = null; // Are there any defined security constraints? SecurityConstraint constraints[] = context.findConst...
512
1
private void writeSession(SessionInformations session, boolean displayUser) throws IOException { final String nextColumnAlignRight = "</td><td align='right'>"; final String nextColumnAlignCenter = "</td><td align='center'>"; write("<td><a href='?part=sessions&amp;sessionId="); write(htmlEncodeButNotSpace(sessi...
513
1
public boolean isUseRouteBuilder() { return false; } @Test
514
1
private <T> T run(PrivilegedAction<T> action) { return System.getSecurityManager() != null ? AccessController.doPrivileged( action ) : action.run(); } // JAXB closes the underlying input stream
515
1
public void execute(FunctionContext context) { RegionConfiguration configuration = (RegionConfiguration) context.getArguments(); if (this.cache.getLogger().fineEnabled()) { StringBuilder builder = new StringBuilder(); builder.append("Function ").append(ID).append(" received request: ").append(conf...
516
1
public static int methodUrl(String path, ByteChunk out, int readTimeout, Map<String, List<String>> reqHead, Map<String, List<String>> resHead, String method) throws IOException { URL url = new URL(path); HttpURLConnection connection = (HttpURLConnecti...
517
1
public void addRecipients(final ExtendedEmailPublisherContext context, final EnvVars env, final Set<InternetAddress> to, final Set<InternetAddress> cc, final Set<InternetAddress> bcc) { final class Debug implements RecipientProviderUtilities.IDebug { private final ExtendedEmailPublisher...
518
1
public static DateTimeZone randomDateTimeZone() { DateTimeZone timeZone; // It sounds like some Java Time Zones are unknown by JODA. For example: Asia/Riyadh88 // We need to fallback in that case to a known time zone try { timeZone = DateTimeZone.forTimeZone(randomTimeZo...
519
1
public void testTriggerWithLockedDownInstance() throws Exception { FreeStyleProject project = DuplicatesUtil.createGerritTriggeredJob(j, projectName); Setup.lockDown(j); GerritTrigger trigger = project.getTrigger(GerritTrigger.class); trigger.setSilentStartMode(false); Ger...
520
1
public static <T> Transformer<T, T> cloneTransformer() { return (Transformer<T, T>) INSTANCE; } /** * Constructor. */
521
1
public void setEnabled(boolean enabled);
522
1
public void testHttpSendStringAndReceiveJavaBody() throws Exception { context.addRoutes(new RouteBuilder() { @Override public void configure() throws Exception { from("jetty:http://localhost:{{port}}/myapp/myservice") .process(new Processor() { ...
523
1
private boolean evaluate(String text) { try { InputSource inputSource = new InputSource(new StringReader(text)); return ((Boolean)expression.evaluate(inputSource, XPathConstants.BOOLEAN)).booleanValue(); } catch (XPathExpressionException e) { return false; ...
524
1
protected boolean isAccepted(String paramName) { if (!this.acceptParams.isEmpty()) { for (Pattern pattern : acceptParams) { Matcher matcher = pattern.matcher(paramName); if (matcher.matches()) { return true; } } ...
525
1
public void loadConfig(Class<?>... configs) { this.context = new AnnotationConfigWebApplicationContext(); this.context.register(configs); this.context.refresh(); this.context.getAutowireCapableBeanFactory().autowireBean(this); }
526
1
private CoderResult decodeHasArray(ByteBuffer in, CharBuffer out) { int outRemaining = out.remaining(); int pos = in.position(); int limit = in.limit(); final byte[] bArr = in.array(); final char[] cArr = out.array(); final int inIndexLimit = limit + in.arrayOffset();...
527
1
public void testBogusPathCheck() { TesseractOCRConfig config = new TesseractOCRConfig(); config.setTesseractPath("blahdeblahblah"); assertEquals("blahdeblahblah", config.getTesseractPath()); }
528
1
public void setValues(PreparedStatement ps) throws SQLException { Timestamp t = new Timestamp(new Date().getTime()); ps.setTimestamp(1, t); ps.setString(2, encNewPassword); ps.setTimestamp(3, t); ps.setString(4, id); ...
529
1
public boolean isTransferException() { return transferException; } /** * If enabled and an Exchange failed processing on the consumer side, and if the caused Exception was send back serialized * in the response as a application/x-java-serialized-object content type. */
530
1
public void testSingletonPatternInSerialization() { final Object[] singletones = new Object[] { CloneTransformer.INSTANCE, ExceptionTransformer.INSTANCE, NOPTransformer.INSTANCE, StringValueTransformer.stringValueTransformer(), }; ...
531
1
public static void main( String[] args) { Security.addProvider(new BouncyCastleProvider()); runTest(new ECDSA5Test()); }
532
1
public synchronized void afterTest() throws IOException { wipeDataDirectories(); randomlyResetClients(); /* reset all clients - each test gets its own client based on the Random instance created above. */ } @Override
533
1
public void init(FilterConfig conf) throws ServletException { if (conf != null && "zookeeper".equals(conf.getInitParameter("signer.secret.provider"))) { SolrZkClient zkClient = (SolrZkClient)conf.getServletContext().getAttribute(DELEGATION_TOKEN_ZK_CLIENT); conf.getServletContext().setAttrib...
534
1
protected void setAuthenticateHeader(HttpServletRequest request, HttpServletResponse response, LoginConfig config, String nOnce) { // Get the realm name String realmName = conf...
535
1
public static Object deserialize(byte[] data) throws IOException, ClassNotFoundException { ByteArrayInputStream in = new ByteArrayInputStream(data); ObjectInputStream is = new ObjectInputStream(in); return is.readObject(); }
536
1
public FormValidation doCheckCommand(@QueryParameter String value) { if(Util.fixEmptyAndTrim(value)==null) return FormValidation.error(Messages.CommandLauncher_NoLaunchCommand()); else return FormValidation.ok(); } } }
537
1
private static void addUserTriggeringTheBuild(Run<?, ?> run, Set<InternetAddress> to, Set<InternetAddress> cc, Set<InternetAddress> bcc, EnvVars env, TaskListener listener, RecipientProviderUtilities.IDebug debug) { final User user = RecipientProviderUtilities.getUserTriggeringTheBuild(run); ...
538
1
protected void finish() throws IOException { if (!response.isCommitted()) { // Validate and write response headers try { prepareResponse(); } catch (IOException e) { // Set error flag error = true; } } ...
539
1
abstract protected JDBCTableReader getTableReader(Connection connection, String tableName, ParseContext parseContext);
540
1
public void testEntityExpansionWReq() throws Exception { String url = "https://localhost:" + getIdpHttpsPort() + "/fediz-idp/federation?"; url += "wa=wsignin1.0"; url += "&whr=urn:org:apache:cxf:fediz:idp:realm-A"; url += "&wtrealm=urn:org:apache:cxf:fediz:fedizhelloworld"; S...
541
1
public static void checkSlip(File parentFile, File file) throws IllegalArgumentException { String parentCanonicalPath; String canonicalPath; try { parentCanonicalPath = parentFile.getCanonicalPath(); canonicalPath = file.getCanonicalPath(); } catch (IOException e) { throw new IORuntimeException(e); ...
542
1
public ExitCode runWithoutHelp(CommandRunnerParams params) throws IOException, InterruptedException { if (saveFilename != null && loadFilename != null) { params.getConsole().printErrorText("Can't use both --load and --save"); return ExitCode.COMMANDLINE_ERROR; } if (saveFilename != nul...
543
1
public BeanDefinition createMatcher(String path, String method) { if (("/**".equals(path) || "**".equals(path)) && method == null) { return new RootBeanDefinition(AnyRequestMatcher.class); } BeanDefinitionBuilder matcherBldr = BeanDefinitionBuilder .rootBeanDefinition(type); matcherBldr.addConstructor...
544
1
public Collection<FileAnnotation> parse(final InputStream file, final String moduleName) throws InvocationTargetException { try { Digester digester = new Digester(); digester.setValidating(false); digester.setClassLoader(LintParser.class.getClassLoader()); ...
545
1
public List<GerritServer> removeServer(GerritServer s) { servers.remove(s); return servers; } /** * Check whether the list of servers contains a GerritServer object of a specific name. * * @param serverName to check. * @return whether the list contains a server with the...
546
1
public void configure() throws Exception { from("direct:start") .to("xslt:org/apache/camel/component/xslt/transform.xsl") .multicast() .beanRef("testBean") .to("mock:result"); } }; ...
547
1
public void removeUser(String username) { UserDatabase database = (UserDatabase) this.resource; User user = database.findUser(username); if (user == null) { return; } try { MBeanUtils.destroyMBean(user); database.removeUser(user); ...
548
1
public void execute(FunctionContext context) { RegionFunctionContext rfc = (RegionFunctionContext) context; context.getResultSender().lastResult(rfc.getDataSet().size()); }
549
1
public void execute(FunctionContext context) { Object[] arguments = (Object[]) context.getArguments(); String regionName = (String) arguments[0]; Set<String> keys = (Set<String>) arguments[1]; if (this.cache.getLogger().fineEnabled()) { StringBuilder builder = new StringBuilder(); builder....
550
1
protected Object extractResponseBody(Exchange exchange, JettyContentExchange httpExchange) throws IOException { Map<String, String> headers = getSimpleMap(httpExchange.getResponseHeaders()); String contentType = headers.get(Exchange.CONTENT_TYPE); // if content type is serialized java objec...
551
1
public int doRead(ByteChunk chunk, Request req) throws IOException { if (endChunk) { return -1; } if(needCRLFParse) { needCRLFParse = false; parseCRLF(false); } if (remaining <= 0) { if (!parseChunkHeader()) { ...
552
1
public FormValidation doNameFreeCheck( @QueryParameter("value") final String value) { if (!value.equals(name)) { if (PluginImpl.containsServer_(value)) { return FormValidation.error("The server name " + value + " is already in use!"); } else if...
553
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.exportPrivateKe...
554
1
public void addOtherTesseractConfig(String key, String value) { if (key == null) { throw new IllegalArgumentException("key must not be null"); } if (value == null) { throw new IllegalArgumentException("value must not be null"); } Matcher m = ALLOWABLE...
555
1
public void load(SolrQueryRequest req, SolrQueryResponse rsp, ContentStream stream, UpdateRequestProcessor processor) throws Exception { final String charset = ContentStreamBase.getCharsetFromContentType(stream.getContentType()); InputStream is = null; XMLStreamReader parser = null; String tr = ...
556
1
private SSLEngine createSSLEngine(Map<String,Object> userProperties) throws DeploymentException { try { // See if a custom SSLContext has been provided SSLContext sslContext = (SSLContext) userProperties.get(Constants.SSL_CONTEXT_PROPERTY); ...
557
1
private AsymmetricCipherKeyPair genKeyPair() { if (!initialized) { initializeDefault(); } // initialize authenticationPaths and treehash instances byte[][][] currentAuthPaths = new byte[numLayer][][]; byte[][][] nextAuthPaths = new byte[numLayer - 1][...
558
1
private void sendEntityMessage(Object message) throws Exception { MockEndpoint endpoint = getMockEndpoint("mock:result"); endpoint.reset(); endpoint.expectedMessageCount(1); template.sendBody("direct:start1", message); assertMockEndpointsSatisfied(); ...
559
1
public static String getContextPath(HttpServletRequest request) { String contextPath = (String) request.getAttribute(INCLUDE_CONTEXT_PATH_ATTRIBUTE); if (contextPath == null) { contextPath = request.getContextPath(); } if ("/".equals(contextPath)) { // Invalid...
560
1
private void doTestRewrite(String config, String request, String expectedURI) throws Exception { Tomcat tomcat = getTomcatInstance(); // No file system docBase required Context ctx = tomcat.addContext("", null); RewriteValve rewriteValve = new RewriteValve(); ctx.getPipelin...
561
1
public Result isAllowed(String principalId) { LockoutPolicy lockoutPolicy = lockoutPolicyRetriever.getLockoutPolicy(); if (!lockoutPolicy.isLockoutEnabled()) { return new Result(true, 0); } long eventsAfter = timeService.getCurrentTimeMillis() - lockoutPolicy.getCountFa...
562
1
public void save() throws Exception { if (getReadonly()) { log.error(sm.getString("memoryUserDatabase.readOnly")); return; } if (!isWriteable()) { log.warn(sm.getString("memoryUserDatabase.notPersistable")); return; } // Writ...
563
1
public static boolean configSuccess(HierarchicalConfiguration reply) { if (reply != null) { if (reply.containsKey("ok")) { return true; } } return false; }
564
1
public void process(Exchange exchange) throws Exception {
565
1
public boolean createDB(String dbName, PortletRequest request) { Connection conn = null; try { conn = DerbyConnectionUtil.getDerbyConnection(dbName, DerbyConnectionUtil.CREATE_DB_PROP); portlet.addInfoMessage(request, portlet.getLocalizedString(request, "s...
566
1
public UnixUser authenticate(String username, String password) throws PAMException { this.password = password; try { check(libpam.pam_set_item(pht,PAM_USER,username),"pam_set_item failed"); check(libpam.pam_authenticate(pht,0),"pam_authenticate failed"); check(lib...
567
1
public void serveImage(ResourceRequest req, ResourceResponse resp) throws IOException { String fn = req.getRenderParameters().getValue("fn"); String ct = req.getRenderParameters().getValue("ct"); resp.setContentType(ct); String path = req.getPortletContext().getRealPath(fn); Fil...
568
1
public Http11NioProcessor createProcessor() { Http11NioProcessor processor = new Http11NioProcessor( proto.getMaxHttpHeaderSize(), (NioEndpoint)proto.endpoint, proto.getMaxTrailerSize()); processor.setAdapter(proto.getAdapter()); proces...
569
1
public Document getMetaData(Idp config, TrustedIdp serviceConfig) throws ProcessingException { try { Crypto crypto = CertsUtils.createCrypto(config.getCertificate()); ByteArrayOutputStream bout = new ByteArrayOutputStream(4096); Writer streamWriter = new Out...
570
1
public void send(final String format, final Object... args) { descriptor.debug(logger, format, args); } } final Debug debug = new Debug(); Set<User> users = null; final Run<?, ?> currentRun = context.getRun(); if (currentRun == null) { ...
571
1
public SocketState process(SocketWrapper<Long> socket) throws IOException { RequestInfo rp = request.getRequestProcessor(); rp.setStage(org.apache.coyote.Constants.STAGE_PARSE); // Setting up the socket this.socket = socket; long socketRef = socket.getSocket().longVa...
572
1
public void testRedirectActionPrefixWithEmptyExtension() throws Exception { Map parameterMap = new HashMap(); parameterMap.put(DefaultActionMapper.REDIRECT_ACTION_PREFIX + "myAction", ""); StrutsMockHttpServletRequest request = new StrutsMockHttpServletRequest(); request.setupGetSer...
573
1
public static void assertSettings(Settings left, Settings right, boolean compareClusterName) { ImmutableSet<Map.Entry<String, String>> entries0 = left.getAsMap().entrySet(); Map<String, String> entries1 = right.getAsMap(); assertThat(entries0.size(), equalTo(entries1.size())); for (M...
574
1
protected void service(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException { log.trace("Service: {}", request); // is there a consumer registered for the request. HttpConsumer consumer = getServletResolveConsumerStrategy().resolve(reque...
575
1
protected void submit(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException, FormException { super.submit(req,rsp); JSONObject json = req.getSubmittedForm(); makeDisabled(req.getParameter("disable")!=null); jdk = req.getParameter("jdk"); if(req.getPa...
576
1
private JMXConnectorServer createServer(String serverName, String bindAddress, int theRmiRegistryPort, int theRmiServerPort, HashMap<String,Object> theEnv, RMIClientSocketFactory registryCsf, RMIServerSocketFactory registrySsf, RMIClientSocketFactory serverCsf, RMISer...
577
1
private void decodeTest() { EllipticCurve curve = new EllipticCurve( new ECFieldFp(new BigInteger("6277101735386680763835789423207666416083908700390324961279")), // q new BigInteger("fffffffffffffffffffffffffffffffefffffffffffffffc", 16), // a new BigInteg...
578
1
private CipherText convertToCipherText(byte[] cipherTextSerializedBytes) throws EncryptionException { try { assert cipherTextSerializedBytes != null : "cipherTextSerializedBytes cannot be null."; assert cipherTextSerializedBytes.length > 0 : "cipherTextSerializedBytes must be >...
579
1
public static void writeXml(Node n, OutputStream os) throws TransformerException { TransformerFactory tf = TransformerFactory.newInstance(); // identity Transformer t = tf.newTransformer(); t.setOutputProperty(OutputKeys.INDENT, "yes"); t.transform(new DOMSource(n), new Strea...
580
1
void setTransferException(boolean transferException); /** * Gets the header filter strategy * * @return the strategy */
581
1
public List<ACL> getAclForPath(String path) { List<ACL> acls = zkACLProvider.getACLsToAdd(path); return acls; } }; }
582
1
protected void forwardToErrorPage(Request request, HttpServletResponse response, LoginConfig config) throws IOException { String errorPage = config.getErrorPage(); if (errorPage == null || errorPage.length() == 0) { String msg = sm.getString("formAuthenticator.no...
583
1
public void testSnapshotMoreThanOnce() throws ExecutionException, InterruptedException, IOException { Client client = client(); final File tempDir = newTempDir(LifecycleScope.SUITE).getAbsoluteFile(); logger.info("--> creating repository"); assertAcked(client.admin().cluster().prepa...
584
1
private boolean evaluate(String text) { try { InputSource inputSource = new InputSource(new StringReader(text)); return ((Boolean)expression.evaluate(inputSource, XPathConstants.BOOLEAN)).booleanValue(); } catch (XPathExpressionException e) { return false; ...
585
1
public void testTrailingHeadersSizeLimit() throws Exception { // Setup Tomcat instance Tomcat tomcat = getTomcatInstance(); // Must have a real docBase - just use temp Context ctx = tomcat.addContext("", System.getProperty("java.io.tmpdir")); Tomcat.addServlet(c...
586
1
public void testIsExpressionIsFalse() throws Exception { // given String anExpression = "foo"; // when boolean actual = ComponentUtils.isExpression(anExpression); // then assertFalse(actual); } } class MockConfigurationProvider implements ConfigurationProvider ...
587
1
@Test(timeout = 1000L) public void testLongMonths() throws Exception { Calendar cal = Calendar.getInstance(); cal.set(Calendar.MONTH, Calendar.JULY); new CronTab("0 0 31 7 *").floor(cal); // would infinite loop }
588
1
public static File unzip(File zip, File toDir, Predicate<ZipEntry> filter) throws IOException { if (!toDir.exists()) { FileUtils.forceMkdir(toDir); } ZipFile zipFile = new ZipFile(zip); try { Enumeration<? extends ZipEntry> entries = zipFile.entries(); while (entries.hasMoreElements...
589
1
public Authentication authenticate(Authentication req) throws AuthenticationException { logger.debug("Processing authentication request for " + req.getName()); if (req.getCredentials() == null) { BadCredentialsException e = new BadCredentialsException("No password supplied"); ...
590
1
public void setUp() throws Exception { lc = new LoggerContext(); lc.setName("testContext"); logger = lc.getLogger(LoggerSerializationTest.class); // create the byte output stream bos = new ByteArrayOutputStream(); oos = new ObjectOutputStream(bos); } @After
591
1
public void parseEmbedded( InputStream stream, ContentHandler handler, Metadata metadata, boolean outputHtml) throws SAXException, IOException { if(outputHtml) { AttributesImpl attributes = new AttributesImpl(); attributes.addAttribute("", "class", "class", "CDA...
592
1
private final void internalMapWrapper(ContextVersion contextVersion, CharChunk path, MappingData mappingData) throws IOException { int pathOffset = path.getOffset(); int pathEnd = path.getEnd(); int servletP...
593
1
protected String buildErrorMessage(Throwable e, Object[] args) { String errorKey = "struts.messages.upload.error." + e.getClass().getSimpleName(); if (LOG.isDebugEnabled()) { LOG.debug("Preparing error message for key: [#0]", errorKey); } return LocalizedTextUtil.findText...
594
1
public void testMultiValued() throws Exception { Map entityAttrs = createMap("name", "e", "url", "testdata.xml", XPathEntityProcessor.FOR_EACH, "/root"); List fields = new ArrayList(); fields.add(createMap("column", "a", "xpath", "/root/a", DataImporter.MULTI_VALUED, "true")); Context c =...
595
1
public String getInfo() { return (info); } // --------------------------------------------------------- Public Methods /** * Authenticate the user making this request, based on the specified * login configuration. Return <code>true</code> if any specified * constraint has b...
596
1
public final void invoke(Request request, Response response) throws IOException, ServletException { // Select the Context to be used for this Request Context context = request.getContext(); if (context == null) { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_...
597
1
private static void addHeadersToRequest(URLConnection connection, JSONObject headers) { try { for (Iterator<?> iter = headers.keys(); iter.hasNext(); ) { /* RFC 2616 says that non-ASCII characters and control * characters are not allowed in header names or values...
598
1
public HttpSecurity and() { return HttpSecurity.this; }
599
1
void setExtensionsTable(StylesheetRoot sroot) throws javax.xml.transform.TransformerException { try { if (sroot.getExtensions() != null) m_extensionsTable = new ExtensionsTable(sroot); } catch (javax.xml.transform.TransformerException te) {te.printStackTrace();} } //=...