Dataset Preview
Go to dataset viewer
Unnamed: 0 (int64)code (string)label (int64)
0
" private List<AuthInfo> createAuthInfo(SolrZkClient zkClient) { List<AuthInfo> ret = new LinkedList<AuthInfo>(); // In theory the credentials to add could change here if zookeeper hasn't been initialized ZkCredentialsProvider credentialsProvider = zkClient.getZkClientConnectionStrategy().getZkCredentialsToAddAutomatically(); for (ZkCredentialsProvider.ZkCredentials zkCredentials : credentialsProvider.getCredentials()) { ret.add(new AuthInfo(zkCredentials.getScheme(), zkCredentials.getAuth())); } return ret; } } }"
0
1
" public String getCharacterEncoding() { return characterEncoding; } /** * Set the character encoding to be used to read the user name and password. * * @param encoding The name of the encoding to use */ "
0
2
" public Log getLogger() { return logger; } "
0
3
" public void getAbsolutePathTest() { String absolutePath = FileUtil.getAbsolutePath("LICENSE-junit.txt"); Assert.assertNotNull(absolutePath); String absolutePath2 = FileUtil.getAbsolutePath(absolutePath); Assert.assertNotNull(absolutePath2); Assert.assertEquals(absolutePath, absolutePath2); } @Test "
0
4
" private Collection getPcClassLoaders() { if (_pcClassLoaders == null) _pcClassLoaders = new ConcurrentReferenceHashSet( ConcurrentReferenceHashSet.WEAK); return _pcClassLoaders; } "
0
5
" public static void main(String argv[]) throws Exception { doMain(SimpleSocketServer.class, argv); } "
0
6
" public JettyHttpComponent getComponent() { return (JettyHttpComponent) super.getComponent(); } @Override "
0
7
" public boolean isConfigured() { return order >= CONFIGURING.order; } } }"
0
8
" protected static final boolean isAlpha(String value) { for (int i = 0; i < value.length(); i++) { char c = value.charAt(i); if (!((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'))) { return false; } } return true; } "
0
9
" public void fail_if_unzipping_stream_outside_target_directory() throws Exception { File zip = new File(getClass().getResource("ZipUtilsTest/zip-slip.zip").toURI()); File toDir = temp.newFolder(); expectedException.expect(IllegalStateException.class); expectedException.expectMessage("Unzipping an entry outside the target directory is not allowed: ../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../tmp/evil.txt"); try (InputStream input = new FileInputStream(zip)) { ZipUtils.unzip(input, toDir); } } "
0
10
" public TransformerFactory createTransformerFactory() { TransformerFactory factory = TransformerFactory.newInstance(); // Enable the Security feature by default try { factory.setFeature(javax.xml.XMLConstants.FEATURE_SECURE_PROCESSING, true); } catch (TransformerConfigurationException e) { LOG.warn("TransformerFactory doesn't support the feature {} with value {}, due to {}.", new Object[]{javax.xml.XMLConstants.FEATURE_SECURE_PROCESSING, "true", e}); } factory.setErrorListener(new XmlErrorListener()); return factory; } "
0
11
" public long getAuthenticatedTime() { return authenticatedTime; } @Override @JsonIgnore "
0
12
" public X509Certificate generateCert(PublicKey publicKey, PrivateKey privateKey, String sigalg, int validity, String cn, String ou, String o, String l, String st, String c) throws java.security.SignatureException, java.security.InvalidKeyException { X509V1CertificateGenerator certgen = new X509V1CertificateGenerator(); // issuer dn Vector order = new Vector(); Hashtable attrmap = new Hashtable(); if (cn != null) { attrmap.put(X509Principal.CN, cn); order.add(X509Principal.CN); } if (ou != null) { attrmap.put(X509Principal.OU, ou); order.add(X509Principal.OU); } if (o != null) { attrmap.put(X509Principal.O, o); order.add(X509Principal.O); } if (l != null) { attrmap.put(X509Principal.L, l); order.add(X509Principal.L); } if (st != null) { attrmap.put(X509Principal.ST, st); order.add(X509Principal.ST); } if (c != null) { attrmap.put(X509Principal.C, c); order.add(X509Principal.C); } X509Principal issuerDN = new X509Principal(order, attrmap); certgen.setIssuerDN(issuerDN); // validity long curr = System.currentTimeMillis(); long untill = curr + (long) validity * 24 * 60 * 60 * 1000; certgen.setNotBefore(new Date(curr)); certgen.setNotAfter(new Date(untill)); // subject dn certgen.setSubjectDN(issuerDN); // public key certgen.setPublicKey(publicKey); // signature alg certgen.setSignatureAlgorithm(sigalg); // serial number certgen.setSerialNumber(new BigInteger(String.valueOf(curr))); // make certificate return certgen.generateX509Certificate(privateKey); } "
0
13
" public FormValidation doCheckCommand(@QueryParameter String value) { if (!Jenkins.getInstance().hasPermission(Jenkins.RUN_SCRIPTS)) { return FormValidation.warning(Messages.CommandLauncher_cannot_be_configured_by_non_administrato()); } if (Util.fixEmptyAndTrim(value) == null) { return FormValidation.error(Messages.CommandLauncher_NoLaunchCommand()); } else { return FormValidation.ok(); } } } } "
0
14
" public void filterWithParameter() throws IOException, ServletException { filterWithParameterForMethod("delete", "DELETE"); filterWithParameterForMethod("put", "PUT"); filterWithParameterForMethod("patch", "PATCH"); } @Test "
0
15
" public void setReplayCache(TokenReplayCache<String> replayCache) { this.replayCache = replayCache; } "
0
16
" public void setUp() throws Exception { scimUserProvisioning = mock(ScimUserProvisioning.class); expiringCodeStore = mock(ExpiringCodeStore.class); passwordValidator = mock(PasswordValidator.class); clientDetailsService = mock(ClientDetailsService.class); resetPasswordService = new UaaResetPasswordService(scimUserProvisioning, expiringCodeStore, passwordValidator, clientDetailsService); PasswordResetEndpoint controller = new PasswordResetEndpoint(resetPasswordService); controller.setCodeStore(expiringCodeStore); controller.setMessageConverters(new HttpMessageConverter[] { new ExceptionReportHttpMessageConverter() }); mockMvc = MockMvcBuilders.standaloneSetup(controller).build(); PasswordChange change = new PasswordChange("id001", "user@example.com", yesterday, null, null); when(expiringCodeStore.generateCode(eq("id001"), any(Timestamp.class), eq(null))) .thenReturn(new ExpiringCode("secret_code", new Timestamp(System.currentTimeMillis() + UaaResetPasswordService.PASSWORD_RESET_LIFETIME), "id001", null)); when(expiringCodeStore.generateCode(eq(JsonUtils.writeValueAsString(change)), any(Timestamp.class), eq(null))) .thenReturn(new ExpiringCode("secret_code", new Timestamp(System.currentTimeMillis() + UaaResetPasswordService.PASSWORD_RESET_LIFETIME), JsonUtils.writeValueAsString(change), null)); } @Test "
0
17
" public AhcComponent getComponent() { return (AhcComponent) super.getComponent(); } @Override "
0
18
" public StandardInterceptUrlRegistry access(String... attributes) { addMapping(requestMatchers, SecurityConfig.createList(attributes)); return UrlAuthorizationConfigurer.this.REGISTRY; } } }"
0
19
" protected static Object toPoolKey(Map map) { Object key = Configurations.getProperty("Id", map); return ( key != null) ? key : map; } /** * Register <code>factory</code> in the pool under <code>key</code>. * * @since 1.1.0 */ "
0
20
" protected Log getLog() { return log; } // ----------------------------------------------------------- Constructors "
0
21
" public void commence(ServletRequest request, ServletResponse response, AuthenticationException authException) throws IOException, ServletException { HttpServletRequest hrequest = (HttpServletRequest)request; HttpServletResponse hresponse = (HttpServletResponse)response; FedizContext fedContext = federationConfig.getFedizContext(); LOG.debug("Federation context: {}", fedContext); // Check to see if it is a metadata request MetadataDocumentHandler mdHandler = new MetadataDocumentHandler(fedContext); if (mdHandler.canHandleRequest(hrequest)) { mdHandler.handleRequest(hrequest, hresponse); return; } String redirectUrl = null; try { FedizProcessor wfProc = FedizProcessorFactory.newFedizProcessor(fedContext.getProtocol()); RedirectionResponse redirectionResponse = wfProc.createSignInRequest(hrequest, fedContext); redirectUrl = redirectionResponse.getRedirectionURL(); if (redirectUrl == null) { LOG.warn("Failed to create SignInRequest."); hresponse.sendError( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Failed to create SignInRequest."); } Map<String, String> headers = redirectionResponse.getHeaders(); if (!headers.isEmpty()) { for (Entry<String, String> entry : headers.entrySet()) { hresponse.addHeader(entry.getKey(), entry.getValue()); } } HttpSession session = ((HttpServletRequest)request).getSession(true); session.setAttribute(SAVED_CONTEXT, redirectionResponse.getRequestState().getState()); } catch (ProcessingException ex) { System.err.println("Failed to create SignInRequest: " + ex.getMessage()); LOG.warn("Failed to create SignInRequest: " + ex.getMessage()); hresponse.sendError( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Failed to create SignInRequest."); } preCommence(hrequest, hresponse); if (LOG.isInfoEnabled()) { LOG.info("Redirecting to IDP: " + redirectUrl); } hresponse.sendRedirect(redirectUrl); } "
0
22
" public void testSetParameterAndAttributeNames() throws Exception { interceptor.setAttributeName("hello"); interceptor.setParameterName("world"); params.put("world", Locale.CHINA); interceptor.intercept(mai); assertNull(params.get("world")); // should have been removed assertNotNull(session.get("hello")); // should be stored here assertEquals(Locale.CHINA, session.get("hello")); } "
0
23
" String postProcessVariableName(String variableName) { return variableName; } } } "
0
24
" public Iterable<Cascadable> getCascadables() { return cascadables; } @Override "
0
25
" public String getDataSourceName() { return dataSourceName; } /** * Set the name of the JNDI JDBC DataSource. * * @param dataSourceName the name of the JNDI JDBC DataSource */ "
0
26
" public boolean equals(Object obj) { if ( this == obj ) { return true; } if ( !super.equals( obj ) ) { return false; } if ( getClass() != obj.getClass() ) { return false; } ConstrainedField other = (ConstrainedField) obj; if ( getLocation().getMember() == null ) { if ( other.getLocation().getMember() != null ) { return false; } } else if ( !getLocation().getMember().equals( other.getLocation().getMember() ) ) { return false; } return true; } "
0
27
" public boolean isSingleton() { return _singleton; } /** * The plugin class name. */ "
0
28
" public String toXml() { StringBuilder sb = new StringBuilder("<user username=\""); sb.append(RequestUtil.filter(username)); sb.append("\" password=\""); sb.append(RequestUtil.filter(password)); sb.append("\""); if (fullName != null) { sb.append(" fullName=\""); sb.append(RequestUtil.filter(fullName)); sb.append("\""); } synchronized (groups) { if (groups.size() > 0) { sb.append(" groups=\""); int n = 0; Iterator<Group> values = groups.iterator(); while (values.hasNext()) { if (n > 0) { sb.append(','); } n++; sb.append(RequestUtil.filter(values.next().getGroupname())); } sb.append("\""); } } synchronized (roles) { if (roles.size() > 0) { sb.append(" roles=\""); int n = 0; Iterator<Role> values = roles.iterator(); while (values.hasNext()) { if (n > 0) { sb.append(','); } n++; sb.append(RequestUtil.filter(values.next().getRolename())); } sb.append("\""); } } sb.append("/>"); return (sb.toString()); } /** * <p>Return a String representation of this user.</p> */ @Override "
0
29
" public static Document signMetaInfo(Crypto crypto, String keyAlias, String keyPassword, Document doc, String referenceID) throws Exception { if (keyAlias == null || "".equals(keyAlias)) { keyAlias = crypto.getDefaultX509Identifier(); } X509Certificate cert = CertsUtils.getX509Certificate(crypto, keyAlias); // } /* public static ByteArrayOutputStream signMetaInfo(FederationContext config, InputStream metaInfo, String referenceID) throws Exception { KeyManager keyManager = config.getSigningKey(); String keyAlias = keyManager.getKeyAlias(); String keypass = keyManager.getKeyPassword(); // in case we did not specify the key alias, we assume there is only one key in the keystore , // we use this key's alias as default. if (keyAlias == null || "".equals(keyAlias)) { //keyAlias = getDefaultX509Identifier(ks); keyAlias = keyManager.getCrypto().getDefaultX509Identifier(); } CryptoType cryptoType = new CryptoType(CryptoType.TYPE.ALIAS); cryptoType.setAlias(keyAlias); X509Certificate[] issuerCerts = keyManager.getCrypto().getX509Certificates(cryptoType); if (issuerCerts == null || issuerCerts.length == 0) { throw new ProcessingException( "No issuer certs were found to sign the metadata using issuer name: " + keyAlias); } X509Certificate cert = issuerCerts[0]; */ String signatureMethod = null; if ("SHA1withDSA".equals(cert.getSigAlgName())) { signatureMethod = SignatureMethod.DSA_SHA1; } else if ("SHA1withRSA".equals(cert.getSigAlgName())) { signatureMethod = SignatureMethod.RSA_SHA1; } else if ("SHA256withRSA".equals(cert.getSigAlgName())) { signatureMethod = SignatureMethod.RSA_SHA1; } else { LOG.error("Unsupported signature method: " + cert.getSigAlgName()); throw new RuntimeException("Unsupported signature method: " + cert.getSigAlgName()); } List<Transform> transformList = new ArrayList<Transform>(); transformList.add(XML_SIGNATURE_FACTORY.newTransform(Transform.ENVELOPED, (TransformParameterSpec)null)); transformList.add(XML_SIGNATURE_FACTORY.newCanonicalizationMethod(CanonicalizationMethod.EXCLUSIVE, (C14NMethodParameterSpec)null)); // Create a Reference to the enveloped document (in this case, // you are signing the whole document, so a URI of "" signifies // that, and also specify the SHA1 digest algorithm and // the ENVELOPED Transform. Reference ref = XML_SIGNATURE_FACTORY.newReference( "#" + referenceID, XML_SIGNATURE_FACTORY.newDigestMethod(DigestMethod.SHA1, null), transformList, null, null); // Create the SignedInfo. SignedInfo si = XML_SIGNATURE_FACTORY.newSignedInfo( XML_SIGNATURE_FACTORY.newCanonicalizationMethod( CanonicalizationMethod.EXCLUSIVE, (C14NMethodParameterSpec)null), XML_SIGNATURE_FACTORY.newSignatureMethod( signatureMethod, null), Collections.singletonList(ref)); // step 2 // Load the KeyStore and get the signing key and certificate. PrivateKey keyEntry = crypto.getPrivateKey(keyAlias, keyPassword); // Create the KeyInfo containing the X509Data. KeyInfoFactory kif = XML_SIGNATURE_FACTORY.getKeyInfoFactory(); List<Object> x509Content = new ArrayList<Object>(); x509Content.add(cert.getSubjectX500Principal().getName()); x509Content.add(cert); X509Data xd = kif.newX509Data(x509Content); KeyInfo ki = kif.newKeyInfo(Collections.singletonList(xd)); // step3 // Create a DOMSignContext and specify the RSA PrivateKey and // location of the resulting XMLSignature's parent element. //DOMSignContext dsc = new DOMSignContext(keyEntry.getPrivateKey(), doc.getDocumentElement()); DOMSignContext dsc = new DOMSignContext(keyEntry, doc.getDocumentElement()); dsc.setIdAttributeNS(doc.getDocumentElement(), null, "ID"); dsc.setNextSibling(doc.getDocumentElement().getFirstChild()); // Create the XMLSignature, but don't sign it yet. XMLSignature signature = XML_SIGNATURE_FACTORY.newXMLSignature(si, ki); // Marshal, generate, and sign the enveloped signature. signature.sign(dsc); // step 4 // Output the resulting document. return doc; } "
0
30
" private Charset getCharset(String encoding) { if (encoding == null) { return DEFAULT_CHARSET; } try { return B2CConverter.getCharset(encoding); } catch (UnsupportedEncodingException e) { return DEFAULT_CHARSET; } } /** * Debug purpose */ "
0
31
" public ConstrainedParameter getParameterMetaData(int parameterIndex) { if ( parameterIndex < 0 || parameterIndex > parameterMetaData.size() - 1 ) { throw log.getInvalidExecutableParameterIndexException( executable.getAsString(), parameterIndex ); } return parameterMetaData.get( parameterIndex ); } /** * Returns meta data for all parameters of the represented executable. * * @return A list with parameter meta data. The length corresponds to the * number of parameters of the executable represented by this meta data * object, so an empty list may be returned (in case of a * parameterless executable), but never {@code null}. */ "
0
32
" private SendfileState processSendfile(SocketWrapperBase<?> socketWrapper) { openSocket = keepAlive; // Done is equivalent to sendfile not being used SendfileState result = SendfileState.DONE; // Do sendfile as needed: add socket to sendfile and end if (sendfileData != null && !getErrorState().isError()) { sendfileData.keepAlive = keepAlive; result = socketWrapper.processSendfile(sendfileData); switch (result) { case ERROR: // Write failed if (log.isDebugEnabled()) { log.debug(sm.getString("http11processor.sendfile.error")); } setErrorState(ErrorState.CLOSE_CONNECTION_NOW, null); //$FALL-THROUGH$ default: sendfileData = null; } } return result; } @Override "
0
33
" protected String determineTargetUrl(HttpServletRequest request) { String targetUrl = request.getParameter("from"); request.getSession().setAttribute("from", targetUrl); if (targetUrl == null) return getDefaultTargetUrl(); if (Util.isAbsoluteUri(targetUrl)) return "."; // avoid open redirect // URL returned from determineTargetUrl() is resolved against the context path, // whereas the "from" URL is resolved against the top of the website, so adjust this. if(targetUrl.startsWith(request.getContextPath())) return targetUrl.substring(request.getContextPath().length()); // not sure when this happens, but apparently this happens in some case. // see #1274 return targetUrl; } /** * @see org.acegisecurity.ui.AbstractProcessingFilter#determineFailureUrl(javax.servlet.http.HttpServletRequest, org.acegisecurity.AuthenticationException) */ @Override "
0
34
" public final void recycle() { try { // Must clear super's buffer. while (ready()) { // InputStreamReader#skip(long) will allocate buffer to skip. read(); } } catch(IOException ioe){ } } } /** Special output stream where close() is overriden, so super.close() is never called. This allows recycling. It can also be disabled, so callbacks will not be called if recycling the converter and if data was not flushed. */ final class IntermediateInputStream extends InputStream { ByteChunk bc = null; public IntermediateInputStream() { } public final void close() throws IOException { // shouldn't be called - we filter it out in writer throw new IOException("close() called - shouldn't happen "); } public final int read(byte cbuf[], int off, int len) throws IOException { return bc.substract(cbuf, off, len); } public final int read() throws IOException { return bc.substract(); } // -------------------- Internal methods -------------------- void setByteChunk( ByteChunk mb ) { bc = mb; } "
0
35
" public void execute(FunctionContext context) { RegionFunctionContext rfc = (RegionFunctionContext) context; Set<String> keys = (Set<String>) rfc.getFilter(); // Get local (primary) data for the context Region primaryDataSet = PartitionRegionHelper.getLocalDataForContext(rfc); if (this.cache.getLogger().fineEnabled()) { StringBuilder builder = new StringBuilder(); builder.append("Function ").append(ID).append(" received request to touch ") .append(primaryDataSet.getFullPath()).append("->").append(keys); this.cache.getLogger().fine(builder.toString()); } // Retrieve each value to update the lastAccessedTime. // Note: getAll is not supported on LocalDataSet. for (String key : keys) { primaryDataSet.get(key); } // Return result to get around NPE in LocalResultCollectorImpl context.getResultSender().lastResult(true); } @Override "
0
36
" private static boolean isFile(Path src) { return Files.exists(src) && Files.isRegularFile(src); } "
0
37
" public BeanDefinition parse(Element element, ParserContext pc) { CompositeComponentDefinition compositeDef = new CompositeComponentDefinition( element.getTagName(), pc.extractSource(element)); pc.pushContainingComponent(compositeDef); registerFilterChainProxyIfNecessary(pc, pc.extractSource(element)); // Obtain the filter chains and add the new chain to it BeanDefinition listFactoryBean = pc.getRegistry().getBeanDefinition( BeanIds.FILTER_CHAINS); List<BeanReference> filterChains = (List<BeanReference>) listFactoryBean .getPropertyValues().getPropertyValue("sourceList").getValue(); filterChains.add(createFilterChain(element, pc)); pc.popAndRegisterContainingComponent(); return null; } /** * Creates the {@code SecurityFilterChain} bean from an &lt;http&gt; element. */ "
0
38
" public void destroy() { normalView = null; viewViews = null; viewServers = null; viewGraphs = null; pageView = null; editView = null; addView = null; addGraph = null; editGraph = null; viewServer = null; editServer = null; addServer = null; helpView = null; editNormalView = null; super.destroy(); } "
0
39
" public BeanDefinition parse(Element elt, ParserContext pc) { MatcherType matcherType = MatcherType.fromElement(elt); String path = elt.getAttribute(HttpSecurityBeanDefinitionParser.ATT_PATH_PATTERN); String requestMatcher = elt.getAttribute(ATT_REQUEST_MATCHER_REF); String filters = elt.getAttribute(HttpSecurityBeanDefinitionParser.ATT_FILTERS); BeanDefinitionBuilder builder = BeanDefinitionBuilder .rootBeanDefinition(DefaultSecurityFilterChain.class); if (StringUtils.hasText(path)) { Assert.isTrue(!StringUtils.hasText(requestMatcher), ""); builder.addConstructorArgValue(matcherType.createMatcher(pc, path, null)); } else { Assert.isTrue(StringUtils.hasText(requestMatcher), ""); builder.addConstructorArgReference(requestMatcher); } if (filters.equals(HttpSecurityBeanDefinitionParser.OPT_FILTERS_NONE)) { builder.addConstructorArgValue(Collections.EMPTY_LIST); } else { String[] filterBeanNames = StringUtils.tokenizeToStringArray(filters, ","); ManagedList<RuntimeBeanReference> filterChain = new ManagedList<RuntimeBeanReference>( filterBeanNames.length); for (String name : filterBeanNames) { filterChain.add(new RuntimeBeanReference(name)); } builder.addConstructorArgValue(filterChain); } return builder.getBeanDefinition(); } "
0
40
" public long end() throws IOException { return 0; } "
0
41
" public static <E> Closure<E> whileClosure(final Predicate<? super E> predicate, final Closure<? super E> closure, final boolean doLoop) { if (predicate == null) { throw new NullPointerException("Predicate must not be null"); } if (closure == null) { throw new NullPointerException("Closure must not be null"); } return new WhileClosure<E>(predicate, closure, doLoop); } /** * Constructor that performs no validation. * Use <code>whileClosure</code> if you want that. * * @param predicate the predicate used to evaluate when the loop terminates, not null * @param closure the closure the execute, not null * @param doLoop true to act as a do-while loop, always executing the closure once */ "
0
42
" public void setDefaultHostName(String defaultHostName) { this.defaultHostName = defaultHostName; } /** * Add a new host to the mapper. * * @param name Virtual host name * @param aliases Alias names for the virtual host * @param host Host object */ "
0
43
" protected void startInternal() throws LifecycleException { // Create the roles PreparedStatement string StringBuilder temp = new StringBuilder("SELECT "); temp.append(roleNameCol); temp.append(" FROM "); temp.append(userRoleTable); temp.append(" WHERE "); temp.append(userNameCol); temp.append(" = ?"); preparedRoles = temp.toString(); // Create the credentials PreparedStatement string temp = new StringBuilder("SELECT "); temp.append(userCredCol); temp.append(" FROM "); temp.append(userTable); temp.append(" WHERE "); temp.append(userNameCol); temp.append(" = ?"); preparedCredentials = temp.toString(); super.startInternal(); } "
0
44
" public XMLLoader init(SolrParams args) { // Init StAX parser: inputFactory = XMLInputFactory.newInstance(); EmptyEntityResolver.configureXMLInputFactory(inputFactory); inputFactory.setXMLReporter(xmllog); try { // The java 1.6 bundled stax parser (sjsxp) does not currently have a thread-safe // XMLInputFactory, as that implementation tries to cache and reuse the // XMLStreamReader. Setting the parser-specific "reuse-instance" property to false // prevents this. // All other known open-source stax parsers (and the bea ref impl) // have thread-safe factories. inputFactory.setProperty("reuse-instance", Boolean.FALSE); } catch (IllegalArgumentException ex) { // Other implementations will likely throw this exception since "reuse-instance" // isimplementation specific. log.debug("Unable to set the 'reuse-instance' property for the input chain: " + inputFactory); } // Init SAX parser (for XSL): saxFactory = SAXParserFactory.newInstance(); saxFactory.setNamespaceAware(true); // XSL needs this! EmptyEntityResolver.configureSAXParserFactory(saxFactory); xsltCacheLifetimeSeconds = XSLT_CACHE_DEFAULT; if(args != null) { xsltCacheLifetimeSeconds = args.getInt(XSLT_CACHE_PARAM,XSLT_CACHE_DEFAULT); log.info("xsltCacheLifetimeSeconds=" + xsltCacheLifetimeSeconds); } return this; } "
0
45
" public void setParameterName(String parameterName) { this.parameterName = parameterName; } "
0
46
" public byte[] asSerializedByteArray() { int kdfInfo = cipherText_.getKDFInfo(); debug("asSerializedByteArray: kdfInfo = " + kdfInfo); long timestamp = cipherText_.getEncryptionTimestamp(); String cipherXform = cipherText_.getCipherTransformation(); assert cipherText_.getKeySize() < Short.MAX_VALUE : "Key size too large. Max is " + Short.MAX_VALUE; short keySize = (short) cipherText_.getKeySize(); assert cipherText_.getBlockSize() < Short.MAX_VALUE : "Block size too large. Max is " + Short.MAX_VALUE; short blockSize = (short) cipherText_.getBlockSize(); byte[] iv = cipherText_.getIV(); assert iv.length < Short.MAX_VALUE : "IV size too large. Max is " + Short.MAX_VALUE; short ivLen = (short) iv.length; byte[] rawCiphertext = cipherText_.getRawCipherText(); int ciphertextLen = rawCiphertext.length; assert ciphertextLen >= 1 : "Raw ciphertext length must be >= 1 byte."; byte[] mac = cipherText_.getSeparateMAC(); assert mac.length < Short.MAX_VALUE : "MAC length too large. Max is " + Short.MAX_VALUE; short macLen = (short) mac.length; byte[] serializedObj = computeSerialization(kdfInfo, timestamp, cipherXform, keySize, blockSize, ivLen, iv, ciphertextLen, rawCiphertext, macLen, mac ); return serializedObj; } /** * Return the actual {@code CipherText} object. * @return The {@code CipherText} object that we are serializing. */ "
0
47
" public void testContextRoot_Bug53339() throws Exception { Tomcat tomcat = getTomcatInstance(); tomcat.enableNaming(); // No file system docBase required Context ctx = tomcat.addContext("", null); Tomcat.addServlet(ctx, "Bug53356", new Bug53356Servlet()); ctx.addServletMapping("", "Bug53356"); tomcat.start(); ByteChunk body = getUrl("http://localhost:" + getPort()); Assert.assertEquals("OK", body.toString()); } "
0
48
" protected void execute() { if (controllersListStrings == null && !removeCont && !removeAll) { print("No controller are given, skipping."); return; } if (controllersListStrings != null) { Arrays.asList(controllersListStrings).forEach( cInfoString -> { ControllerInfo controllerInfo = parseCInfoString(cInfoString); if (controllerInfo != null) { controllers.add(controllerInfo); } }); } DriverService service = get(DriverService.class); deviceId = DeviceId.deviceId(uri); DriverHandler h = service.createHandler(deviceId); ControllerConfig config = h.behaviour(ControllerConfig.class); print("before:"); config.getControllers().forEach(c -> print(c.target())); try { if (removeAll) { if (!controllers.isEmpty()) { print("Controllers list should be empty to remove all controllers"); } else { List<ControllerInfo> controllersToRemove = config.getControllers(); controllersToRemove.forEach(c -> print("Will remove " + c.target())); config.removeControllers(controllersToRemove); } } else { if (controllers.isEmpty()) { print("Controllers list is empty, cannot set/remove empty controllers"); } else { if (removeCont) { print("Will remove specified controllers"); config.removeControllers(controllers); } else { print("Will add specified controllers"); config.setControllers(controllers); } } } } catch (NullPointerException e) { print("No Device with requested parameters {} ", uri); } print("after:"); config.getControllers().forEach(c -> print(c.target())); print("size %d", config.getControllers().size()); } "
0
49
" protected void saveLocale(ActionInvocation invocation, Locale locale) { invocation.getInvocationContext().setLocale(locale); } "
0
50
" public boolean isFinished() { return endChunk; } "
0
51
" public void test1() throws ANTLRException { new CronTab("@yearly"); new CronTab("@weekly"); new CronTab("@midnight"); new CronTab("@monthly"); new CronTab("0 0 * 1-10/3 *"); } @Test "
0
52
" public void multiByteReadThrowsAtEofForCorruptedStoredEntry() throws Exception { byte[] content; try (FileInputStream fs = new FileInputStream(getFile("COMPRESS-264.zip"))) { content = IOUtils.toByteArray(fs); } // make size much bigger than entry's real size for (int i = 17; i < 26; i++) { content[i] = (byte) 0xff; } byte[] buf = new byte[2]; try (ByteArrayInputStream in = new ByteArrayInputStream(content); ZipArchiveInputStream archive = new ZipArchiveInputStream(in)) { ArchiveEntry e = archive.getNextEntry(); try { IOUtils.toByteArray(archive); fail("expected exception"); } catch (IOException ex) { assertEquals("Truncated ZIP file", ex.getMessage()); } try { archive.read(buf); fail("expected exception"); } catch (IOException ex) { assertEquals("Truncated ZIP file", ex.getMessage()); } try { archive.read(buf); fail("expected exception"); } catch (IOException ex) { assertEquals("Truncated ZIP file", ex.getMessage()); } } } "
0
53
" public void testRead7ZipMultiVolumeArchiveForStream() throws IOException { final FileInputStream archive = new FileInputStream(getFile("apache-maven-2.2.1.zip.001")); ZipArchiveInputStream zi = null; try { zi = new ZipArchiveInputStream(archive,null,false); // these are the entries that are supposed to be processed // correctly without any problems for (final String element : ENTRIES) { assertEquals(element, zi.getNextEntry().getName()); } // this is the last entry that is truncated final ArchiveEntry lastEntry = zi.getNextEntry(); assertEquals(LAST_ENTRY_NAME, lastEntry.getName()); final byte [] buffer = new byte [4096]; // before the fix, we'd get 0 bytes on this read and all // subsequent reads thus a client application might enter // an infinite loop after the fix, we should get an // exception try { while (zi.read(buffer) > 0) { } fail("shouldn't be able to read from truncated entry"); } catch (final IOException e) { assertEquals("Truncated ZIP file", e.getMessage()); } try { zi.read(buffer); fail("shouldn't be able to read from truncated entry after exception"); } catch (final IOException e) { assertEquals("Truncated ZIP file", e.getMessage()); } // and now we get another entry, which should also yield // an exception try { zi.getNextEntry(); fail("shouldn't be able to read another entry from truncated" + " file"); } catch (final IOException e) { // this is to be expected } } finally { if (zi != null) { zi.close(); } } } @Test(expected=IOException.class) "
0
54
" public static Charset getCharset(String enc) throws UnsupportedEncodingException { // Encoding names should all be ASCII String lowerCaseEnc = enc.toLowerCase(Locale.US); Charset charset = (Charset) encodingToCharsetCache.get(lowerCaseEnc); if (charset == null) { // Pre-population of the cache means this must be invalid throw new UnsupportedEncodingException(enc); } return charset; } "
0
55
" public final String convert(String str, boolean query) { if (str == null) return null; if( (!query || str.indexOf( '+' ) < 0) && str.indexOf( '%' ) < 0 ) return str; StringBuffer dec = new StringBuffer(); // decoded string output int strPos = 0; int strLen = str.length(); dec.ensureCapacity(str.length()); while (strPos < strLen) { int laPos; // lookahead position // look ahead to next URLencoded metacharacter, if any for (laPos = strPos; laPos < strLen; laPos++) { char laChar = str.charAt(laPos); if ((laChar == '+' && query) || (laChar == '%')) { break; } } // if there were non-metacharacters, copy them all as a block if (laPos > strPos) { dec.append(str.substring(strPos,laPos)); strPos = laPos; } // shortcut out of here if we're at the end of the string if (strPos >= strLen) { break; } // process next metacharacter char metaChar = str.charAt(strPos); if (metaChar == '+') { dec.append(' '); strPos++; continue; } else if (metaChar == '%') { // We throw the original exception - the super will deal with // it // try { dec.append((char)Integer. parseInt(str.substring(strPos + 1, strPos + 3),16)); strPos += 3; } } return dec.toString(); } "
0
56
" public String[] getGroups() { UserDatabase database = (UserDatabase) this.resource; ArrayList<String> results = new ArrayList<String>(); Iterator<Group> groups = database.getGroups(); while (groups.hasNext()) { Group group = groups.next(); results.add(findGroup(group.getGroupname())); } return results.toArray(new String[results.size()]); } /** * Return the MBean Names of all roles defined in this database. */ "
0
57
" public void testEntities() throws Exception { // use a binary file, so when it's loaded fail with XML eror: String file = getFile("mailing_lists.pdf").toURI().toASCIIString(); String xml = "<?xml version=\"1.0\"?>" + "<!DOCTYPE foo [" + // check that external entities are not resolved! "<!ENTITY bar SYSTEM \""+file+"\">"+ // but named entities should be "<!ENTITY wacky \"zzz\">"+ "]>" + "<random>" + " &bar;" + " <document>" + " <node name=\"id\" value=\"12345\"/>" + " <node name=\"foo_s\" value=\"&wacky;\"/>" + " </document>" + "</random>"; SolrQueryRequest req = req(CommonParams.TR, "xsl-update-handler-test.xsl"); SolrQueryResponse rsp = new SolrQueryResponse(); BufferingRequestProcessor p = new BufferingRequestProcessor(null); XMLLoader loader = new XMLLoader().init(null); loader.load(req, rsp, new ContentStreamBase.StringStream(xml), p); AddUpdateCommand add = p.addCommands.get(0); assertEquals("12345", add.solrDoc.getField("id").getFirstValue()); assertEquals("zzz", add.solrDoc.getField("foo_s").getFirstValue()); req.close(); } "
0
58
" public void init(Map<String,Object> pluginConfig) { try { String delegationTokenEnabled = (String)pluginConfig.getOrDefault(DELEGATION_TOKEN_ENABLED_PROPERTY, "false"); authFilter = (Boolean.parseBoolean(delegationTokenEnabled)) ? new HadoopAuthFilter() : new AuthenticationFilter(); // Initialize kerberos before initializing curator instance. boolean initKerberosZk = Boolean.parseBoolean((String)pluginConfig.getOrDefault(INIT_KERBEROS_ZK, "false")); if (initKerberosZk) { (new Krb5HttpClientBuilder()).getBuilder(); } FilterConfig conf = getInitFilterConfig(pluginConfig); authFilter.init(conf); } catch (ServletException e) { log.error("Error initializing " + getClass().getSimpleName(), e); throw new SolrException(ErrorCode.SERVER_ERROR, "Error initializing " + getClass().getName() + ": "+e); } } @SuppressWarnings("unchecked") "
0
59
" public void testExceptionTransformer() { assertNotNull(TransformerUtils.exceptionTransformer()); assertSame(TransformerUtils.exceptionTransformer(), TransformerUtils.exceptionTransformer()); try { TransformerUtils.exceptionTransformer().transform(null); } catch (final FunctorException ex) { try { TransformerUtils.exceptionTransformer().transform(cString); } catch (final FunctorException ex2) { return; } } fail(); } // nullTransformer //------------------------------------------------------------------ @Test "
0
60
" protected void process(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { ModuleUtils.getInstance().selectModule(request, getServletContext()); ModuleConfig config = getModuleConfig(request); RequestProcessor processor = getProcessorForModule(config); if (processor == null) { processor = getRequestProcessor(config); } processor.process(request, response); } "
0
61
" public void addRecipients(final ExtendedEmailPublisherContext context, EnvVars env, Set<InternetAddress> to, Set<InternetAddress> cc, Set<InternetAddress> bcc) { final class Debug implements RecipientProviderUtilities.IDebug { private final ExtendedEmailPublisherDescriptor descriptor = Jenkins.getActiveInstance().getDescriptorByType(ExtendedEmailPublisherDescriptor.class); private final PrintStream logger = context.getListener().getLogger(); public void send(final String format, final Object... args) { descriptor.debug(logger, format, args); } } final Debug debug = new Debug(); debug.send("Sending email to upstream committer(s)."); Run<?, ?> cur; Cause.UpstreamCause upc = context.getRun().getCause(Cause.UpstreamCause.class); while (upc != null) { Job<?, ?> p = (Job<?, ?>) Jenkins.getActiveInstance().getItemByFullName(upc.getUpstreamProject()); if(p == null) { context.getListener().getLogger().print("There is a break in the project linkage, could not retrieve upstream project information"); break; } cur = p.getBuildByNumber(upc.getUpstreamBuild()); upc = cur.getCause(Cause.UpstreamCause.class); addUpstreamCommittersTriggeringBuild(cur, to, cc, bcc, env, context, debug); } } /** * Adds for the given upstream build the committers to the recipient list for each commit in the upstream build. * * @param build the upstream build * @param to the to recipient list * @param cc the cc recipient list * @param bcc the bcc recipient list * @param env * @param listener */ "
0
62
" private static synchronized PyObject get_dis() { if (dis == null) { dis = __builtin__.__import__("dis"); } return dis; } "
0
63
" public void processAction(ActionRequest actionRequest, ActionResponse actionResponse) throws PortletException, IOException { String action = actionRequest.getParameter("action"); actionResponse.setRenderParameter("action", action); if (action.equals("showView")) { String view_id = actionRequest.getParameter("view_id"); actionResponse.setRenderParameter("view_id", view_id); } else if (action.equals("showAllViews")) { // no parameters needed to be redirected to doView() } else if (action.equals("showAllServers")) { // no parameters needed to be redirected to doView() } else if (action.equals("showAllGraphs")) { // no parameters needed to be redirected to doView() } else if (action.equals("showEditView")) { String view_id = actionRequest.getParameter("view_id"); actionResponse.setRenderParameter("view_id", view_id); } else if (action.equals("saveEditView")) { updateView(actionRequest, actionResponse); } else if (action.equals("showAddView")) { // no parameters needed to be redirected to doView() } else if (action.equals("saveAddView")) { addView(actionRequest, actionResponse); } else if (action.equals("showAddGraph")) { String server_id = actionRequest.getParameter("server_id"); if (server_id != null) actionResponse.setRenderParameter("server_id", server_id); String mbean = actionRequest.getParameter("mbean"); if (mbean != null) actionResponse.setRenderParameter("mbean", mbean); String dataname = actionRequest.getParameter("dataname"); if (dataname != null) actionResponse.setRenderParameter("dataname", dataname); } else if (action.equals("saveAddGraph")) { addGraph(actionRequest, actionResponse); } else if (action.equals("showEditGraph")) { String graph_id = actionRequest.getParameter("graph_id"); actionResponse.setRenderParameter("graph_id", graph_id); } else if (action.equals("saveEditGraph")) { updateGraph(actionRequest, actionResponse); } else if (action.equals("deleteGraph")) { deleteGraph(actionRequest, actionResponse); } else if (action.equals("deleteView")) { deleteView(actionRequest, actionResponse); } else if (action.equals("showServer")) { String server_id = actionRequest.getParameter("server_id"); actionResponse.setRenderParameter("server_id", server_id); } else if (action.equals("showEditServer")) { String server_id = actionRequest.getParameter("server_id"); actionResponse.setRenderParameter("server_id", server_id); } else if (action.equals("saveEditServer")) { updateServer(actionRequest, actionResponse); } else if (action.equals("showAddServer")) { // no parameters needed to be redirected to doView() } else if (action.equals("deleteServer")) { deleteServer(actionRequest, actionResponse); } else if (action.equals("saveAddServer")) { addServer(actionRequest, actionResponse); } else if (action.equals("startTrackingMbean")) { String server_id = actionRequest.getParameter("server_id"); actionResponse.setRenderParameter("server_id", server_id); String mbean = actionRequest.getParameter("mbean"); actionResponse.setRenderParameter("mbean", mbean); } else if (action.equals("stopTrackingMbean")) { String server_id = actionRequest.getParameter("server_id"); actionResponse.setRenderParameter("server_id", server_id); String mbean = actionRequest.getParameter("mbean"); actionResponse.setRenderParameter("mbean", mbean); } else if (action.equals("stopThread") || action.equals("disableServerViewQuery")) { String server_id = actionRequest.getParameter("server_id"); String message = stopThread(server_id); actionResponse.setRenderParameter("server_id", server_id); actionResponse.setRenderParameter("message", message); } else if (action.equals("startThread") || action.equals("enableServerViewQuery")) { String server_id = actionRequest.getParameter("server_id"); String snapshotDuration = actionRequest .getParameter("snapshotDuration"); String message = startThread(server_id, new Long(snapshotDuration)); actionResponse.setRenderParameter("message", message); actionResponse.setRenderParameter("server_id", server_id); actionResponse.setRenderParameter("snapshotDuration", snapshotDuration); } else if (action.equals("disableServer") || action.equals("disableEditServer")) { String server_id = actionRequest.getParameter("server_id"); actionResponse.setRenderParameter("server_id", server_id); ; actionResponse.setRenderParameter("message", alterServerState( server_id, false)); } else if (action.equals("enableServer") || action.equals("enableEditServer")) { String server_id = actionRequest.getParameter("server_id"); actionResponse.setRenderParameter("message", alterServerState( server_id, true)); actionResponse.setRenderParameter("server_id", server_id); ; } else if (action.equals("testAddServerConnection")) { String name = actionRequest.getParameter("name"); String ip = actionRequest.getParameter("ip"); String username = actionRequest.getParameter("username"); String password = actionRequest.getParameter("password"); String password2 = actionRequest.getParameter("password2"); Integer port = Integer.parseInt(actionRequest.getParameter("port")); Integer protocol = Integer.parseInt(actionRequest.getParameter("protocol")); String message = testConnection(name, ip, username, password, port, protocol); actionResponse.setRenderParameter("message", message); actionResponse.setRenderParameter("name", name); actionResponse.setRenderParameter("username", username); actionResponse.setRenderParameter("ip", ip); // Don't return the password in the output // actionResponse.setRenderParameter("password", password); // actionResponse.setRenderParameter("password2", password2); actionResponse.setRenderParameter("port", "" + port); actionResponse.setRenderParameter("protocol", "" + protocol); } else if (action.equals("testEditServerConnection")) { String name = actionRequest.getParameter("name"); String ip = actionRequest.getParameter("ip"); String username = actionRequest.getParameter("username"); String password = actionRequest.getParameter("password"); String password2 = actionRequest.getParameter("password2"); String server_id = actionRequest.getParameter("server_id"); String snapshot = actionRequest.getParameter("snapshot"); String retention = actionRequest.getParameter("retention"); Integer port = Integer.parseInt(actionRequest.getParameter("port")); Integer protocol = Integer.parseInt(actionRequest.getParameter("protocol")); if(snapshot == null) { snapshot = ""; } if(retention == null) { retention = ""; } String message = testConnection(name, ip, username, password, port, protocol); actionResponse.setRenderParameter("message", message); actionResponse.setRenderParameter("name", name); actionResponse.setRenderParameter("username", username); actionResponse.setRenderParameter("ip", ip); // Don't return the password in the output // actionResponse.setRenderParameter("password", password); // actionResponse.setRenderParameter("password2", password2); actionResponse.setRenderParameter("snapshot", snapshot); actionResponse.setRenderParameter("server_id", server_id); actionResponse.setRenderParameter("retention", retention); actionResponse.setRenderParameter("port", "" + port); actionResponse.setRenderParameter("protocol", "" + protocol); } } "
0
64
" List<OrderDecorator> getFilters() { List<OrderDecorator> filters = new ArrayList<OrderDecorator>(); if (cpf != null) { filters.add(new OrderDecorator(cpf, CHANNEL_FILTER)); } if (concurrentSessionFilter != null) { filters.add(new OrderDecorator(concurrentSessionFilter, CONCURRENT_SESSION_FILTER)); } if (webAsyncManagerFilter != null) { filters.add(new OrderDecorator(webAsyncManagerFilter, WEB_ASYNC_MANAGER_FILTER)); } filters.add(new OrderDecorator(securityContextPersistenceFilter, SECURITY_CONTEXT_FILTER)); if (servApiFilter != null) { filters.add(new OrderDecorator(servApiFilter, SERVLET_API_SUPPORT_FILTER)); } if (jaasApiFilter != null) { filters.add(new OrderDecorator(jaasApiFilter, JAAS_API_SUPPORT_FILTER)); } if (sfpf != null) { filters.add(new OrderDecorator(sfpf, SESSION_MANAGEMENT_FILTER)); } filters.add(new OrderDecorator(fsi, FILTER_SECURITY_INTERCEPTOR)); if (sessionPolicy != SessionCreationPolicy.STATELESS) { filters.add(new OrderDecorator(requestCacheAwareFilter, REQUEST_CACHE_FILTER)); } if (this.corsFilter != null) { filters.add(new OrderDecorator(this.corsFilter, CORS_FILTER)); } if (addHeadersFilter != null) { filters.add(new OrderDecorator(addHeadersFilter, HEADERS_FILTER)); } if (csrfFilter != null) { filters.add(new OrderDecorator(csrfFilter, CSRF_FILTER)); } return filters; } "
0
65
" public void injectChaos(Random random) throws Exception { // sometimes we restart one of the jetty nodes if (random.nextBoolean()) { JettySolrRunner jetty = jettys.get(random.nextInt(jettys.size())); ChaosMonkey.stop(jetty); log.info("============ Restarting jetty"); ChaosMonkey.start(jetty); } // sometimes we restart zookeeper if (random.nextBoolean()) { zkServer.shutdown(); log.info("============ Restarting zookeeper"); zkServer = new ZkTestServer(zkServer.getZkDir(), zkServer.getPort()); zkServer.run(); } // sometimes we cause a connection loss - sometimes it will hit the overseer if (random.nextBoolean()) { JettySolrRunner jetty = jettys.get(random.nextInt(jettys.size())); ChaosMonkey.causeConnectionLoss(jetty); } } "
0
66
" public Permission getRequiredPermission() { return Jenkins.ADMINISTER; } "
0
67
" public Document getMetaData( HttpServletRequest request, FedizContext config ) throws ProcessingException { try { ByteArrayOutputStream bout = new ByteArrayOutputStream(4096); Writer streamWriter = new OutputStreamWriter(bout, "UTF-8"); XMLStreamWriter writer = XML_OUTPUT_FACTORY.createXMLStreamWriter(streamWriter); Protocol protocol = config.getProtocol(); writer.writeStartDocument("UTF-8", "1.0"); String referenceID = IDGenerator.generateID("_"); writer.writeStartElement("md", "EntityDescriptor", SAML2_METADATA_NS); writer.writeAttribute("ID", referenceID); String serviceURL = protocol.getApplicationServiceURL(); if (serviceURL == null) { serviceURL = extractFullContextPath(request); } writer.writeAttribute("entityID", serviceURL); writer.writeNamespace("md", SAML2_METADATA_NS); writer.writeNamespace("fed", WS_FEDERATION_NS); writer.writeNamespace("wsa", WS_ADDRESSING_NS); writer.writeNamespace("auth", WS_FEDERATION_NS); writer.writeNamespace("xsi", SCHEMA_INSTANCE_NS); if (protocol instanceof FederationProtocol) { writeFederationMetadata(writer, config, serviceURL); } else if (protocol instanceof SAMLProtocol) { writeSAMLMetadata(writer, request, config, serviceURL); } writer.writeEndElement(); // EntityDescriptor writer.writeEndDocument(); streamWriter.flush(); bout.flush(); // if (LOG.isDebugEnabled()) { String out = new String(bout.toByteArray()); LOG.debug("***************** unsigned ****************"); LOG.debug(out); LOG.debug("***************** unsigned ****************"); } InputStream is = new ByteArrayInputStream(bout.toByteArray()); boolean hasSigningKey = false; try { if (config.getSigningKey().getCrypto() != null) { hasSigningKey = true; } } catch (Exception ex) { LOG.info("No signingKey element found in config: " + ex.getMessage()); } if (hasSigningKey) { Document doc = DOMUtils.readXml(is); Document result = SignatureUtils.signMetaInfo( config.getSigningKey().getCrypto(), config.getSigningKey().getKeyAlias(), config.getSigningKey().getKeyPassword(), doc, referenceID); if (result != null) { return result; } else { throw new ProcessingException("Failed to sign the metadata document: result=null"); } } return DOMUtils.readXml(is); } catch (ProcessingException e) { throw e; } catch (Exception e) { LOG.error("Error creating service metadata information ", e); throw new ProcessingException("Error creating service metadata information: " + e.getMessage()); } } "
0
68
" protected void configure(HttpSecurity http) throws Exception { // This config is also on UrlAuthorizationConfigurer javadoc http .apply(new UrlAuthorizationConfigurer<HttpSecurity>(getApplicationContext())).getRegistry() .antMatchers("/users**","/sessions/**").hasRole("USER") .antMatchers("/signup").hasRole("ANONYMOUS") .anyRequest().hasRole("USER"); } // @formatter:on "
0
69
" public void testInitializiationIsConsistent() { long clusterSeed = randomLong(); int minNumDataNodes = randomIntBetween(0, 9); int maxNumDataNodes = randomIntBetween(minNumDataNodes, 10); String clusterName = randomRealisticUnicodeOfCodepointLengthBetween(1, 10); SettingsSource settingsSource = SettingsSource.EMPTY; int numClientNodes = randomIntBetween(0, 10); boolean enableRandomBenchNodes = randomBoolean(); boolean enableHttpPipelining = randomBoolean(); int jvmOrdinal = randomIntBetween(0, 10); String nodePrefix = randomRealisticUnicodeOfCodepointLengthBetween(1, 10); InternalTestCluster cluster0 = new InternalTestCluster(clusterSeed, minNumDataNodes, maxNumDataNodes, clusterName, settingsSource, numClientNodes, enableHttpPipelining, jvmOrdinal, nodePrefix); InternalTestCluster cluster1 = new InternalTestCluster(clusterSeed, minNumDataNodes, maxNumDataNodes, clusterName, settingsSource, numClientNodes, enableHttpPipelining, jvmOrdinal, nodePrefix); assertClusters(cluster0, cluster1, true); } "
0
70
" public void testConfigureDownstreamProjectSecurity() throws Exception { jenkins.setSecurityRealm(new LegacySecurityRealm()); ProjectMatrixAuthorizationStrategy auth = new ProjectMatrixAuthorizationStrategy(); auth.add(Jenkins.READ, "alice"); jenkins.setAuthorizationStrategy(auth); FreeStyleProject upstream = createFreeStyleProject("upstream"); Map<Permission,Set<String>> perms = new HashMap<Permission,Set<String>>(); perms.put(Item.READ, Collections.singleton("alice")); perms.put(Item.CONFIGURE, Collections.singleton("alice")); upstream.addProperty(new AuthorizationMatrixProperty(perms)); FreeStyleProject downstream = createFreeStyleProject("downstream"); /* Original SECURITY-55 test case: downstream.addProperty(new AuthorizationMatrixProperty(Collections.singletonMap(Item.READ, Collections.singleton("alice")))); */ WebClient wc = createWebClient(); wc.login("alice"); HtmlPage page = wc.getPage(upstream, "configure"); HtmlForm config = page.getFormByName("config"); config.getButtonByCaption("Add post-build action").click(); // lib/hudson/project/config-publishers2.jelly page.getAnchorByText("Build other projects").click(); HtmlTextInput childProjects = config.getInputByName("buildTrigger.childProjects"); childProjects.setValueAttribute("downstream"); try { submit(config); fail(); } catch (FailingHttpStatusCodeException x) { assertEquals(403, x.getStatusCode()); } assertEquals(Collections.emptyList(), upstream.getDownstreamProjects()); } "
0
71
" boolean isAllowJavaSerializedObject(); /** * The status codes which is considered a success response. The values are inclusive. The range must be defined as from-to with the dash included. * <p/> * The default range is <tt>200-299</tt> */ "
0
72
" public void register(ContainerBuilder builder, LocatableProperties props) throws ConfigurationException { builder.factory(com.opensymphony.xwork2.ObjectFactory.class) .factory(ActionProxyFactory.class, DefaultActionProxyFactory.class, Scope.SINGLETON) .factory(ObjectTypeDeterminer.class, DefaultObjectTypeDeterminer.class, Scope.SINGLETON) .factory(XWorkConverter.class, Scope.SINGLETON) .factory(XWorkBasicConverter.class, Scope.SINGLETON) .factory(ConversionPropertiesProcessor.class, DefaultConversionPropertiesProcessor.class, Scope.SINGLETON) .factory(ConversionFileProcessor.class, DefaultConversionFileProcessor.class, Scope.SINGLETON) .factory(ConversionAnnotationProcessor.class, DefaultConversionAnnotationProcessor.class, Scope.SINGLETON) .factory(TypeConverterCreator.class, DefaultTypeConverterCreator.class, Scope.SINGLETON) .factory(TypeConverterHolder.class, DefaultTypeConverterHolder.class, Scope.SINGLETON) .factory(FileManager.class, "system", DefaultFileManager.class, Scope.SINGLETON) .factory(FileManagerFactory.class, DefaultFileManagerFactory.class, Scope.SINGLETON) .factory(ValueStackFactory.class, OgnlValueStackFactory.class, Scope.SINGLETON) .factory(ValidatorFactory.class, DefaultValidatorFactory.class, Scope.SINGLETON) .factory(ValidatorFileParser.class, DefaultValidatorFileParser.class, Scope.SINGLETON) .factory(PatternMatcher.class, WildcardHelper.class, Scope.SINGLETON) .factory(ReflectionProvider.class, OgnlReflectionProvider.class, Scope.SINGLETON) .factory(ReflectionContextFactory.class, OgnlReflectionContextFactory.class, Scope.SINGLETON) .factory(PropertyAccessor.class, CompoundRoot.class.getName(), CompoundRootAccessor.class, Scope.SINGLETON) .factory(PropertyAccessor.class, Object.class.getName(), ObjectAccessor.class, Scope.SINGLETON) .factory(PropertyAccessor.class, Iterator.class.getName(), XWorkIteratorPropertyAccessor.class, Scope.SINGLETON) .factory(PropertyAccessor.class, Enumeration.class.getName(), XWorkEnumerationAccessor.class, Scope.SINGLETON) .factory(UnknownHandlerManager.class, DefaultUnknownHandlerManager.class, Scope.SINGLETON) // silly workarounds for ognl since there is no way to flush its caches .factory(PropertyAccessor.class, List.class.getName(), XWorkListPropertyAccessor.class, Scope.SINGLETON) .factory(PropertyAccessor.class, ArrayList.class.getName(), XWorkListPropertyAccessor.class, Scope.SINGLETON) .factory(PropertyAccessor.class, HashSet.class.getName(), XWorkCollectionPropertyAccessor.class, Scope.SINGLETON) .factory(PropertyAccessor.class, Set.class.getName(), XWorkCollectionPropertyAccessor.class, Scope.SINGLETON) .factory(PropertyAccessor.class, HashMap.class.getName(), XWorkMapPropertyAccessor.class, Scope.SINGLETON) .factory(PropertyAccessor.class, Map.class.getName(), XWorkMapPropertyAccessor.class, Scope.SINGLETON) .factory(PropertyAccessor.class, Collection.class.getName(), XWorkCollectionPropertyAccessor.class, Scope.SINGLETON) .factory(PropertyAccessor.class, ObjectProxy.class.getName(), ObjectProxyPropertyAccessor.class, Scope.SINGLETON) .factory(MethodAccessor.class, Object.class.getName(), XWorkMethodAccessor.class, Scope.SINGLETON) .factory(MethodAccessor.class, CompoundRoot.class.getName(), CompoundRootAccessor.class, Scope.SINGLETON) .factory(TextParser.class, OgnlTextParser.class, Scope.SINGLETON) .factory(NullHandler.class, Object.class.getName(), InstantiatingNullHandler.class, Scope.SINGLETON) .factory(ActionValidatorManager.class, AnnotationActionValidatorManager.class, Scope.SINGLETON) .factory(ActionValidatorManager.class, "no-annotations", DefaultActionValidatorManager.class, Scope.SINGLETON) .factory(TextProvider.class, "system", DefaultTextProvider.class, Scope.SINGLETON) .factory(TextProvider.class, TextProviderSupport.class, Scope.SINGLETON) .factory(LocaleProvider.class, DefaultLocaleProvider.class, Scope.SINGLETON) .factory(OgnlUtil.class, Scope.SINGLETON) .factory(CollectionConverter.class, Scope.SINGLETON) .factory(ArrayConverter.class, Scope.SINGLETON) .factory(DateConverter.class, Scope.SINGLETON) .factory(NumberConverter.class, Scope.SINGLETON) .factory(StringConverter.class, Scope.SINGLETON); props.setProperty(XWorkConstants.DEV_MODE, Boolean.FALSE.toString()); props.setProperty(XWorkConstants.LOG_MISSING_PROPERTIES, Boolean.FALSE.toString()); props.setProperty(XWorkConstants.ENABLE_OGNL_EXPRESSION_CACHE, Boolean.TRUE.toString()); props.setProperty(XWorkConstants.ENABLE_OGNL_EVAL_EXPRESSION, Boolean.FALSE.toString()); props.setProperty(XWorkConstants.RELOAD_XML_CONFIGURATION, Boolean.FALSE.toString()); } "
0
73
" private String getIncompatiblePluginMessage(Object obj, Class<?> type) { return _loc.get("incompatible-plugin", new Object[]{ _name, obj == null ? null : obj.getClass().getName(), type == null ? null : type.getName() }).toString(); } "
0
74
" public Properties defaultOutputProperties() { Properties properties = new Properties(); properties.put(OutputKeys.ENCODING, defaultCharset); properties.put(OutputKeys.OMIT_XML_DECLARATION, "yes"); return properties; } /** * Converts the given input Source into the required result */ "
0
75
" public void run() { request.getCoyoteRequest().action(ActionCode.ASYNC_DISPATCHED, null); try { applicationDispatcher.dispatch(servletRequest, servletResponse); }catch (Exception x) { //log.error("Async.dispatch",x); throw new RuntimeException(x); } } } } "
0
76
" private String getState(ServletRequest request) { if (request.getParameter(FederationConstants.PARAM_CONTEXT) != null) { return request.getParameter(FederationConstants.PARAM_CONTEXT); } else if (request.getParameter(SAMLSSOConstants.RELAY_STATE) != null) { return request.getParameter(SAMLSSOConstants.RELAY_STATE); } return null; } @Override "
0
77
" private Settings nodeSettings() { return ImmutableSettings.builder() .put("node.add_id_to_custom_path", false) .put("node.enable_custom_paths", true) .put("gateway.type", "local") // don't delete things! .put(ThrottlingAllocationDecider.CLUSTER_ROUTING_ALLOCATION_NODE_CONCURRENT_RECOVERIES, 6) .put("index.store.fs.fs_lock", randomFrom("native", "simple")) .build(); } /** * Tests the case where we create an index without shadow replicas, snapshot it and then restore into * an index with shadow replicas enabled. */ @Test "
0
78
" public void testExceptionFactory() { assertNotNull(FactoryUtils.exceptionFactory()); assertSame(FactoryUtils.exceptionFactory(), FactoryUtils.exceptionFactory()); try { FactoryUtils.exceptionFactory().create(); } catch (final FunctorException ex) { try { FactoryUtils.exceptionFactory().create(); } catch (final FunctorException ex2) { return; } } fail(); } // nullFactory //------------------------------------------------------------------ @Test "
0
79
" public void setQuery( MessageBytes queryMB ) { this.queryMB=queryMB; } "
0
80
" private void signIn(String userName, String password) { webDriver.get(baseUrl + "/logout.do"); webDriver.get(baseUrl + "/login"); webDriver.findElement(By.name("username")).sendKeys(userName); webDriver.findElement(By.name("password")).sendKeys(password); webDriver.findElement(By.xpath("//input[@value='Sign in']")).click(); assertThat(webDriver.findElement(By.cssSelector("h1")).getText(), containsString("Where to?")); } "
0
81
" protected void embalmTarget() { if (!gotMethods && target.allowedMethods.isEmpty()) { target.allowedMethods.add(WILDCARD); } target.params = Collections.unmodifiableMap(target.params); target.results = Collections.unmodifiableMap(target.results); target.interceptors = Collections.unmodifiableList(target.interceptors); target.exceptionMappings = Collections.unmodifiableList(target.exceptionMappings); target.allowedMethods = Collections.unmodifiableSet(target.allowedMethods); } } } "
0
82
" public String getCommand() { return agentCommand; } /** * Gets the formatted current time stamp. */ "
0
83
" protected final ApplicationContext getApplicationContext() { return this.context; } @Autowired "
0
84
" private Object readResolve() { this.remote = normalize(this.remote); return this; } "
0
85
" public void setMethodParam(String methodParam) { Assert.hasText(methodParam, "'methodParam' must not be empty"); this.methodParam = methodParam; } @Override "
0
86
" public void toCode(final List<String> lineList, final String requestID, final int indentSpaces, final boolean includeProcessing) { // Create the request variable. final ArrayList<ToCodeArgHelper> constructorArgs = new ArrayList<ToCodeArgHelper>(3); constructorArgs.add(ToCodeArgHelper.createString(bindDN.stringValue(), "Bind DN")); constructorArgs.add(ToCodeArgHelper.createString("---redacted-password---", "Bind Password")); final Control[] controls = getControls(); if (controls.length > 0) { constructorArgs.add(ToCodeArgHelper.createControlArray(controls, "Bind Controls")); } ToCodeHelper.generateMethodCall(lineList, indentSpaces, "SimpleBindRequest", requestID + "Request", "new SimpleBindRequest", constructorArgs); // Add lines for processing the request and obtaining the result. if (includeProcessing) { // Generate a string with the appropriate indent. final StringBuilder buffer = new StringBuilder(); for (int i=0; i < indentSpaces; i++) { buffer.append(' '); } final String indent = buffer.toString(); lineList.add(""); lineList.add(indent + "try"); lineList.add(indent + '{'); lineList.add(indent + " BindResult " + requestID + "Result = connection.bind(" + requestID + "Request);"); lineList.add(indent + " // The bind was processed successfully."); lineList.add(indent + '}'); lineList.add(indent + "catch (LDAPException e)"); lineList.add(indent + '{'); lineList.add(indent + " // The bind failed. Maybe the following will " + "help explain why."); lineList.add(indent + " // Note that the connection is now likely in " + "an unauthenticated state."); lineList.add(indent + " ResultCode resultCode = e.getResultCode();"); lineList.add(indent + " String message = e.getMessage();"); lineList.add(indent + " String matchedDN = e.getMatchedDN();"); lineList.add(indent + " String[] referralURLs = e.getReferralURLs();"); lineList.add(indent + " Control[] responseControls = " + "e.getResponseControls();"); lineList.add(indent + '}'); } } "
0
87
" public void process(Exchange exchange) throws Exception { // if we bridge endpoint then we need to skip matching headers with the HTTP_QUERY to avoid sending // duplicated headers to the receiver, so use this skipRequestHeaders as the list of headers to skip Map<String, Object> skipRequestHeaders = null; if (getEndpoint().isBridgeEndpoint()) { exchange.setProperty(Exchange.SKIP_GZIP_ENCODING, Boolean.TRUE); String queryString = exchange.getIn().getHeader(Exchange.HTTP_QUERY, String.class); if (queryString != null) { skipRequestHeaders = URISupport.parseQuery(queryString, false, true); } // Need to remove the Host key as it should be not used exchange.getIn().getHeaders().remove("host"); } HttpMethod method = createMethod(exchange); Message in = exchange.getIn(); String httpProtocolVersion = in.getHeader(Exchange.HTTP_PROTOCOL_VERSION, String.class); if (httpProtocolVersion != null) { // set the HTTP protocol version HttpMethodParams params = method.getParams(); params.setVersion(HttpVersion.parse(httpProtocolVersion)); } HeaderFilterStrategy strategy = getEndpoint().getHeaderFilterStrategy(); // propagate headers as HTTP headers for (Map.Entry<String, Object> entry : in.getHeaders().entrySet()) { String key = entry.getKey(); Object headerValue = in.getHeader(key); if (headerValue != null) { // use an iterator as there can be multiple values. (must not use a delimiter, and allow empty values) final Iterator<?> it = ObjectHelper.createIterator(headerValue, null, true); // the value to add as request header final List<String> values = new ArrayList<String>(); // if its a multi value then check each value if we can add it and for multi values they // should be combined into a single value while (it.hasNext()) { String value = exchange.getContext().getTypeConverter().convertTo(String.class, it.next()); // we should not add headers for the parameters in the uri if we bridge the endpoint // as then we would duplicate headers on both the endpoint uri, and in HTTP headers as well if (skipRequestHeaders != null && skipRequestHeaders.containsKey(key)) { continue; } if (value != null && strategy != null && !strategy.applyFilterToCamelHeaders(key, value, exchange)) { values.add(value); } } // add the value(s) as a http request header if (values.size() > 0) { // use the default toString of a ArrayList to create in the form [xxx, yyy] // if multi valued, for a single value, then just output the value as is String s = values.size() > 1 ? values.toString() : values.get(0); method.addRequestHeader(key, s); } } } // lets store the result in the output message. try { if (LOG.isDebugEnabled()) { LOG.debug("Executing http {} method: {}", method.getName(), method.getURI().toString()); } int responseCode = executeMethod(method); LOG.debug("Http responseCode: {}", responseCode); if (!throwException) { // if we do not use failed exception then populate response for all response codes populateResponse(exchange, method, in, strategy, responseCode); } else { if (responseCode >= 100 && responseCode < 300) { // only populate response for OK response populateResponse(exchange, method, in, strategy, responseCode); } else { // operation failed so populate exception to throw throw populateHttpOperationFailedException(exchange, method, responseCode); } } } finally { method.releaseConnection(); } } @Override "
0
88
" public String getDisplayName() { return "Culprits"; } } } "
0
89
" private void verifyNoDescendantsWithLocalModifications(final String action) { for (final ProcessGroup descendant : findAllProcessGroups()) { final VersionControlInformation descendantVci = descendant.getVersionControlInformation(); if (descendantVci != null) { final VersionedFlowState flowState = descendantVci.getStatus().getState(); final boolean modified = flowState == VersionedFlowState.LOCALLY_MODIFIED || flowState == VersionedFlowState.LOCALLY_MODIFIED_AND_STALE; if (modified) { throw new IllegalStateException("Process Group cannot " + action + " because it contains a child or descendant Process Group that is under Version Control and " + "has local modifications. Each descendant Process Group that is under Version Control must first be reverted or have its changes pushed to the Flow Registry before " + "this action can be performed on the parent Process Group."); } if (flowState == VersionedFlowState.SYNC_FAILURE) { throw new IllegalStateException("Process Group cannot " + action + " because it contains a child or descendant Process Group that is under Version Control and " + "is not synchronized with the Flow Registry. Each descendant Process Group must first be synchronized with the Flow Registry before this action can be " + "performed on the parent Process Group. NiFi will continue to attempt to communicate with the Flow Registry periodically in the background."); } } } } "
0
90
" public String changePasswordPage() { return "change_password"; } @RequestMapping(value="/change_password.do", method = POST) "
0
91
" private void assertJoe(ScimUser joe) { assertNotNull(joe); assertEquals(JOE_ID, joe.getId()); assertEquals("Joe", joe.getGivenName()); assertEquals("User", joe.getFamilyName()); assertEquals("joe@joe.com", joe.getPrimaryEmail()); assertEquals("joe", joe.getUserName()); assertEquals("+1-222-1234567", joe.getPhoneNumbers().get(0).getValue()); assertNull(joe.getGroups()); } "
0
92
" public boolean getMapperDirectoryRedirectEnabled() { return mapperDirectoryRedirectEnabled; } @Override "
0
93
" void populateResponse(Exchange exchange, JettyContentExchange httpExchange) throws Exception; /** * Gets the header filter strategy * * @return the strategy */ "
0
94
" public void testUtf8MalformedHarmony() { for (byte[] input : MALFORMED) { doHarmonyDecoder(input, true, -1); } } "
0
95
" public void zip_directory() throws IOException { File foo = FileUtils.toFile(getClass().getResource("/org/sonar/api/utils/ZipUtilsTest/shouldZipDirectory/foo.txt")); File dir = foo.getParentFile(); File zip = temp.newFile(); ZipUtils.zipDir(dir, zip); assertThat(zip).exists().isFile(); assertThat(zip.length()).isGreaterThan(1L); Iterator<? extends ZipEntry> zipEntries = Iterators.forEnumeration(new ZipFile(zip).entries()); assertThat(zipEntries).hasSize(4); File unzipDir = temp.newFolder(); ZipUtils.unzip(zip, unzipDir); assertThat(new File(unzipDir, "bar.txt")).exists().isFile(); assertThat(new File(unzipDir, "foo.txt")).exists().isFile(); assertThat(new File(unzipDir, "dir1/hello.properties")).exists().isFile(); } @Test "
0
96
" public void setShouldReset(boolean shouldReset) { m_shouldReset = shouldReset; } /** * A stack of current template modes. */ "
0
97
" public static void initializeSamlUtils() { try { samlTestUtils.initializeSimple(); } catch (ConfigurationException e) { e.printStackTrace(); } } @Override "
0
98
" public void setAllowUnverifiedUsers(boolean allowUnverifiedUsers) { this.allowUnverifiedUsers = allowUnverifiedUsers; } "
0
99
" private static void verifyInsideTargetDirectory(ZipEntry entry, Path entryPath, Path targetDirPath) { if (!entryPath.normalize().startsWith(targetDirPath.normalize())) { // vulnerability - trying to create a file outside the target directory throw new IllegalStateException("Unzipping an entry outside the target directory is not allowed: " + entry.getName()); } } /** * @see #unzip(File, File, Predicate) * @deprecated replaced by {@link Predicate<ZipEntry>} in 6.2. */ @Deprecated @FunctionalInterface "
0
End of preview (truncated to 100 rows)
README.md exists but content is empty. Use the Edit dataset card button to edit it.
Edit dataset card
Evaluate models HF Leaderboard