CoolFace
Datasetpublic

Zaib/java-vulnerability

sourceHugging Faceafl-3.0updated 4y agoView on Hugging Face
8likes51downloads
test.csv11456 linesDownload Raw Back to root
1,label,code20,0,"    private static void initKeyPair(SecureRandom prng) throws NoSuchAlgorithmException {3        String sigAlg = signatureAlgorithm.toLowerCase();4        if ( sigAlg.endsWith(""withdsa"") ) {5            //6            // Admittedly, this is a kludge. However for Sun JCE, even though7            // ""SHA1withDSA"" is a valid signature algorithm name, if one calls8            //      KeyPairGenerator kpg = KeyPairGenerator.getInstance(""SHA1withDSA"");9            // that will throw a NoSuchAlgorithmException with an exception10            // message of ""SHA1withDSA KeyPairGenerator not available"". Since11            // SHA1withDSA and DSA keys should be identical, we use ""DSA""12            // in the case that SHA1withDSA or SHAwithDSA was specified. This is13            // all just to make these 2 work as expected. Sigh. (Note:14            // this was tested with JDK 1.6.0_21, but likely fails with earlier15            // versions of the JDK as well.)16            //17            sigAlg = ""DSA"";18        } else if ( sigAlg.endsWith(""withrsa"") ) {19            // Ditto for RSA.20            sigAlg = ""RSA"";21        }22        KeyPairGenerator keyGen = KeyPairGenerator.getInstance(sigAlg);23        keyGen.initialize(signatureKeyLength, prng);24        KeyPair pair = keyGen.generateKeyPair();25        privateKey = pair.getPrivate();26        publicKey = pair.getPublic();27    }28"291,0,"    public ZipArchiveEntry getNextZipEntry() throws IOException {30        uncompressedCount = 0;31 32        boolean firstEntry = true;33        if (closed || hitCentralDirectory) {34            return null;35        }36        if (current != null) {37            closeEntry();38            firstEntry = false;39        }40 41        long currentHeaderOffset = getBytesRead();42        try {43            if (firstEntry) {44                // split archives have a special signature before the45                // first local file header - look for it and fail with46                // the appropriate error message if this is a split47                // archive.48                readFirstLocalFileHeader(lfhBuf);49            } else {50                readFully(lfhBuf);51            }52        } catch (final EOFException e) {53            return null;54        }55 56        final ZipLong sig = new ZipLong(lfhBuf);57        if (!sig.equals(ZipLong.LFH_SIG)) {58            if (sig.equals(ZipLong.CFH_SIG) || sig.equals(ZipLong.AED_SIG) || isApkSigningBlock(lfhBuf)) {59                hitCentralDirectory = true;60                skipRemainderOfArchive();61                return null;62            }63            throw new ZipException(String.format(""Unexpected record signature: 0X%X"", sig.getValue()));64        }65 66        int off = WORD;67        current = new CurrentEntry();68 69        final int versionMadeBy = ZipShort.getValue(lfhBuf, off);70        off += SHORT;71        current.entry.setPlatform((versionMadeBy >> ZipFile.BYTE_SHIFT) & ZipFile.NIBLET_MASK);72 73        final GeneralPurposeBit gpFlag = GeneralPurposeBit.parse(lfhBuf, off);74        final boolean hasUTF8Flag = gpFlag.usesUTF8ForNames();75        final ZipEncoding entryEncoding = hasUTF8Flag ? ZipEncodingHelper.UTF8_ZIP_ENCODING : zipEncoding;76        current.hasDataDescriptor = gpFlag.usesDataDescriptor();77        current.entry.setGeneralPurposeBit(gpFlag);78 79        off += SHORT;80 81        current.entry.setMethod(ZipShort.getValue(lfhBuf, off));82        off += SHORT;83 84        final long time = ZipUtil.dosToJavaTime(ZipLong.getValue(lfhBuf, off));85        current.entry.setTime(time);86        off += WORD;87 88        ZipLong size = null, cSize = null;89        if (!current.hasDataDescriptor) {90            current.entry.setCrc(ZipLong.getValue(lfhBuf, off));91            off += WORD;92 93            cSize = new ZipLong(lfhBuf, off);94            off += WORD;95 96            size = new ZipLong(lfhBuf, off);97            off += WORD;98        } else {99            off += 3 * WORD;100        }101 102        final int fileNameLen = ZipShort.getValue(lfhBuf, off);103 104        off += SHORT;105 106        final int extraLen = ZipShort.getValue(lfhBuf, off);107        off += SHORT; // NOSONAR - assignment as documentation108 109        final byte[] fileName = new byte[fileNameLen];110        readFully(fileName);111        current.entry.setName(entryEncoding.decode(fileName), fileName);112        if (hasUTF8Flag) {113            current.entry.setNameSource(ZipArchiveEntry.NameSource.NAME_WITH_EFS_FLAG);114        }115 116        final byte[] extraData = new byte[extraLen];117        readFully(extraData);118        current.entry.setExtra(extraData);119 120        if (!hasUTF8Flag && useUnicodeExtraFields) {121            ZipUtil.setNameAndCommentFromExtraFields(current.entry, fileName, null);122        }123 124        processZip64Extra(size, cSize);125 126        current.entry.setLocalHeaderOffset(currentHeaderOffset);127        current.entry.setDataOffset(getBytesRead());128        current.entry.setStreamContiguous(true);129 130        ZipMethod m = ZipMethod.getMethodByCode(current.entry.getMethod());131        if (current.entry.getCompressedSize() != ArchiveEntry.SIZE_UNKNOWN) {132            if (ZipUtil.canHandleEntryData(current.entry) && m != ZipMethod.STORED && m != ZipMethod.DEFLATED) {133                InputStream bis = new BoundedInputStream(in, current.entry.getCompressedSize());134                switch (m) {135                case UNSHRINKING:136                    current.in = new UnshrinkingInputStream(bis);137                    break;138                case IMPLODING:139                    current.in = new ExplodingInputStream(140                        current.entry.getGeneralPurposeBit().getSlidingDictionarySize(),141                        current.entry.getGeneralPurposeBit().getNumberOfShannonFanoTrees(),142                        bis);143                    break;144                case BZIP2:145                    current.in = new BZip2CompressorInputStream(bis);146                    break;147                case ENHANCED_DEFLATED:148                    current.in = new Deflate64CompressorInputStream(bis);149                    break;150                default:151                    // we should never get here as all supported methods have been covered152                    // will cause an error when read is invoked, don't throw an exception here so people can153                    // skip unsupported entries154                    break;155                }156            }157        } else if (m == ZipMethod.ENHANCED_DEFLATED) {158            current.in = new Deflate64CompressorInputStream(in);159        }160 161        entriesRead++;162        return current.entry;163    }164 165    /**166     * Fills the given array with the first local file header and167     * deals with splitting/spanning markers that may prefix the first168     * LFH.169     */170"1712,0,"    private static void assertCorrectConfig(User user, String unixPath) {172        assertThat(user.getConfigFile().getFile().getPath(), endsWith(unixPath.replace('/', File.separatorChar)));173    }174 175"1763,0,"    public void testRepositoryCreation() throws Exception {177        Client client = client();178 179        File location = randomRepoPath();180 181        logger.info(""-->  creating repository"");182        PutRepositoryResponse putRepositoryResponse = client.admin().cluster().preparePutRepository(""test-repo-1"")183                .setType(""fs"").setSettings(ImmutableSettings.settingsBuilder()184                                .put(""location"", location)185                ).get();186        assertThat(putRepositoryResponse.isAcknowledged(), equalTo(true));187 188        logger.info(""--> verify the repository"");189        int numberOfFiles = location.listFiles().length;190        VerifyRepositoryResponse verifyRepositoryResponse = client.admin().cluster().prepareVerifyRepository(""test-repo-1"").get();191        assertThat(verifyRepositoryResponse.getNodes().length, equalTo(cluster().numDataAndMasterNodes()));192 193        logger.info(""--> verify that we didn't leave any files as a result of verification"");194        assertThat(location.listFiles().length, equalTo(numberOfFiles));195 196        logger.info(""--> check that repository is really there"");197        ClusterStateResponse clusterStateResponse = client.admin().cluster().prepareState().clear().setMetaData(true).get();198        MetaData metaData = clusterStateResponse.getState().getMetaData();199        RepositoriesMetaData repositoriesMetaData = metaData.custom(RepositoriesMetaData.TYPE);200        assertThat(repositoriesMetaData, notNullValue());201        assertThat(repositoriesMetaData.repository(""test-repo-1""), notNullValue());202        assertThat(repositoriesMetaData.repository(""test-repo-1"").type(), equalTo(""fs""));203 204        logger.info(""-->  creating another repository"");205        putRepositoryResponse = client.admin().cluster().preparePutRepository(""test-repo-2"")206                .setType(""fs"").setSettings(ImmutableSettings.settingsBuilder()207                                .put(""location"", randomRepoPath())208                ).get();209        assertThat(putRepositoryResponse.isAcknowledged(), equalTo(true));210 211        logger.info(""--> check that both repositories are in cluster state"");212        clusterStateResponse = client.admin().cluster().prepareState().clear().setMetaData(true).get();213        metaData = clusterStateResponse.getState().getMetaData();214        repositoriesMetaData = metaData.custom(RepositoriesMetaData.TYPE);215        assertThat(repositoriesMetaData, notNullValue());216        assertThat(repositoriesMetaData.repositories().size(), equalTo(2));217        assertThat(repositoriesMetaData.repository(""test-repo-1""), notNullValue());218        assertThat(repositoriesMetaData.repository(""test-repo-1"").type(), equalTo(""fs""));219        assertThat(repositoriesMetaData.repository(""test-repo-2""), notNullValue());220        assertThat(repositoriesMetaData.repository(""test-repo-2"").type(), equalTo(""fs""));221 222        logger.info(""--> check that both repositories can be retrieved by getRepositories query"");223        GetRepositoriesResponse repositoriesResponse = client.admin().cluster().prepareGetRepositories().get();224        assertThat(repositoriesResponse.repositories().size(), equalTo(2));225        assertThat(findRepository(repositoriesResponse.repositories(), ""test-repo-1""), notNullValue());226        assertThat(findRepository(repositoriesResponse.repositories(), ""test-repo-2""), notNullValue());227 228        logger.info(""--> delete repository test-repo-1"");229        client.admin().cluster().prepareDeleteRepository(""test-repo-1"").get();230        repositoriesResponse = client.admin().cluster().prepareGetRepositories().get();231        assertThat(repositoriesResponse.repositories().size(), equalTo(1));232        assertThat(findRepository(repositoriesResponse.repositories(), ""test-repo-2""), notNullValue());233 234        logger.info(""--> delete repository test-repo-2"");235        client.admin().cluster().prepareDeleteRepository(""test-repo-2"").get();236        repositoriesResponse = client.admin().cluster().prepareGetRepositories().get();237        assertThat(repositoriesResponse.repositories().size(), equalTo(0));238    }239 240"2414,0,"    protected Blob getBlob(ResultSet resultSet, int columnIndex, Metadata m) throws SQLException {242        byte[] bytes = resultSet.getBytes(columnIndex);243        if (!resultSet.wasNull()) {244            return new SerialBlob(bytes);245        }246        return null;247    }248"2495,0,"	private <T> T run(PrivilegedAction<T> action) {250		return System.getSecurityManager() != null ? AccessController.doPrivileged( action ) : action.run();251	}252"2536,0,"    protected boolean statusDropsConnection(int status) {254        return status == 400 /* SC_BAD_REQUEST */ ||255               status == 408 /* SC_REQUEST_TIMEOUT */ ||256               status == 411 /* SC_LENGTH_REQUIRED */ ||257               status == 413 /* SC_REQUEST_ENTITY_TOO_LARGE */ ||258               status == 414 /* SC_REQUEST_URI_TOO_LARGE */ ||259               status == 500 /* SC_INTERNAL_SERVER_ERROR */ ||260               status == 503 /* SC_SERVICE_UNAVAILABLE */ ||261               status == 501 /* SC_NOT_IMPLEMENTED */;262    }263 264"2657,0,"    private ControllerInfo getControllerInfo(Annotations annotation, String s) {266        String[] data = s.split("":"");267        if (data.length != 3) {268            print(""Wrong format of the controller %s, should be in the format <protocol>:<ip>:<port>"", s);269            return null;270        }271        String type = data[0];272        IpAddress ip = IpAddress.valueOf(data[1]);273        int port = Integer.parseInt(data[2]);274        if (annotation != null) {275            return new ControllerInfo(ip, port, type, annotation);276        }277        return new ControllerInfo(ip, port, type);278    }279"2808,0,"    public Authentication authenticate(Authentication authentication) throws AuthenticationException {281        Assert.isInstanceOf(UsernamePasswordAuthenticationToken.class, authentication,282            messages.getMessage(""LdapAuthenticationProvider.onlySupports"",283                ""Only UsernamePasswordAuthenticationToken is supported""));284 285        final UsernamePasswordAuthenticationToken userToken = (UsernamePasswordAuthenticationToken)authentication;286 287        String username = userToken.getName();288        String password = (String) authentication.getCredentials();289 290        if (logger.isDebugEnabled()) {291            logger.debug(""Processing authentication request for user: "" + username);292        }293 294        if (!StringUtils.hasLength(username)) {295            throw new BadCredentialsException(messages.getMessage(""LdapAuthenticationProvider.emptyUsername"",296                    ""Empty Username""));297        }298 299        if (!StringUtils.hasLength(password)) {300            throw new BadCredentialsException(messages.getMessage(""AbstractLdapAuthenticationProvider.emptyPassword"",301                    ""Empty Password""));302        }303 304        Assert.notNull(password, ""Null password was supplied in authentication token"");305 306        DirContextOperations userData = doAuthentication(userToken);307 308        UserDetails user = userDetailsContextMapper.mapUserFromContext(userData, authentication.getName(),309                    loadUserAuthorities(userData, authentication.getName(), (String)authentication.getCredentials()));310 311        return createSuccessfulAuthentication(userToken, user);312    }313 314"3159,0,"		protected IgnoreCsrfProtectionRegistry chainRequestMatchers(316				List<RequestMatcher> requestMatchers) {317			CsrfConfigurer.this.ignoredCsrfProtectionMatchers.addAll(requestMatchers);318			return this;319		}320	}321}"32210,0,"  private String[] getParts(String encodedJWT) {323    String[] parts = encodedJWT.split(""\\."");324    // Secured JWT XXXXX.YYYYY.ZZZZZ, Unsecured JWT XXXXX.YYYYY.325    if (parts.length == 3 || (parts.length == 2 && encodedJWT.endsWith("".""))) {326      return parts;327    }328 329    throw new InvalidJWTException(""The encoded JWT is not properly formatted. Expected a three part dot separated string."");330  }331"33211,0,"    public String getAlgorithm() {333 334        return (this.algorithm);335 336    }337 338 339    /**340     * Set the message digest algorithm for this Manager.341     *342     * @param algorithm The new message digest algorithm343     */344"34512,0,"	public ChannelRequestMatcherRegistry getRegistry() {346		return REGISTRY;347	}348 349	@Override350"35113,0,"    public String getDefaultWebXml() {352        if( defaultWebXml == null ) {353            defaultWebXml=Constants.DefaultWebXml;354        }355 356        return (this.defaultWebXml);357 358    }359 360 361    /**362     * Set the location of the default deployment descriptor363     *364     * @param path Absolute/relative path to the default web.xml365     */366"36714,0,"  public Collection<ResourcePermission> getRequiredPermissions(String regionName) {368    return Collections.singletonList(ResourcePermissions.DATA_MANAGE);369  }370 371"37215,0,"    private void enableAllocation(String index) {373        client().admin().indices().prepareUpdateSettings(index).setSettings(ImmutableSettings.builder().put(374                ""index.routing.allocation.enable"", ""all""375        )).get();376    }377"37816,0,"        public void parse(InputStream stream, ContentHandler ignore,379                Metadata metadata, ParseContext context) throws IOException,380                SAXException, TikaException {381            //Test to see if we should avoid parsing382            if (parserState.recursiveParserWrapperHandler.hasHitMaximumEmbeddedResources()) {383                return;384            }385            // Work out what this thing is386            String objectName = getResourceName(metadata, parserState);387            String objectLocation = this.location + objectName;388      389            metadata.add(AbstractRecursiveParserWrapperHandler.EMBEDDED_RESOURCE_PATH, objectLocation);390 391 392            //get a fresh handler393            ContentHandler localHandler = parserState.recursiveParserWrapperHandler.getNewContentHandler();394            parserState.recursiveParserWrapperHandler.startEmbeddedDocument(localHandler, metadata);395 396            Parser preContextParser = context.get(Parser.class);397            context.set(Parser.class, new EmbeddedParserDecorator(getWrappedParser(), objectLocation, parserState));398            long started = System.currentTimeMillis();399            try {400                super.parse(stream, localHandler, metadata, context);401            } catch (SAXException e) {402                boolean wlr = isWriteLimitReached(e);403                if (wlr == true) {404                    metadata.add(WRITE_LIMIT_REACHED, ""true"");405                } else {406                    if (catchEmbeddedExceptions) {407                        ParserUtils.recordParserFailure(this, e, metadata);408                    } else {409                        throw e;410                    }411                }412            } catch(CorruptedFileException e) {413                throw e;414            } catch (TikaException e) {415                if (catchEmbeddedExceptions) {416                    ParserUtils.recordParserFailure(this, e, metadata);417                } else {418                    throw e;419                }420            } finally {421                context.set(Parser.class, preContextParser);422                long elapsedMillis = System.currentTimeMillis() - started;423                metadata.set(RecursiveParserWrapperHandler.PARSE_TIME_MILLIS, Long.toString(elapsedMillis));424                parserState.recursiveParserWrapperHandler.endEmbeddedDocument(localHandler, metadata);425            }426        }427    }428 429    /**430     * This tracks the state of the parse of a single document.431     * In future versions, this will allow the RecursiveParserWrapper to be thread safe.432     */433    private class ParserState {434        private int unknownCount = 0;435        private final AbstractRecursiveParserWrapperHandler recursiveParserWrapperHandler;436        private ParserState(AbstractRecursiveParserWrapperHandler handler) {437            this.recursiveParserWrapperHandler = handler;438        }439 440 441    }442}443"44417,0,"  public static void beforeTests() throws Exception {445    initCore(""solrconfig.xml"",""schema.xml"");446    handler = new UpdateRequestHandler();447  }448 449  @Test450"45118,0,"    public void setUp() throws Exception {452        interceptor = new I18nInterceptor();453        interceptor.init();454        params = new HashMap<String, Object>();455        session = new HashMap();456 457        Map<String, Object> ctx = new HashMap<String, Object>();458        ctx.put(ActionContext.PARAMETERS, params);459        ctx.put(ActionContext.SESSION, session);460        ac = new ActionContext(ctx);461 462        Action action = new Action() {463            public String execute() throws Exception {464                return SUCCESS;465            }466        };467        mai = new MockActionInvocation();468        ((MockActionInvocation) mai).setAction(action);469        ((MockActionInvocation) mai).setInvocationContext(ac);470    }471 472    @After473"47419,0,"    private MockHttpServletRequestBuilder createChangePasswordRequest(ScimUser user, String code, boolean useCSRF, String password, String passwordConfirmation) throws Exception {475        MockHttpServletRequestBuilder post = post(""/reset_password.do"");476        if (useCSRF) {477            post.with(csrf());478        }479        post.param(""code"", code)480            .param(""email"", user.getPrimaryEmail())481            .param(""password"", password)482            .param(""password_confirmation"", passwordConfirmation);483        return post;484    }485"48620,0,"    protected Log getLog() {487        return log;488    }489 490    // ----------------------------------------------------------- Constructors491 492 493"49421,0,"    public int getCount() {495        return iCount;496    }497 498"49922,0,"	public BeanDefinitionHolder decorate(Node node, BeanDefinitionHolder holder,500			ParserContext parserContext) {501		BeanDefinition filterChainProxy = holder.getBeanDefinition();502 503		ManagedList<BeanMetadataElement> securityFilterChains = new ManagedList<BeanMetadataElement>();504		Element elt = (Element) node;505 506		MatcherType matcherType = MatcherType.fromElement(elt);507 508		List<Element> filterChainElts = DomUtils.getChildElementsByTagName(elt,509				Elements.FILTER_CHAIN);510 511		for (Element chain : filterChainElts) {512			String path = chain513					.getAttribute(HttpSecurityBeanDefinitionParser.ATT_PATH_PATTERN);514			String filters = chain515					.getAttribute(HttpSecurityBeanDefinitionParser.ATT_FILTERS);516 517			if (!StringUtils.hasText(path)) {518				parserContext.getReaderContext().error(519						""The attribute '""520								+ HttpSecurityBeanDefinitionParser.ATT_PATH_PATTERN521								+ ""' must not be empty"", elt);522			}523 524			if (!StringUtils.hasText(filters)) {525				parserContext.getReaderContext().error(526						""The attribute '"" + HttpSecurityBeanDefinitionParser.ATT_FILTERS527								+ ""'must not be empty"", elt);528			}529 530			BeanDefinition matcher = matcherType.createMatcher(parserContext, path, null);531 532			if (filters.equals(HttpSecurityBeanDefinitionParser.OPT_FILTERS_NONE)) {533				securityFilterChains.add(createSecurityFilterChain(matcher,534						new ManagedList(0)));535			}536			else {537				String[] filterBeanNames = StringUtils538						.tokenizeToStringArray(filters, "","");539				ManagedList filterChain = new ManagedList(filterBeanNames.length);540 541				for (String name : filterBeanNames) {542					filterChain.add(new RuntimeBeanReference(name));543				}544 545				securityFilterChains.add(createSecurityFilterChain(matcher, filterChain));546			}547		}548 549		filterChainProxy.getConstructorArgumentValues().addGenericArgumentValue(550				securityFilterChains);551 552		return holder;553	}554 555"55623,0,"  public XObject execute(XPathContext xctxt) throws javax.xml.transform.TransformerException557  {558 559    String fullName = m_arg0.execute(xctxt).str();560    int indexOfNSSep = fullName.indexOf(':');561    String result = null;562    String propName = """";563 564    // List of properties where the name of the565    // property argument is to be looked for.566    Properties xsltInfo = new Properties();567 568    loadPropertyFile(XSLT_PROPERTIES, xsltInfo);569 570    if (indexOfNSSep > 0)571    {572      String prefix = (indexOfNSSep >= 0)573                      ? fullName.substring(0, indexOfNSSep) : """";574      String namespace;575 576      namespace = xctxt.getNamespaceContext().getNamespaceForPrefix(prefix);577      propName = (indexOfNSSep < 0)578                 ? fullName : fullName.substring(indexOfNSSep + 1);579 580      if (namespace.startsWith(""http://www.w3.org/XSL/Transform"")581              || namespace.equals(""http://www.w3.org/1999/XSL/Transform""))582      {583        result = xsltInfo.getProperty(propName);584 585        if (null == result)586        {587          warn(xctxt, XPATHErrorResources.WG_PROPERTY_NOT_SUPPORTED,588               new Object[]{ fullName });  //""XSL Property not supported: ""+fullName);589 590          return XString.EMPTYSTRING;591        }592      }593      else594      {595        warn(xctxt, XPATHErrorResources.WG_DONT_DO_ANYTHING_WITH_NS,596             new Object[]{ namespace,597                           fullName });  //""Don't currently do anything with namespace ""+namespace+"" in property: ""+fullName);598 599        try600        {601            //if secure procession is enabled only handle required properties do not not map any valid system property602            if(!xctxt.isSecureProcessing())603            {604                result = System.getProperty(fullName);605            }606            else607            {608                warn(xctxt, XPATHErrorResources.WG_SECURITY_EXCEPTION,609                        new Object[]{ fullName });  //""SecurityException when trying to access XSL system property: ""+fullName);610                result = xsltInfo.getProperty(propName);611            }612            if (null == result)613            {614                return XString.EMPTYSTRING;615            }616        }617        catch (SecurityException se)618        {619          warn(xctxt, XPATHErrorResources.WG_SECURITY_EXCEPTION,620               new Object[]{ fullName });  //""SecurityException when trying to access XSL system property: ""+fullName);621 622          return XString.EMPTYSTRING;623        }624      }625    }626    else627    {628      try629      {630          //if secure procession is enabled only handle required properties do not not map any valid system property631          if(!xctxt.isSecureProcessing())632          {633              result = System.getProperty(fullName);634          }635          else636          {637              warn(xctxt, XPATHErrorResources.WG_SECURITY_EXCEPTION,638                      new Object[]{ fullName });  //""SecurityException when trying to access XSL system property: ""+fullName);639              result = xsltInfo.getProperty(propName);640          }641          if (null == result)642          {643              return XString.EMPTYSTRING;644          }645      }646      catch (SecurityException se)647      {648        warn(xctxt, XPATHErrorResources.WG_SECURITY_EXCEPTION,649             new Object[]{ fullName });  //""SecurityException when trying to access XSL system property: ""+fullName);650 651        return XString.EMPTYSTRING;652      }653    }654 655    if (propName.equals(""version"") && result.length() > 0)656    {657      try658      {659        // Needs to return the version number of the spec we conform to.660        return new XString(""1.0"");661      }662      catch (Exception ex)663      {664        return new XString(result);665      }666    }667    else668      return new XString(result);669  }670 671  /**672   * Retrieve a propery bundle from a specified file673   * 674   * @param file The string name of the property file.  The name 675   * should already be fully qualified as path/filename676   * @param target The target property bag the file will be placed into.677   */678"67924,0,"	public boolean equals(Object obj) {680		if ( this == obj ) {681			return true;682		}683		if ( !super.equals( obj ) ) {684			return false;685		}686		if ( getClass() != obj.getClass() ) {687			return false;688		}689		ConstrainedExecutable other = (ConstrainedExecutable) obj;690		if ( executable == null ) {691			if ( other.executable != null ) {692				return false;693			}694		}695		else if ( !executable.equals( other.executable ) ) {696			return false;697		}698		return true;699	}700"70125,0,"    public static HierarchicalConfiguration loadXml(InputStream xmlStream) {702        try {703            XMLConfiguration cfg = new XMLConfiguration();704            DocumentBuilderFactory dbfactory = DocumentBuilderFactory.newInstance();705            //Disabling DTDs in order to avoid XXE xml-based attacks.706            disableFeature(dbfactory, DISALLOW_DTD_FEATURE);707            disableFeature(dbfactory, DISALLOW_EXTERNAL_DTD);708            dbfactory.setXIncludeAware(false);709            dbfactory.setExpandEntityReferences(false);710            cfg.setDocumentBuilder(dbfactory.newDocumentBuilder());711            cfg.load(xmlStream);712            return cfg;713        } catch (ConfigurationException | ParserConfigurationException e) {714            throw new IllegalArgumentException(""Cannot load xml from Stream"", e);715        }716    }717 718"71926,0,"        void noteBytesRead(int pBytes) {720            /* Indicates, that the given number of bytes have been read from721             * the input stream.722             */723            bytesRead += pBytes;724            notifyListener();725        }726 727        /**728         * Called to indicate, that a new file item has been detected.729         */730"73127,0,"    private static DocumentBuilder getBuilder() throws ParserConfigurationException {732        ClassLoader loader = Thread.currentThread().getContextClassLoader();733        if (loader == null) {734            loader = DOMUtils.class.getClassLoader();735        }736        if (loader == null) {737            DocumentBuilderFactory dbf = createDocumentBuilderFactory();738            return dbf.newDocumentBuilder();739        }740        DocumentBuilder builder = DOCUMENT_BUILDERS.get(loader);741        if (builder == null) {742            DocumentBuilderFactory dbf = createDocumentBuilderFactory();743            builder = dbf.newDocumentBuilder();744            DOCUMENT_BUILDERS.put(loader, builder);745        }746        return builder;747    }748 749    /**750     * This function is much like getAttribute, but returns null, not """", for a nonexistent attribute.751     * 752     * @param e753     * @param attributeName754     */755"75628,0,"	public StandardInterceptUrlRegistry getRegistry() {757		return REGISTRY;758	}759 760	/**761	 * Adds an {@link ObjectPostProcessor} for this class.762	 *763	 * @param objectPostProcessor764	 * @return the {@link UrlAuthorizationConfigurer} for further customizations765	 */766"76729,0,"  public synchronized XPathRecordReader addField(String name, String xpath, boolean multiValued, int flags) {768    addField0(xpath, name, multiValued, false, flags);769    return this;770  }771 772  /**773   * Splits the XPATH into a List of xpath segments and calls build() to774   * construct a tree of Nodes representing xpath segments. The resulting775   * tree structure ends up describing all the Xpaths we are interested in.776   *777   * @param xpath The xpath expression for this field778   * @param name The name for this field in the emitted record779   * @param multiValued If 'true' then the emitted record will have values in 780   *                    a List&lt;String&gt;781   * @param isRecord Flags that this XPATH is from a forEach statement782   * @param flags The only supported flag is 'FLATTEN'783   */784"78530,0,"        public void setConstants(ContainerBuilder builder) {786            for (Object keyobj : keySet()) {787                String key = (String)keyobj;788                builder.factory(String.class, key,789                        new LocatableConstantFactory<String>(getProperty(key), getPropertyLocation(key)));790            }791        }792    }793}794"79531,0,"    public CommandLauncher launch(String host, TaskListener listener) throws IOException, InterruptedException {796        return new CommandLauncher(command,new EnvVars(""SLAVE"",host));797    }798 799    @Extension @Symbol(""command"")800"80132,0,"   private void  parseCSSStyleSheet(String sheet) throws SVGParseException802   {803      CSSParser  cssp = new CSSParser(MediaType.screen);804      svgDocument.addCSSRules(cssp.parse(sheet));805   }806 807"80833,0,"  public void test_unsecuredJWT_validation() throws Exception {809    JWT jwt = new JWT().setSubject(""123456789"");810    Signer signer = new UnsecuredSigner();811    Verifier hmacVerifier = HMACVerifier.newVerifier(""too many secrets"");812 813    String encodedUnsecuredJWT = JWTEncoder.getInstance().encode(jwt, signer);814 815    // Ensure that attempting to decode an un-secured JWT fails when we provide a verifier816    expectException(MissingVerifierException.class, () -> JWT.getDecoder().decode(encodedUnsecuredJWT, hmacVerifier));817 818    String encodedUnsecuredJWT_withKid = JWTEncoder.getInstance().encode(jwt, signer, (header) -> header.set(""kid"", ""abc""));819    String encodedUnsecuredJWT_withoutKid = JWTEncoder.getInstance().encode(jwt, signer);820 821    Map<String, Verifier> verifierMap = new HashMap<>();822    verifierMap.put(null, hmacVerifier);823    verifierMap.put(""abc"", hmacVerifier);824 825    // Ensure that attempting to decode an un-secured JWT fails when we provide a verifier with or without using a kid826    expectException(MissingVerifierException.class, () -> JWT.getDecoder().decode(encodedUnsecuredJWT_withKid, verifierMap));827    expectException(MissingVerifierException.class, () -> JWT.getDecoder().decode(encodedUnsecuredJWT_withoutKid, verifierMap));828  }829 830  @Test831"83234,0,"    public String getConnectionName() {833        return connectionName;834    }835 836    /**837     * Set the username to use to connect to the database.838     *839     * @param connectionName Username840     */841"84235,0,"        protected Log getLog() {843            return log;844        }845 846        @Override847"84836,0,"        public BigInteger[] decode(849            byte[] encoding)850            throws IOException851        {852            BigInteger[] sig = new BigInteger[2];853 854            byte[] first = new byte[encoding.length / 2];855            byte[] second = new byte[encoding.length / 2];856 857            System.arraycopy(encoding, 0, first, 0, first.length);858            System.arraycopy(encoding, first.length, second, 0, second.length);859 860            sig[0] = new BigInteger(1, first);861            sig[1] = new BigInteger(1, second);862 863            return sig;864        }865    }866}"86737,0,"        public ScimGroup mapRow(ResultSet rs, int rowNum) throws SQLException {868            int pos = 1;869            String id = rs.getString(pos++);870            String name = rs.getString(pos++);871            String description = rs.getString(pos++);872            Date created = rs.getTimestamp(pos++);873            Date modified = rs.getTimestamp(pos++);874            int version = rs.getInt(pos++);875            String zoneId = rs.getString(pos++);876            ScimGroup group = new ScimGroup(id, name, zoneId);877            group.setDescription(description);878            ScimMeta meta = new ScimMeta(created, modified, version);879            group.setMeta(meta);880            return group;881        }882    }883}884"88538,0,"    public void testSendStringMessage() throws Exception {886        sendMessageAndHaveItTransformed(""<mail><subject>Hey</subject><body>Hello world!</body></mail>"");887    }888    889"89039,0,"    public void testSingletonPatternInSerialization() {891        final Object[] singletones = new Object[] {892                ExceptionFactory.INSTANCE,893        };894 895        for (final Object original : singletones) {896            TestUtils.assertSameAfterSerialization(897                    ""Singletone patern broken for "" + original.getClass(),898                    original899            );900        }901    }902 903"90440,0,"	private void doTestParameterNameLengthRestriction( ParametersInterceptor parametersInterceptor,905													   int paramNameMaxLength ) {906		StringBuilder sb = new StringBuilder();907		for (int i = 0; i < paramNameMaxLength + 1; i++) {908            sb.append(""x"");909        }910 911		Map<String, Object> actual = new LinkedHashMap<String, Object>();912		parametersInterceptor.setValueStackFactory(createValueStackFactory(actual));913		ValueStack stack = createStubValueStack(actual);914 915		Map<String, Object> parameters = new HashMap<String, Object>();916		parameters.put(sb.toString(), """");917		parameters.put(""huuhaa"", """");918 919		Action action = new SimpleAction();920		parametersInterceptor.setParameters(action, stack, parameters);921		assertEquals(1, actual.size());922	}923 924"92541,0,"        public boolean equals(Object obj) {926            if (obj instanceof CharEntry) {927                return value.equals(((CharEntry) obj).value);928            }929            return false;930        }931        932    }933 934 935}936"93742,0,"    protected boolean readMessage(AjpMessage message)938        throws IOException {939 940        byte[] buf = message.getBuffer();941        int headerLength = message.getHeaderLength();942 943        read(buf, 0, headerLength);944 945        int messageLength = message.processHeader(true);946        if (messageLength < 0) {947            // Invalid AJP header signature948            // TODO: Throw some exception and close the connection to frontend.949            return false;950        }951        else if (messageLength == 0) {952            // Zero length message.953            return true;954        }955        else {956            if (messageLength > buf.length) {957                // Message too long for the buffer958                // Need to trigger a 400 response959                throw new IllegalArgumentException(sm.getString(960                        ""ajpprocessor.header.tooLong"",961                        Integer.valueOf(messageLength),962                        Integer.valueOf(buf.length)));963            }964            read(buf, headerLength, messageLength);965            return true;966        }967    }968"96943,0,"    public boolean allPresentAndPositive() {970        return lockoutPeriodSeconds >= 0 && lockoutAfterFailures >= 0 && countFailuresWithin >= 0;971    }972"97344,0,"    public boolean event(org.apache.coyote.Request req, 974            org.apache.coyote.Response res, SocketStatus status) {975 976        Request request = (Request) req.getNote(ADAPTER_NOTES);977        Response response = (Response) res.getNote(ADAPTER_NOTES);978 979        if (request.getWrapper() != null) {980            981            boolean error = false;982            try {983                if (status == SocketStatus.OPEN) {984                    request.getEvent().setEventType(CometEvent.EventType.READ);985                    request.getEvent().setEventSubType(null);986                } else if (status == SocketStatus.DISCONNECT) {987                    request.getEvent().setEventType(CometEvent.EventType.ERROR);988                    request.getEvent().setEventSubType(CometEvent.EventSubType.CLIENT_DISCONNECT);989                    error = true;990                } else if (status == SocketStatus.ERROR) {991                    request.getEvent().setEventType(CometEvent.EventType.ERROR);992                    request.getEvent().setEventSubType(CometEvent.EventSubType.IOEXCEPTION);993                    error = true;994                } else if (status == SocketStatus.STOP) {995                    request.getEvent().setEventType(CometEvent.EventType.END);996                    request.getEvent().setEventSubType(CometEvent.EventSubType.SERVER_SHUTDOWN);997                } else if (status == SocketStatus.TIMEOUT) {998                    request.getEvent().setEventType(CometEvent.EventType.ERROR);999                    request.getEvent().setEventSubType(CometEvent.EventSubType.TIMEOUT);1000                }1001                1002                // Calling the container1003                connector.getContainer().getPipeline().getFirst().event(request, response, request.getEvent());1004 1005                if (response.isClosed() || !request.isComet()) {1006                    res.action(ActionCode.ACTION_COMET_END, null);1007                }1008                return (!error);1009            } catch (Throwable t) {1010                if (!(t instanceof IOException)) {1011                    log.error(sm.getString(""coyoteAdapter.service""), t);1012                }1013                error = true;1014                // FIXME: Since there's likely some structures kept in the servlet or elsewhere,1015                // a cleanup event of some sort could be needed ?1016                return false;1017            } finally {1018                // Recycle the wrapper request and response1019                if (error || response.isClosed() || !request.isComet()) {1020                    request.recycle();1021                    request.setFilterChain(null);1022                    response.recycle();1023                }1024            }1025            1026        } else {1027            return false;1028        }1029    }1030    1031 1032    /**1033     * Service method.1034     */1035"103645,0,"    public void testSnapshotAndRestore() throws ExecutionException, InterruptedException, IOException {1037        logger.info(""-->  creating repository"");1038        assertAcked(client().admin().cluster().preparePutRepository(""test-repo"")1039                .setType(""fs"").setSettings(ImmutableSettings.settingsBuilder()1040                        .put(""location"", randomRepoPath().getAbsolutePath())1041                        .put(""compress"", randomBoolean())1042                        .put(""chunk_size"", randomIntBetween(100, 1000))));1043        String[] indicesBefore = new String[randomIntBetween(2,5)];1044        String[] indicesAfter = new String[randomIntBetween(2,5)];1045        for (int i = 0; i < indicesBefore.length; i++) {1046            indicesBefore[i] = ""index_before_"" + i;1047            createIndex(indicesBefore[i]);1048        }1049        for (int i = 0; i < indicesAfter.length; i++) {1050            indicesAfter[i] = ""index_after_"" + i;1051            createIndex(indicesAfter[i]);1052        }1053        String[] indices = new String[indicesBefore.length + indicesAfter.length];1054        System.arraycopy(indicesBefore, 0, indices, 0, indicesBefore.length);1055        System.arraycopy(indicesAfter, 0, indices, indicesBefore.length, indicesAfter.length);1056        ensureYellow();1057        logger.info(""--> indexing some data"");1058        IndexRequestBuilder[] buildersBefore = new IndexRequestBuilder[randomIntBetween(10, 200)];1059        for (int i = 0; i < buildersBefore.length; i++) {1060            buildersBefore[i] = client().prepareIndex(RandomPicks.randomFrom(getRandom(), indicesBefore), ""foo"", Integer.toString(i)).setSource(""{ \""foo\"" : \""bar\"" } "");1061        }1062        IndexRequestBuilder[] buildersAfter = new IndexRequestBuilder[randomIntBetween(10, 200)];1063        for (int i = 0; i < buildersAfter.length; i++) {1064            buildersAfter[i] = client().prepareIndex(RandomPicks.randomFrom(getRandom(), indicesBefore), ""bar"", Integer.toString(i)).setSource(""{ \""foo\"" : \""bar\"" } "");1065        }1066        indexRandom(true, buildersBefore);1067        indexRandom(true, buildersAfter);1068        assertThat(client().prepareCount(indices).get().getCount(), equalTo((long) (buildersBefore.length + buildersAfter.length)));1069        long[] counts = new long[indices.length];1070        for (int i = 0; i < indices.length; i++) {1071            counts[i] = client().prepareCount(indices[i]).get().getCount();1072        }1073 1074        logger.info(""--> snapshot subset of indices before upgrage"");1075        CreateSnapshotResponse createSnapshotResponse = client().admin().cluster().prepareCreateSnapshot(""test-repo"", ""test-snap-1"").setWaitForCompletion(true).setIndices(""index_before_*"").get();1076        assertThat(createSnapshotResponse.getSnapshotInfo().successfulShards(), greaterThan(0));1077        assertThat(createSnapshotResponse.getSnapshotInfo().successfulShards(), equalTo(createSnapshotResponse.getSnapshotInfo().totalShards()));1078 1079        assertThat(client().admin().cluster().prepareGetSnapshots(""test-repo"").setSnapshots(""test-snap-1"").get().getSnapshots().get(0).state(), equalTo(SnapshotState.SUCCESS));1080 1081        logger.info(""--> delete some data from indices that were already snapshotted"");1082        int howMany = randomIntBetween(1, buildersBefore.length);1083 1084        for (int i = 0; i < howMany; i++) {1085            IndexRequestBuilder indexRequestBuilder = RandomPicks.randomFrom(getRandom(), buildersBefore);1086            IndexRequest request = indexRequestBuilder.request();1087            client().prepareDelete(request.index(), request.type(), request.id()).get();1088        }1089        refresh();1090        final long numDocs = client().prepareCount(indices).get().getCount();1091        assertThat(client().prepareCount(indices).get().getCount(), lessThan((long) (buildersBefore.length + buildersAfter.length)));1092 1093 1094        client().admin().indices().prepareUpdateSettings(indices).setSettings(ImmutableSettings.builder().put(EnableAllocationDecider.INDEX_ROUTING_ALLOCATION_ENABLE, ""none"")).get();1095        backwardsCluster().allowOnAllNodes(indices);1096        logClusterState();1097        boolean upgraded;1098        do {1099            logClusterState();1100            CountResponse countResponse = client().prepareCount().get();1101            assertHitCount(countResponse, numDocs);1102            upgraded = backwardsCluster().upgradeOneNode();1103            ensureYellow();1104            countResponse = client().prepareCount().get();1105            assertHitCount(countResponse, numDocs);1106        } while (upgraded);1107        client().admin().indices().prepareUpdateSettings(indices).setSettings(ImmutableSettings.builder().put(EnableAllocationDecider.INDEX_ROUTING_ALLOCATION_ENABLE, ""all"")).get();1108 1109        logger.info(""--> close indices"");1110        client().admin().indices().prepareClose(""index_before_*"").get();1111 1112        logger.info(""--> verify repository"");1113        client().admin().cluster().prepareVerifyRepository(""test-repo"").get();1114 1115        logger.info(""--> restore all indices from the snapshot"");1116        RestoreSnapshotResponse restoreSnapshotResponse = client().admin().cluster().prepareRestoreSnapshot(""test-repo"", ""test-snap-1"").setWaitForCompletion(true).execute().actionGet();1117        assertThat(restoreSnapshotResponse.getRestoreInfo().totalShards(), greaterThan(0));1118 1119        ensureYellow();1120        assertThat(client().prepareCount(indices).get().getCount(), equalTo((long) (buildersBefore.length + buildersAfter.length)));1121        for (int i = 0; i < indices.length; i++) {1122            assertThat(counts[i], equalTo(client().prepareCount(indices[i]).get().getCount()));1123        }1124 1125        logger.info(""--> snapshot subset of indices after upgrade"");1126        createSnapshotResponse = client().admin().cluster().prepareCreateSnapshot(""test-repo"", ""test-snap-2"").setWaitForCompletion(true).setIndices(""index_*"").get();1127        assertThat(createSnapshotResponse.getSnapshotInfo().successfulShards(), greaterThan(0));1128        assertThat(createSnapshotResponse.getSnapshotInfo().successfulShards(), equalTo(createSnapshotResponse.getSnapshotInfo().totalShards()));1129 1130        // Test restore after index deletion1131        logger.info(""--> delete indices"");1132        String index = RandomPicks.randomFrom(getRandom(), indices);1133        cluster().wipeIndices(index);1134        logger.info(""--> restore one index after deletion"");1135        restoreSnapshotResponse = client().admin().cluster().prepareRestoreSnapshot(""test-repo"", ""test-snap-2"").setWaitForCompletion(true).setIndices(index).execute().actionGet();1136        assertThat(restoreSnapshotResponse.getRestoreInfo().totalShards(), greaterThan(0));1137        ensureYellow();1138        assertThat(client().prepareCount(indices).get().getCount(), equalTo((long) (buildersBefore.length + buildersAfter.length)));1139        for (int i = 0; i < indices.length; i++) {1140            assertThat(counts[i], equalTo(client().prepareCount(indices[i]).get().getCount()));1141        }1142    }1143 1144"114546,0,"    public XMSSPrivateKeyParameters getNextKey()1146    {1147        /* prepare authentication path for next leaf */1148        int treeHeight = this.params.getHeight();1149        if (this.getIndex() < ((1 << treeHeight) - 1))1150        {1151            return new XMSSPrivateKeyParameters.Builder(params)1152                .withSecretKeySeed(secretKeySeed).withSecretKeyPRF(secretKeyPRF)1153                .withPublicSeed(publicSeed).withRoot(root)1154                .withBDSState(bdsState.getNextState(publicSeed, secretKeySeed, (OTSHashAddress)new OTSHashAddress.Builder().build())).build();1155        }1156        else1157        {1158            return new XMSSPrivateKeyParameters.Builder(params)1159                .withSecretKeySeed(secretKeySeed).withSecretKeyPRF(secretKeyPRF)1160                .withPublicSeed(publicSeed).withRoot(root)1161                .withBDSState(new BDS(params, getIndex() + 1)).build();  // no more nodes left.1162        }1163    }1164 1165"116647,0,"    public void addRecipients(final ExtendedEmailPublisherContext context, EnvVars env, Set<InternetAddress> to, Set<InternetAddress> cc, Set<InternetAddress> bcc) {1167        final class Debug implements RecipientProviderUtilities.IDebug {1168            private final ExtendedEmailPublisherDescriptor descriptor1169                    = Jenkins.getActiveInstance().getDescriptorByType(ExtendedEmailPublisherDescriptor.class);1170 1171            private final PrintStream logger = context.getListener().getLogger();1172 1173            public void send(final String format, final Object... args) {1174                descriptor.debug(logger, format, args);1175            }1176        }1177        final Debug debug = new Debug();1178        // looking for Upstream build.1179        Run<?, ?> cur = context.getRun();1180        Cause.UpstreamCause upc = cur.getCause(Cause.UpstreamCause.class);1181        while (upc != null) {1182            // UpstreamCause.getUpStreamProject() returns the full name, so use getItemByFullName1183            Job<?, ?> p = (Job<?, ?>) Jenkins.getActiveInstance().getItemByFullName(upc.getUpstreamProject());1184            if (p == null) {1185                context.getListener().getLogger().print(""There is a break in the project linkage, could not retrieve upstream project information"");1186                break;1187            }1188            cur = p.getBuildByNumber(upc.getUpstreamBuild());1189            upc = cur.getCause(Cause.UpstreamCause.class);1190        }1191        addUserTriggeringTheBuild(cur, to, cc, bcc, env, context, debug);1192    }1193 1194"119548,0,"    public void setSslSupport(SSLSupport sslSupport) {1196        this.sslSupport = sslSupport;1197    }1198"119949,0,"  public void loadPropertyFile(String file, Properties target)1200  {

Showing the first 1,200 of 11456 lines. Download the file for the rest.