Zaib/java-vulnerability
851
1,label,code20,0," private List<AuthInfo> createAuthInfo(SolrZkClient zkClient) {3 List<AuthInfo> ret = new LinkedList<AuthInfo>();4 5 // In theory the credentials to add could change here if zookeeper hasn't been initialized6 ZkCredentialsProvider credentialsProvider =7 zkClient.getZkClientConnectionStrategy().getZkCredentialsToAddAutomatically();8 for (ZkCredentialsProvider.ZkCredentials zkCredentials : credentialsProvider.getCredentials()) {9 ret.add(new AuthInfo(zkCredentials.getScheme(), zkCredentials.getAuth()));10 }11 return ret;12 }13 }14}"151,0," public String getCharacterEncoding() {16 return characterEncoding;17 }18 19 20 /**21 * Set the character encoding to be used to read the user name and password.22 *23 * @param encoding The name of the encoding to use24 */25"262,0," public Log getLogger() {27 return logger;28 }29 30"313,0," public void getAbsolutePathTest() {32 String absolutePath = FileUtil.getAbsolutePath(""LICENSE-junit.txt"");33 Assert.assertNotNull(absolutePath);34 String absolutePath2 = FileUtil.getAbsolutePath(absolutePath);35 Assert.assertNotNull(absolutePath2);36 Assert.assertEquals(absolutePath, absolutePath2);37 }38 39 @Test40"414,0," private Collection getPcClassLoaders() {42 if (_pcClassLoaders == null)43 _pcClassLoaders = new ConcurrentReferenceHashSet(44 ConcurrentReferenceHashSet.WEAK);45 46 return _pcClassLoaders;47 }48"495,0," public static void main(String argv[]) throws Exception {50 doMain(SimpleSocketServer.class, argv);51 }52 53"546,0," public JettyHttpComponent getComponent() {55 return (JettyHttpComponent) super.getComponent();56 }57 58 @Override59"607,0," public boolean isConfigured() {61 return order >= CONFIGURING.order;62 }63 }64}"658,0," protected static final boolean isAlpha(String value) {66 for (int i = 0; i < value.length(); i++) {67 char c = value.charAt(i);68 if (!((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'))) {69 return false;70 }71 }72 return true;73 }74 75"769,0," public void fail_if_unzipping_stream_outside_target_directory() throws Exception {77 File zip = new File(getClass().getResource(""ZipUtilsTest/zip-slip.zip"").toURI());78 File toDir = temp.newFolder();79 80 expectedException.expect(IllegalStateException.class);81 expectedException.expectMessage(""Unzipping an entry outside the target directory is not allowed: ../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../../tmp/evil.txt"");82 83 try (InputStream input = new FileInputStream(zip)) {84 ZipUtils.unzip(input, toDir);85 }86 }87 88"8910,0," public TransformerFactory createTransformerFactory() {90 TransformerFactory factory = TransformerFactory.newInstance();91 // Enable the Security feature by default92 try {93 factory.setFeature(javax.xml.XMLConstants.FEATURE_SECURE_PROCESSING, true);94 } catch (TransformerConfigurationException e) {95 LOG.warn(""TransformerFactory doesn't support the feature {} with value {}, due to {}."", new Object[]{javax.xml.XMLConstants.FEATURE_SECURE_PROCESSING, ""true"", e});96 }97 factory.setErrorListener(new XmlErrorListener());98 return factory;99 }100 101"10211,0," public long getAuthenticatedTime() {103 return authenticatedTime;104 }105 106 @Override107 @JsonIgnore108"10912,0," public X509Certificate generateCert(PublicKey publicKey,110 PrivateKey privateKey, String sigalg, int validity, String cn,111 String ou, String o, String l, String st, String c)112 throws java.security.SignatureException,113 java.security.InvalidKeyException {114 X509V1CertificateGenerator certgen = new X509V1CertificateGenerator();115 116 // issuer dn117 Vector order = new Vector();118 Hashtable attrmap = new Hashtable();119 120 if (cn != null) {121 attrmap.put(X509Principal.CN, cn);122 order.add(X509Principal.CN);123 }124 125 if (ou != null) {126 attrmap.put(X509Principal.OU, ou);127 order.add(X509Principal.OU);128 }129 130 if (o != null) {131 attrmap.put(X509Principal.O, o);132 order.add(X509Principal.O);133 }134 135 if (l != null) {136 attrmap.put(X509Principal.L, l);137 order.add(X509Principal.L);138 }139 140 if (st != null) {141 attrmap.put(X509Principal.ST, st);142 order.add(X509Principal.ST);143 }144 145 if (c != null) {146 attrmap.put(X509Principal.C, c);147 order.add(X509Principal.C);148 }149 150 X509Principal issuerDN = new X509Principal(order, attrmap);151 certgen.setIssuerDN(issuerDN);152 153 // validity154 long curr = System.currentTimeMillis();155 long untill = curr + (long) validity * 24 * 60 * 60 * 1000;156 157 certgen.setNotBefore(new Date(curr));158 certgen.setNotAfter(new Date(untill));159 160 // subject dn161 certgen.setSubjectDN(issuerDN);162 163 // public key164 certgen.setPublicKey(publicKey);165 166 // signature alg167 certgen.setSignatureAlgorithm(sigalg);168 169 // serial number170 certgen.setSerialNumber(new BigInteger(String.valueOf(curr)));171 172 // make certificate173 return certgen.generateX509Certificate(privateKey);174 }175"17613,0," public FormValidation doCheckCommand(@QueryParameter String value) {177 if (!Jenkins.getInstance().hasPermission(Jenkins.RUN_SCRIPTS)) {178 return FormValidation.warning(Messages.CommandLauncher_cannot_be_configured_by_non_administrato());179 }180 if (Util.fixEmptyAndTrim(value) == null) {181 return FormValidation.error(Messages.CommandLauncher_NoLaunchCommand());182 } else {183 return FormValidation.ok();184 }185 }186 187 }188}189"19014,0," public void filterWithParameter() throws IOException, ServletException {191 filterWithParameterForMethod(""delete"", ""DELETE"");192 filterWithParameterForMethod(""put"", ""PUT"");193 filterWithParameterForMethod(""patch"", ""PATCH"");194 }195 196 @Test197"19815,0," public void setReplayCache(TokenReplayCache<String> replayCache) {199 this.replayCache = replayCache;200 }201 202"20316,0," public void setUp() throws Exception {204 scimUserProvisioning = mock(ScimUserProvisioning.class);205 expiringCodeStore = mock(ExpiringCodeStore.class);206 passwordValidator = mock(PasswordValidator.class);207 clientDetailsService = mock(ClientDetailsService.class);208 resetPasswordService = new UaaResetPasswordService(scimUserProvisioning, expiringCodeStore, passwordValidator, clientDetailsService);209 PasswordResetEndpoint controller = new PasswordResetEndpoint(resetPasswordService);210 controller.setCodeStore(expiringCodeStore);211 controller.setMessageConverters(new HttpMessageConverter[] { new ExceptionReportHttpMessageConverter() });212 mockMvc = MockMvcBuilders.standaloneSetup(controller).build();213 214 PasswordChange change = new PasswordChange(""id001"", ""user@example.com"", yesterday, null, null);215 216 when(expiringCodeStore.generateCode(eq(""id001""), any(Timestamp.class), eq(null)))217 .thenReturn(new ExpiringCode(""secret_code"", new Timestamp(System.currentTimeMillis() + UaaResetPasswordService.PASSWORD_RESET_LIFETIME), ""id001"", null));218 219 when(expiringCodeStore.generateCode(eq(JsonUtils.writeValueAsString(change)), any(Timestamp.class), eq(null)))220 .thenReturn(new ExpiringCode(""secret_code"", new Timestamp(System.currentTimeMillis() + UaaResetPasswordService.PASSWORD_RESET_LIFETIME), JsonUtils.writeValueAsString(change), null));221 }222 223 @Test224"22517,0," public AhcComponent getComponent() {226 return (AhcComponent) super.getComponent();227 }228 229 @Override230"23118,0," public StandardInterceptUrlRegistry access(String... attributes) {232 addMapping(requestMatchers, SecurityConfig.createList(attributes));233 return UrlAuthorizationConfigurer.this.REGISTRY;234 }235 }236}"23719,0," protected static Object toPoolKey(Map map) {238 Object key = Configurations.getProperty(""Id"", map);239 return ( key != null) ? key : map;240 }241 242 /**243 * Register <code>factory</code> in the pool under <code>key</code>.244 *245 * @since 1.1.0246 */247"24820,0," protected Log getLog() {249 return log;250 }251 252 // ----------------------------------------------------------- Constructors253 254 255"25621,0," public void commence(ServletRequest request, ServletResponse response,257 AuthenticationException authException) throws IOException, ServletException {258 259 HttpServletRequest hrequest = (HttpServletRequest)request;260 HttpServletResponse hresponse = (HttpServletResponse)response;261 FedizContext fedContext = federationConfig.getFedizContext();262 LOG.debug(""Federation context: {}"", fedContext);263 264 // Check to see if it is a metadata request265 MetadataDocumentHandler mdHandler = new MetadataDocumentHandler(fedContext);266 if (mdHandler.canHandleRequest(hrequest)) {267 mdHandler.handleRequest(hrequest, hresponse);268 return;269 }270 271 String redirectUrl = null;272 try {273 FedizProcessor wfProc = 274 FedizProcessorFactory.newFedizProcessor(fedContext.getProtocol());275 276 RedirectionResponse redirectionResponse =277 wfProc.createSignInRequest(hrequest, fedContext);278 redirectUrl = redirectionResponse.getRedirectionURL();279 280 if (redirectUrl == null) {281 LOG.warn(""Failed to create SignInRequest."");282 hresponse.sendError(283 HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ""Failed to create SignInRequest."");284 }285 286 Map<String, String> headers = redirectionResponse.getHeaders();287 if (!headers.isEmpty()) {288 for (Entry<String, String> entry : headers.entrySet()) {289 hresponse.addHeader(entry.getKey(), entry.getValue());290 }291 }292 293 HttpSession session = ((HttpServletRequest)request).getSession(true);294 session.setAttribute(SAVED_CONTEXT, redirectionResponse.getRequestState().getState());295 } catch (ProcessingException ex) {296 System.err.println(""Failed to create SignInRequest: "" + ex.getMessage());297 LOG.warn(""Failed to create SignInRequest: "" + ex.getMessage());298 hresponse.sendError(299 HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ""Failed to create SignInRequest."");300 }301 302 preCommence(hrequest, hresponse);303 if (LOG.isInfoEnabled()) {304 LOG.info(""Redirecting to IDP: "" + redirectUrl);305 }306 hresponse.sendRedirect(redirectUrl);307 308 }309 310"31122,0," public void testSetParameterAndAttributeNames() throws Exception {312 interceptor.setAttributeName(""hello"");313 interceptor.setParameterName(""world"");314 315 params.put(""world"", Locale.CHINA);316 interceptor.intercept(mai);317 318 assertNull(params.get(""world"")); // should have been removed319 320 assertNotNull(session.get(""hello"")); // should be stored here321 assertEquals(Locale.CHINA, session.get(""hello""));322 }323"32423,0," String postProcessVariableName(String variableName) {325 return variableName;326 }327 }328 329}330"33124,0," public Iterable<Cascadable> getCascadables() {332 return cascadables;333 }334 335 @Override336"33725,0," public String getDataSourceName() {338 return dataSourceName;339 }340 341 /**342 * Set the name of the JNDI JDBC DataSource.343 *344 * @param dataSourceName the name of the JNDI JDBC DataSource345 */346"34726,0," public boolean equals(Object obj) {348 if ( this == obj ) {349 return true;350 }351 if ( !super.equals( obj ) ) {352 return false;353 }354 if ( getClass() != obj.getClass() ) {355 return false;356 }357 ConstrainedField other = (ConstrainedField) obj;358 if ( getLocation().getMember() == null ) {359 if ( other.getLocation().getMember() != null ) {360 return false;361 }362 }363 else if ( !getLocation().getMember().equals( other.getLocation().getMember() ) ) {364 return false;365 }366 return true;367 }368"36927,0," public boolean isSingleton() {370 return _singleton;371 }372 373 /**374 * The plugin class name.375 */376"37728,0," public String toXml() {378 379 StringBuilder sb = new StringBuilder(""<user username=\"""");380 sb.append(RequestUtil.filter(username));381 sb.append(""\"" password=\"""");382 sb.append(RequestUtil.filter(password));383 sb.append(""\"""");384 if (fullName != null) {385 sb.append("" fullName=\"""");386 sb.append(RequestUtil.filter(fullName));387 sb.append(""\"""");388 }389 synchronized (groups) {390 if (groups.size() > 0) {391 sb.append("" groups=\"""");392 int n = 0;393 Iterator<Group> values = groups.iterator();394 while (values.hasNext()) {395 if (n > 0) {396 sb.append(',');397 }398 n++;399 sb.append(RequestUtil.filter(values.next().getGroupname()));400 }401 sb.append(""\"""");402 }403 }404 synchronized (roles) {405 if (roles.size() > 0) {406 sb.append("" roles=\"""");407 int n = 0;408 Iterator<Role> values = roles.iterator();409 while (values.hasNext()) {410 if (n > 0) {411 sb.append(',');412 }413 n++;414 sb.append(RequestUtil.filter(values.next().getRolename()));415 }416 sb.append(""\"""");417 }418 }419 sb.append(""/>"");420 return (sb.toString());421 422 }423 424 /**425 * <p>Return a String representation of this user.</p>426 */427 @Override428"42929,0," public static Document signMetaInfo(Crypto crypto, String keyAlias, String keyPassword,430 Document doc, String referenceID) throws Exception {431 if (keyAlias == null || """".equals(keyAlias)) {432 keyAlias = crypto.getDefaultX509Identifier();433 }434 X509Certificate cert = CertsUtils.getX509Certificate(crypto, keyAlias);435// }436 437/* public static ByteArrayOutputStream signMetaInfo(FederationContext config, InputStream metaInfo,438 String referenceID)439 throws Exception {440 441 KeyManager keyManager = config.getSigningKey();442 String keyAlias = keyManager.getKeyAlias();443 String keypass = keyManager.getKeyPassword();444 445 // in case we did not specify the key alias, we assume there is only one key in the keystore ,446 // we use this key's alias as default. 447 if (keyAlias == null || """".equals(keyAlias)) {448 //keyAlias = getDefaultX509Identifier(ks);449 keyAlias = keyManager.getCrypto().getDefaultX509Identifier();450 }451 CryptoType cryptoType = new CryptoType(CryptoType.TYPE.ALIAS);452 cryptoType.setAlias(keyAlias);453 X509Certificate[] issuerCerts = keyManager.getCrypto().getX509Certificates(cryptoType);454 if (issuerCerts == null || issuerCerts.length == 0) {455 throw new ProcessingException(456 ""No issuer certs were found to sign the metadata using issuer name: ""457 + keyAlias);458 }459 X509Certificate cert = issuerCerts[0];460*/ 461 String signatureMethod = null;462 if (""SHA1withDSA"".equals(cert.getSigAlgName())) {463 signatureMethod = SignatureMethod.DSA_SHA1;464 } else if (""SHA1withRSA"".equals(cert.getSigAlgName())) {465 signatureMethod = SignatureMethod.RSA_SHA1;466 } else if (""SHA256withRSA"".equals(cert.getSigAlgName())) {467 signatureMethod = SignatureMethod.RSA_SHA1;468 } else {469 LOG.error(""Unsupported signature method: "" + cert.getSigAlgName());470 throw new RuntimeException(""Unsupported signature method: "" + cert.getSigAlgName());471 }472 473 List<Transform> transformList = new ArrayList<Transform>();474 transformList.add(XML_SIGNATURE_FACTORY.newTransform(Transform.ENVELOPED, (TransformParameterSpec)null));475 transformList.add(XML_SIGNATURE_FACTORY.newCanonicalizationMethod(CanonicalizationMethod.EXCLUSIVE,476 (C14NMethodParameterSpec)null));477 478 // Create a Reference to the enveloped document (in this case,479 // you are signing the whole document, so a URI of """" signifies480 // that, and also specify the SHA1 digest algorithm and481 // the ENVELOPED Transform.482 Reference ref = XML_SIGNATURE_FACTORY.newReference(483 ""#"" + referenceID,484 XML_SIGNATURE_FACTORY.newDigestMethod(DigestMethod.SHA1, null),485 transformList,486 null, null);487 488 // Create the SignedInfo.489 SignedInfo si = XML_SIGNATURE_FACTORY.newSignedInfo(490 XML_SIGNATURE_FACTORY.newCanonicalizationMethod(491 CanonicalizationMethod.EXCLUSIVE, (C14NMethodParameterSpec)null),492 XML_SIGNATURE_FACTORY.newSignatureMethod(493 signatureMethod, null), Collections.singletonList(ref));494 495 // step 2496 // Load the KeyStore and get the signing key and certificate.497 498 PrivateKey keyEntry = crypto.getPrivateKey(keyAlias, keyPassword);499 500 // Create the KeyInfo containing the X509Data.501 KeyInfoFactory kif = XML_SIGNATURE_FACTORY.getKeyInfoFactory();502 List<Object> x509Content = new ArrayList<Object>();503 x509Content.add(cert.getSubjectX500Principal().getName());504 x509Content.add(cert);505 X509Data xd = kif.newX509Data(x509Content);506 KeyInfo ki = kif.newKeyInfo(Collections.singletonList(xd));507 508 // step3509 510 // Create a DOMSignContext and specify the RSA PrivateKey and511 // location of the resulting XMLSignature's parent element.512 //DOMSignContext dsc = new DOMSignContext(keyEntry.getPrivateKey(), doc.getDocumentElement());513 DOMSignContext dsc = new DOMSignContext(keyEntry, doc.getDocumentElement());514 dsc.setIdAttributeNS(doc.getDocumentElement(), null, ""ID"");515 dsc.setNextSibling(doc.getDocumentElement().getFirstChild());516 517 // Create the XMLSignature, but don't sign it yet.518 XMLSignature signature = XML_SIGNATURE_FACTORY.newXMLSignature(si, ki);519 520 // Marshal, generate, and sign the enveloped signature.521 signature.sign(dsc);522 523 // step 4524 // Output the resulting document.525 526 return doc;527 }528 529"53030,0," private Charset getCharset(String encoding) {531 if (encoding == null) {532 return DEFAULT_CHARSET;533 }534 try {535 return B2CConverter.getCharset(encoding);536 } catch (UnsupportedEncodingException e) {537 return DEFAULT_CHARSET;538 }539 }540 541 /**542 * Debug purpose543 */544"54531,0," public ConstrainedParameter getParameterMetaData(int parameterIndex) {546 if ( parameterIndex < 0 || parameterIndex > parameterMetaData.size() - 1 ) {547 throw log.getInvalidExecutableParameterIndexException(548 executable.getAsString(),549 parameterIndex550 );551 }552 553 return parameterMetaData.get( parameterIndex );554 }555 556 /**557 * Returns meta data for all parameters of the represented executable.558 *559 * @return A list with parameter meta data. The length corresponds to the560 * number of parameters of the executable represented by this meta data561 * object, so an empty list may be returned (in case of a562 * parameterless executable), but never {@code null}.563 */564"56532,0," private SendfileState processSendfile(SocketWrapperBase<?> socketWrapper) {566 openSocket = keepAlive;567 // Done is equivalent to sendfile not being used568 SendfileState result = SendfileState.DONE;569 // Do sendfile as needed: add socket to sendfile and end570 if (sendfileData != null && !getErrorState().isError()) {571 sendfileData.keepAlive = keepAlive;572 result = socketWrapper.processSendfile(sendfileData);573 switch (result) {574 case ERROR:575 // Write failed576 if (log.isDebugEnabled()) {577 log.debug(sm.getString(""http11processor.sendfile.error""));578 }579 setErrorState(ErrorState.CLOSE_CONNECTION_NOW, null);580 //$FALL-THROUGH$581 default:582 sendfileData = null;583 }584 }585 return result;586 }587 588 589 @Override590"59133,0," protected String determineTargetUrl(HttpServletRequest request) {592 String targetUrl = request.getParameter(""from"");593 request.getSession().setAttribute(""from"", targetUrl);594 595 if (targetUrl == null)596 return getDefaultTargetUrl();597 598 if (Util.isAbsoluteUri(targetUrl))599 return "".""; // avoid open redirect600 601 // URL returned from determineTargetUrl() is resolved against the context path,602 // whereas the ""from"" URL is resolved against the top of the website, so adjust this.603 if(targetUrl.startsWith(request.getContextPath()))604 return targetUrl.substring(request.getContextPath().length());605 606 // not sure when this happens, but apparently this happens in some case.607 // see #1274608 return targetUrl;609 }610 611 /**612 * @see org.acegisecurity.ui.AbstractProcessingFilter#determineFailureUrl(javax.servlet.http.HttpServletRequest, org.acegisecurity.AuthenticationException)613 */614 @Override615"61634,0," public final void recycle() {617 try {618 // Must clear super's buffer.619 while (ready()) {620 // InputStreamReader#skip(long) will allocate buffer to skip.621 read();622 }623 } catch(IOException ioe){624 }625 }626}627 628 629/** Special output stream where close() is overriden, so super.close()630 is never called.631 632 This allows recycling. It can also be disabled, so callbacks will633 not be called if recycling the converter and if data was not flushed.634*/635final class IntermediateInputStream extends InputStream {636 ByteChunk bc = null;637 638 public IntermediateInputStream() {639 }640 641 public final void close() throws IOException {642 // shouldn't be called - we filter it out in writer643 throw new IOException(""close() called - shouldn't happen "");644 }645 646 public final int read(byte cbuf[], int off, int len) throws IOException {647 return bc.substract(cbuf, off, len);648 }649 650 public final int read() throws IOException {651 return bc.substract();652 }653 654 // -------------------- Internal methods --------------------655 656 657 void setByteChunk( ByteChunk mb ) {658 bc = mb;659 }660 661"66235,0," public void execute(FunctionContext context) {663 RegionFunctionContext rfc = (RegionFunctionContext) context;664 Set<String> keys = (Set<String>) rfc.getFilter();665 666 // Get local (primary) data for the context667 Region primaryDataSet = PartitionRegionHelper.getLocalDataForContext(rfc);668 669 if (this.cache.getLogger().fineEnabled()) {670 StringBuilder builder = new StringBuilder();671 builder.append(""Function "").append(ID).append("" received request to touch "")672 .append(primaryDataSet.getFullPath()).append(""->"").append(keys);673 this.cache.getLogger().fine(builder.toString());674 }675 676 // Retrieve each value to update the lastAccessedTime.677 // Note: getAll is not supported on LocalDataSet.678 for (String key : keys) {679 primaryDataSet.get(key);680 }681 682 // Return result to get around NPE in LocalResultCollectorImpl683 context.getResultSender().lastResult(true);684 }685 686 @Override687"68836,0," private static boolean isFile(Path src) {689 return Files.exists(src) && Files.isRegularFile(src);690 }691"69237,0," public BeanDefinition parse(Element element, ParserContext pc) {693 CompositeComponentDefinition compositeDef = new CompositeComponentDefinition(694 element.getTagName(), pc.extractSource(element));695 pc.pushContainingComponent(compositeDef);696 697 registerFilterChainProxyIfNecessary(pc, pc.extractSource(element));698 699 // Obtain the filter chains and add the new chain to it700 BeanDefinition listFactoryBean = pc.getRegistry().getBeanDefinition(701 BeanIds.FILTER_CHAINS);702 List<BeanReference> filterChains = (List<BeanReference>) listFactoryBean703 .getPropertyValues().getPropertyValue(""sourceList"").getValue();704 705 filterChains.add(createFilterChain(element, pc));706 707 pc.popAndRegisterContainingComponent();708 return null;709 }710 711 /**712 * Creates the {@code SecurityFilterChain} bean from an <http> element.713 */714"71538,0," public void destroy() {716 normalView = null;717 viewViews = null;718 viewServers = null;719 viewGraphs = null;720 pageView = null;721 editView = null;722 addView = null;723 addGraph = null;724 editGraph = null;725 viewServer = null;726 editServer = null;727 addServer = null;728 helpView = null;729 editNormalView = null;730 super.destroy();731 }732"73339,0," public BeanDefinition parse(Element elt, ParserContext pc) {734 MatcherType matcherType = MatcherType.fromElement(elt);735 String path = elt.getAttribute(HttpSecurityBeanDefinitionParser.ATT_PATH_PATTERN);736 String requestMatcher = elt.getAttribute(ATT_REQUEST_MATCHER_REF);737 String filters = elt.getAttribute(HttpSecurityBeanDefinitionParser.ATT_FILTERS);738 739 BeanDefinitionBuilder builder = BeanDefinitionBuilder740 .rootBeanDefinition(DefaultSecurityFilterChain.class);741 742 if (StringUtils.hasText(path)) {743 Assert.isTrue(!StringUtils.hasText(requestMatcher), """");744 builder.addConstructorArgValue(matcherType.createMatcher(pc, path, null));745 }746 else {747 Assert.isTrue(StringUtils.hasText(requestMatcher), """");748 builder.addConstructorArgReference(requestMatcher);749 }750 751 if (filters.equals(HttpSecurityBeanDefinitionParser.OPT_FILTERS_NONE)) {752 builder.addConstructorArgValue(Collections.EMPTY_LIST);753 }754 else {755 String[] filterBeanNames = StringUtils.tokenizeToStringArray(filters, "","");756 ManagedList<RuntimeBeanReference> filterChain = new ManagedList<RuntimeBeanReference>(757 filterBeanNames.length);758 759 for (String name : filterBeanNames) {760 filterChain.add(new RuntimeBeanReference(name));761 }762 763 builder.addConstructorArgValue(filterChain);764 }765 766 return builder.getBeanDefinition();767 }768"76940,0," public long end() throws IOException {770 return 0;771 }772 773"77441,0," public static <E> Closure<E> whileClosure(final Predicate<? super E> predicate,775 final Closure<? super E> closure, final boolean doLoop) {776 if (predicate == null) {777 throw new NullPointerException(""Predicate must not be null"");778 }779 if (closure == null) {780 throw new NullPointerException(""Closure must not be null"");781 }782 return new WhileClosure<E>(predicate, closure, doLoop);783 }784 785 /**786 * Constructor that performs no validation.787 * Use <code>whileClosure</code> if you want that.788 *789 * @param predicate the predicate used to evaluate when the loop terminates, not null790 * @param closure the closure the execute, not null791 * @param doLoop true to act as a do-while loop, always executing the closure once792 */793"79442,0," public void setDefaultHostName(String defaultHostName) {795 this.defaultHostName = defaultHostName;796 }797 798 /**799 * Add a new host to the mapper.800 *801 * @param name Virtual host name802 * @param aliases Alias names for the virtual host803 * @param host Host object804 */805"80643,0," protected void startInternal() throws LifecycleException {807 808 // Create the roles PreparedStatement string809 StringBuilder temp = new StringBuilder(""SELECT "");810 temp.append(roleNameCol);811 temp.append("" FROM "");812 temp.append(userRoleTable);813 temp.append("" WHERE "");814 temp.append(userNameCol);815 temp.append("" = ?"");816 preparedRoles = temp.toString();817 818 // Create the credentials PreparedStatement string819 temp = new StringBuilder(""SELECT "");820 temp.append(userCredCol);821 temp.append("" FROM "");822 temp.append(userTable);823 temp.append("" WHERE "");824 temp.append(userNameCol);825 temp.append("" = ?"");826 preparedCredentials = temp.toString();827 828 super.startInternal();829 }830"83144,0," public XMLLoader init(SolrParams args) {832 // Init StAX parser:833 inputFactory = XMLInputFactory.newInstance();834 EmptyEntityResolver.configureXMLInputFactory(inputFactory);835 inputFactory.setXMLReporter(xmllog);836 try {837 // The java 1.6 bundled stax parser (sjsxp) does not currently have a thread-safe838 // XMLInputFactory, as that implementation tries to cache and reuse the839 // XMLStreamReader. Setting the parser-specific ""reuse-instance"" property to false840 // prevents this.841 // All other known open-source stax parsers (and the bea ref impl)842 // have thread-safe factories.843 inputFactory.setProperty(""reuse-instance"", Boolean.FALSE);844 } catch (IllegalArgumentException ex) {845 // Other implementations will likely throw this exception since ""reuse-instance""846 // isimplementation specific.847 log.debug(""Unable to set the 'reuse-instance' property for the input chain: "" + inputFactory);848 }849 850 // Init SAX parser (for XSL):851 saxFactory = SAXParserFactory.newInstance();852 saxFactory.setNamespaceAware(true); // XSL needs this!853 EmptyEntityResolver.configureSAXParserFactory(saxFactory);854 855 xsltCacheLifetimeSeconds = XSLT_CACHE_DEFAULT;856 if(args != null) {857 xsltCacheLifetimeSeconds = args.getInt(XSLT_CACHE_PARAM,XSLT_CACHE_DEFAULT);858 log.info(""xsltCacheLifetimeSeconds="" + xsltCacheLifetimeSeconds);859 }860 return this;861 }862 863"86445,0," public void setParameterName(String parameterName) {865 this.parameterName = parameterName;866 }867 868"86946,0," public byte[] asSerializedByteArray() {870 int kdfInfo = cipherText_.getKDFInfo();871 debug(""asSerializedByteArray: kdfInfo = "" + kdfInfo);872 long timestamp = cipherText_.getEncryptionTimestamp();873 String cipherXform = cipherText_.getCipherTransformation();874 assert cipherText_.getKeySize() < Short.MAX_VALUE :875 ""Key size too large. Max is "" + Short.MAX_VALUE;876 short keySize = (short) cipherText_.getKeySize();877 assert cipherText_.getBlockSize() < Short.MAX_VALUE :878 ""Block size too large. Max is "" + Short.MAX_VALUE;879 short blockSize = (short) cipherText_.getBlockSize();880 byte[] iv = cipherText_.getIV();881 assert iv.length < Short.MAX_VALUE :882 ""IV size too large. Max is "" + Short.MAX_VALUE;883 short ivLen = (short) iv.length;884 byte[] rawCiphertext = cipherText_.getRawCipherText();885 int ciphertextLen = rawCiphertext.length;886 assert ciphertextLen >= 1 : ""Raw ciphertext length must be >= 1 byte."";887 byte[] mac = cipherText_.getSeparateMAC();888 assert mac.length < Short.MAX_VALUE :889 ""MAC length too large. Max is "" + Short.MAX_VALUE;890 short macLen = (short) mac.length;891 892 byte[] serializedObj = computeSerialization(kdfInfo,893 timestamp,894 cipherXform,895 keySize,896 blockSize,897 ivLen,898 iv,899 ciphertextLen,900 rawCiphertext,901 macLen,902 mac903 );904 905 return serializedObj;906 }907 908 /**909 * Return the actual {@code CipherText} object.910 * @return The {@code CipherText} object that we are serializing.911 */912"91347,0," public void testContextRoot_Bug53339() throws Exception {914 Tomcat tomcat = getTomcatInstance();915 tomcat.enableNaming();916 917 // No file system docBase required918 Context ctx = tomcat.addContext("""", null);919 920 Tomcat.addServlet(ctx, ""Bug53356"", new Bug53356Servlet());921 ctx.addServletMapping("""", ""Bug53356"");922 923 tomcat.start();924 925 ByteChunk body = getUrl(""http://localhost:"" + getPort());926 927 Assert.assertEquals(""OK"", body.toString());928 }929 930"93148,0," protected void execute() {932 933 if (controllersListStrings == null && !removeCont && !removeAll) {934 print(""No controller are given, skipping."");935 return;936 }937 if (controllersListStrings != null) {938 Arrays.asList(controllersListStrings).forEach(939 cInfoString -> {940 ControllerInfo controllerInfo = parseCInfoString(cInfoString);941 if (controllerInfo != null) {942 controllers.add(controllerInfo);943 }944 });945 }946 DriverService service = get(DriverService.class);947 deviceId = DeviceId.deviceId(uri);948 DriverHandler h = service.createHandler(deviceId);949 ControllerConfig config = h.behaviour(ControllerConfig.class);950 print(""before:"");951 config.getControllers().forEach(c -> print(c.target()));952 try {953 if (removeAll) {954 if (!controllers.isEmpty()) {955 print(""Controllers list should be empty to remove all controllers"");956 } else {957 List<ControllerInfo> controllersToRemove = config.getControllers();958 controllersToRemove.forEach(c -> print(""Will remove "" + c.target()));959 config.removeControllers(controllersToRemove);960 }961 } else {962 if (controllers.isEmpty()) {963 print(""Controllers list is empty, cannot set/remove empty controllers"");964 } else {965 if (removeCont) {966 print(""Will remove specified controllers"");967 config.removeControllers(controllers);968 } else {969 print(""Will add specified controllers"");970 config.setControllers(controllers);971 }972 }973 }974 } catch (NullPointerException e) {975 print(""No Device with requested parameters {} "", uri);976 }977 print(""after:"");978 config.getControllers().forEach(c -> print(c.target()));979 print(""size %d"", config.getControllers().size());980 }981 982 983"98449,0," protected void saveLocale(ActionInvocation invocation, Locale locale) {985 invocation.getInvocationContext().setLocale(locale);986 }987 988"98950,0," public boolean isFinished() {990 return endChunk;991 }992"99351,0," public void test1() throws ANTLRException {994 new CronTab(""@yearly"");995 new CronTab(""@weekly"");996 new CronTab(""@midnight"");997 new CronTab(""@monthly"");998 new CronTab(""0 0 * 1-10/3 *"");999 }1000 1001 @Test1002"100352,0," public void multiByteReadThrowsAtEofForCorruptedStoredEntry() throws Exception {1004 byte[] content;1005 try (FileInputStream fs = new FileInputStream(getFile(""COMPRESS-264.zip""))) {1006 content = IOUtils.toByteArray(fs);1007 }1008 // make size much bigger than entry's real size1009 for (int i = 17; i < 26; i++) {1010 content[i] = (byte) 0xff;1011 }1012 byte[] buf = new byte[2];1013 try (ByteArrayInputStream in = new ByteArrayInputStream(content);1014 ZipArchiveInputStream archive = new ZipArchiveInputStream(in)) {1015 ArchiveEntry e = archive.getNextEntry();1016 try {1017 IOUtils.toByteArray(archive);1018 fail(""expected exception"");1019 } catch (IOException ex) {1020 assertEquals(""Truncated ZIP file"", ex.getMessage());1021 }1022 try {1023 archive.read(buf);1024 fail(""expected exception"");1025 } catch (IOException ex) {1026 assertEquals(""Truncated ZIP file"", ex.getMessage());1027 }1028 try {1029 archive.read(buf);1030 fail(""expected exception"");1031 } catch (IOException ex) {1032 assertEquals(""Truncated ZIP file"", ex.getMessage());1033 }1034 }1035 }1036 1037"103853,0," public void testRead7ZipMultiVolumeArchiveForStream() throws IOException {1039 1040 final FileInputStream archive =1041 new FileInputStream(getFile(""apache-maven-2.2.1.zip.001""));1042 ZipArchiveInputStream zi = null;1043 try {1044 zi = new ZipArchiveInputStream(archive,null,false);1045 1046 // these are the entries that are supposed to be processed1047 // correctly without any problems1048 for (final String element : ENTRIES) {1049 assertEquals(element, zi.getNextEntry().getName());1050 }1051 1052 // this is the last entry that is truncated1053 final ArchiveEntry lastEntry = zi.getNextEntry();1054 assertEquals(LAST_ENTRY_NAME, lastEntry.getName());1055 final byte [] buffer = new byte [4096];1056 1057 // before the fix, we'd get 0 bytes on this read and all1058 // subsequent reads thus a client application might enter1059 // an infinite loop after the fix, we should get an1060 // exception1061 try {1062 while (zi.read(buffer) > 0) { }1063 fail(""shouldn't be able to read from truncated entry"");1064 } catch (final IOException e) {1065 assertEquals(""Truncated ZIP file"", e.getMessage());1066 }1067 1068 try {1069 zi.read(buffer);1070 fail(""shouldn't be able to read from truncated entry after exception"");1071 } catch (final IOException e) {1072 assertEquals(""Truncated ZIP file"", e.getMessage());1073 }1074 1075 // and now we get another entry, which should also yield1076 // an exception1077 try {1078 zi.getNextEntry();1079 fail(""shouldn't be able to read another entry from truncated""1080 + "" file"");1081 } catch (final IOException e) {1082 // this is to be expected1083 }1084 } finally {1085 if (zi != null) {1086 zi.close();1087 }1088 }1089 }1090 1091 @Test(expected=IOException.class)1092"109354,0," public static Charset getCharset(String enc)1094 throws UnsupportedEncodingException {1095 1096 // Encoding names should all be ASCII1097 String lowerCaseEnc = enc.toLowerCase(Locale.US);1098 1099 Charset charset = (Charset) encodingToCharsetCache.get(lowerCaseEnc);1100 1101 if (charset == null) {1102 // Pre-population of the cache means this must be invalid1103 throw new UnsupportedEncodingException(enc);1104 }1105 return charset;1106 }1107 1108"110955,0," public final String convert(String str, boolean query)1110 {1111 if (str == null) return null;1112 1113 if( (!query || str.indexOf( '+' ) < 0) && str.indexOf( '%' ) < 0 )1114 return str;1115 1116 StringBuffer dec = new StringBuffer(); // decoded string output1117 int strPos = 0;1118 int strLen = str.length();1119 1120 dec.ensureCapacity(str.length());1121 while (strPos < strLen) {1122 int laPos; // lookahead position1123 1124 // look ahead to next URLencoded metacharacter, if any1125 for (laPos = strPos; laPos < strLen; laPos++) {1126 char laChar = str.charAt(laPos);1127 if ((laChar == '+' && query) || (laChar == '%')) {1128 break;1129 }1130 }1131 1132 // if there were non-metacharacters, copy them all as a block1133 if (laPos > strPos) {1134 dec.append(str.substring(strPos,laPos));1135 strPos = laPos;1136 }1137 1138 // shortcut out of here if we're at the end of the string1139 if (strPos >= strLen) {1140 break;1141 }1142 1143 // process next metacharacter1144 char metaChar = str.charAt(strPos);1145 if (metaChar == '+') {1146 dec.append(' ');1147 strPos++;1148 continue;1149 } else if (metaChar == '%') {1150 // We throw the original exception - the super will deal with1151 // it1152 // try {1153 dec.append((char)Integer.1154 parseInt(str.substring(strPos + 1, strPos + 3),16));1155 strPos += 3;1156 }1157 }1158 1159 return dec.toString();1160 }1161 1162 1163 1164"116556,0," public String[] getGroups() {1166 1167 UserDatabase database = (UserDatabase) this.resource;1168 ArrayList<String> results = new ArrayList<String>();1169 Iterator<Group> groups = database.getGroups();1170 while (groups.hasNext()) {1171 Group group = groups.next();1172 results.add(findGroup(group.getGroupname()));1173 }1174 return results.toArray(new String[results.size()]);1175 1176 }1177 1178 1179 /**1180 * Return the MBean Names of all roles defined in this database.1181 */1182"118357,0," public void testEntities() throws Exception1184 {1185 // use a binary file, so when it's loaded fail with XML eror:1186 String file = getFile(""mailing_lists.pdf"").toURI().toASCIIString();1187 String xml = 1188 ""<?xml version=\""1.0\""?>"" +1189 ""<!DOCTYPE foo ["" + 1190 // check that external entities are not resolved!1191 ""<!ENTITY bar SYSTEM \""""+file+""\"">""+1192 // but named entities should be1193 ""<!ENTITY wacky \""zzz\"">""+1194 ""]>"" +1195 ""<random>"" +1196 "" &bar;"" +1197 "" <document>"" +1198 "" <node name=\""id\"" value=\""12345\""/>"" +1199 "" <node name=\""foo_s\"" value=\""&wacky;\""/>"" +1200 "" </document>"" +