Unnamed: 0
int64
0
637
label
int64
0
1
code
stringlengths
24
8.83k
0
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; } } }
1
0
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 */
2
0
public Log getLogger() { return logger; }
3
0
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
4
0
private Collection getPcClassLoaders() { if (_pcClassLoaders == null) _pcClassLoaders = new ConcurrentReferenceHashSet( ConcurrentReferenceHashSet.WEAK); return _pcClassLoaders; }
5
0
public static void main(String argv[]) throws Exception { doMain(SimpleSocketServer.class, argv); }
6
0
public JettyHttpComponent getComponent() { return (JettyHttpComponent) super.getComponent(); } @Override
7
0
public boolean isConfigured() { return order >= CONFIGURING.order; } } }
8
0
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; }
9
0
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); } }
10
0
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; }
11
0
public long getAuthenticatedTime() { return authenticatedTime; } @Override @JsonIgnore
12
0
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); }
13
0
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(); } } } }
14
0
public void filterWithParameter() throws IOException, ServletException { filterWithParameterForMethod("delete", "DELETE"); filterWithParameterForMethod("put", "PUT"); filterWithParameterForMethod("patch", "PATCH"); } @Test
15
0
public void setReplayCache(TokenReplayCache<String> replayCache) { this.replayCache = replayCache; }
16
0
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
17
0
public AhcComponent getComponent() { return (AhcComponent) super.getComponent(); } @Override
18
0
public StandardInterceptUrlRegistry access(String... attributes) { addMapping(requestMatchers, SecurityConfig.createList(attributes)); return UrlAuthorizationConfigurer.this.REGISTRY; } } }
19
0
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 */
20
0
protected Log getLog() { return log; } // ----------------------------------------------------------- Constructors
21
0
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); }
22
0
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")); }
23
0
String postProcessVariableName(String variableName) { return variableName; } } }
24
0
public Iterable<Cascadable> getCascadables() { return cascadables; } @Override
25
0
public String getDataSourceName() { return dataSourceName; } /** * Set the name of the JNDI JDBC DataSource. * * @param dataSourceName the name of the JNDI JDBC DataSource */
26
0
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; }
27
0
public boolean isSingleton() { return _singleton; } /** * The plugin class name. */
28
0
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
29
0
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; }
30
0
private Charset getCharset(String encoding) { if (encoding == null) { return DEFAULT_CHARSET; } try { return B2CConverter.getCharset(encoding); } catch (UnsupportedEncodingException e) { return DEFAULT_CHARSET; } } /** * Debug purpose */
31
0
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}. */
32
0
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
33
0
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
34
0
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; }
35
0
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
36
0
private static boolean isFile(Path src) { return Files.exists(src) && Files.isRegularFile(src); }
37
0
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. */
38
0
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(); }
39
0
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(); }
40
0
public long end() throws IOException { return 0; }
41
0
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 */
42
0
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 */
43
0
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(); }
44
0
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; }
45
0
public void setParameterName(String parameterName) { this.parameterName = parameterName; }
46
0
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. */
47
0
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()); }
48
0
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()); }
49
0
protected void saveLocale(ActionInvocation invocation, Locale locale) { invocation.getInvocationContext().setLocale(locale); }
50
0
public boolean isFinished() { return endChunk; }
51
0
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
52
0
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()); } } }
53
0
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)
54
0
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; }
55
0
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(); }
56
0
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. */
57
0
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(); }
58
0
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")
59
0
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
60
0
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); }
61
0
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 */
62
0
private static synchronized PyObject get_dis() { if (dis == null) { dis = __builtin__.__import__("dis"); } return dis; }
63
0
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); } }
64
0
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; }
65
0
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); } }
66
0
public Permission getRequiredPermission() { return Jenkins.ADMINISTER; }
67
0
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()); } }
68
0
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
69
0
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); }
70
0
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()); }
71
0
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> */
72
0
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()); }
73
0
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(); }
74
0
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 */
75
0
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); } } } }
76
0
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
77
0
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
78
0
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
79
0
public void setQuery( MessageBytes queryMB ) { this.queryMB=queryMB; }
80
0
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?")); }
81
0
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); } } }
82
0
public String getCommand() { return agentCommand; } /** * Gets the formatted current time stamp. */
83
0
protected final ApplicationContext getApplicationContext() { return this.context; } @Autowired
84
0
private Object readResolve() { this.remote = normalize(this.remote); return this; }
85
0
public void setMethodParam(String methodParam) { Assert.hasText(methodParam, "'methodParam' must not be empty"); this.methodParam = methodParam; } @Override
86
0
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 + '}'); } }
87
0
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
88
0
public String getDisplayName() { return "Culprits"; } } }
89
0
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."); } } } }
90
0
public String changePasswordPage() { return "change_password"; } @RequestMapping(value="/change_password.do", method = POST)
91
0
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()); }
92
0
public boolean getMapperDirectoryRedirectEnabled() { return mapperDirectoryRedirectEnabled; } @Override
93
0
void populateResponse(Exchange exchange, JettyContentExchange httpExchange) throws Exception; /** * Gets the header filter strategy * * @return the strategy */
94
0
public void testUtf8MalformedHarmony() { for (byte[] input : MALFORMED) { doHarmonyDecoder(input, true, -1); } }
95
0
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
96
0
public void setShouldReset(boolean shouldReset) { m_shouldReset = shouldReset; } /** * A stack of current template modes. */
97
0
public static void initializeSamlUtils() { try { samlTestUtils.initializeSimple(); } catch (ConfigurationException e) { e.printStackTrace(); } } @Override
98
0
public void setAllowUnverifiedUsers(boolean allowUnverifiedUsers) { this.allowUnverifiedUsers = allowUnverifiedUsers; }
99
0
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
README.md exists but content is empty. Use the Edit dataset card button to edit it.
Downloads last month
53
Edit dataset card