diff --git a/.gitattributes b/.gitattributes deleted file mode 100644 index a770de78287b5353fb380cf8774b1e6caf2881d9..0000000000000000000000000000000000000000 --- a/.gitattributes +++ /dev/null @@ -1,37 +0,0 @@ -*.7z filter=lfs diff=lfs merge=lfs -text -*.arrow filter=lfs diff=lfs merge=lfs -text -*.bin filter=lfs diff=lfs merge=lfs -text -*.bz2 filter=lfs diff=lfs merge=lfs -text -*.ftz filter=lfs diff=lfs merge=lfs -text -*.gz filter=lfs diff=lfs merge=lfs -text -*.h5 filter=lfs diff=lfs merge=lfs -text -*.joblib filter=lfs diff=lfs merge=lfs -text -*.lfs.* filter=lfs diff=lfs merge=lfs -text -*.model filter=lfs diff=lfs merge=lfs -text -*.msgpack filter=lfs diff=lfs merge=lfs -text -*.onnx filter=lfs diff=lfs merge=lfs -text -*.ot filter=lfs diff=lfs merge=lfs -text -*.parquet filter=lfs diff=lfs merge=lfs -text -*.pb filter=lfs diff=lfs merge=lfs -text -*.pt filter=lfs diff=lfs merge=lfs -text -*.pth filter=lfs diff=lfs merge=lfs -text -*.rar filter=lfs diff=lfs merge=lfs -text -saved_model/**/* filter=lfs diff=lfs merge=lfs -text -*.tar.* filter=lfs diff=lfs merge=lfs -text -*.tflite filter=lfs diff=lfs merge=lfs -text -*.tgz filter=lfs diff=lfs merge=lfs -text -*.wasm filter=lfs diff=lfs merge=lfs -text -*.xz filter=lfs diff=lfs merge=lfs -text -*.zip filter=lfs diff=lfs merge=lfs -text -*.zstandard filter=lfs diff=lfs merge=lfs -text -*tfevents* filter=lfs diff=lfs merge=lfs -text -# Audio files - uncompressed -*.pcm filter=lfs diff=lfs merge=lfs -text -*.sam filter=lfs diff=lfs merge=lfs -text -*.raw filter=lfs diff=lfs merge=lfs -text -# Audio files - compressed -*.aac filter=lfs diff=lfs merge=lfs -text -*.flac filter=lfs diff=lfs merge=lfs -text -*.mp3 filter=lfs diff=lfs merge=lfs -text -*.ogg filter=lfs diff=lfs merge=lfs -text -*.wav filter=lfs diff=lfs merge=lfs -text diff --git a/README.md b/README.md deleted file mode 100644 index 412db81741a560726ed2aab3f8b92bc62f73440e..0000000000000000000000000000000000000000 --- a/README.md +++ /dev/null @@ -1,3 +0,0 @@ ---- -license: afl-3.0 ---- diff --git a/Zaib--java-vulnerability/csv-test.parquet b/Zaib--java-vulnerability/csv-test.parquet new file mode 100644 index 0000000000000000000000000000000000000000..6e33bddaf4f47a0b28ea64736b5985d91f8fc6b9 --- /dev/null +++ b/Zaib--java-vulnerability/csv-test.parquet @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0c7da03a4c906ab7d4b8d08df6392603dadc17a7176a2c3a4ebfe74407036a30 +size 179089 diff --git a/Zaib--java-vulnerability/csv-train.parquet b/Zaib--java-vulnerability/csv-train.parquet new file mode 100644 index 0000000000000000000000000000000000000000..33c98468b256f7bb8bdcbf76578bc42cd2a62a9a --- /dev/null +++ b/Zaib--java-vulnerability/csv-train.parquet @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:467171586b3c0d5f8ab638ae2bb88ed65955396d5c51f12f934c395d7aeb0ac2 +size 249051 diff --git a/Zaib--java-vulnerability/csv-validation.parquet b/Zaib--java-vulnerability/csv-validation.parquet new file mode 100644 index 0000000000000000000000000000000000000000..6e33bddaf4f47a0b28ea64736b5985d91f8fc6b9 --- /dev/null +++ b/Zaib--java-vulnerability/csv-validation.parquet @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0c7da03a4c906ab7d4b8d08df6392603dadc17a7176a2c3a4ebfe74407036a30 +size 179089 diff --git a/test.csv b/test.csv deleted file mode 100644 index 99c2c2d13c7b4b9b4d17db3bfb69586a73aa417e..0000000000000000000000000000000000000000 --- a/test.csv +++ /dev/null @@ -1,11455 +0,0 @@ -,label,code -0,0," private static void initKeyPair(SecureRandom prng) throws NoSuchAlgorithmException { - String sigAlg = signatureAlgorithm.toLowerCase(); - if ( sigAlg.endsWith(""withdsa"") ) { - // - // Admittedly, this is a kludge. However for Sun JCE, even though - // ""SHA1withDSA"" is a valid signature algorithm name, if one calls - // KeyPairGenerator kpg = KeyPairGenerator.getInstance(""SHA1withDSA""); - // that will throw a NoSuchAlgorithmException with an exception - // message of ""SHA1withDSA KeyPairGenerator not available"". Since - // SHA1withDSA and DSA keys should be identical, we use ""DSA"" - // in the case that SHA1withDSA or SHAwithDSA was specified. This is - // all just to make these 2 work as expected. Sigh. (Note: - // this was tested with JDK 1.6.0_21, but likely fails with earlier - // versions of the JDK as well.) - // - sigAlg = ""DSA""; - } else if ( sigAlg.endsWith(""withrsa"") ) { - // Ditto for RSA. - sigAlg = ""RSA""; - } - KeyPairGenerator keyGen = KeyPairGenerator.getInstance(sigAlg); - keyGen.initialize(signatureKeyLength, prng); - KeyPair pair = keyGen.generateKeyPair(); - privateKey = pair.getPrivate(); - publicKey = pair.getPublic(); - } -" -1,0," public ZipArchiveEntry getNextZipEntry() throws IOException { - uncompressedCount = 0; - - boolean firstEntry = true; - if (closed || hitCentralDirectory) { - return null; - } - if (current != null) { - closeEntry(); - firstEntry = false; - } - - long currentHeaderOffset = getBytesRead(); - try { - if (firstEntry) { - // split archives have a special signature before the - // first local file header - look for it and fail with - // the appropriate error message if this is a split - // archive. - readFirstLocalFileHeader(lfhBuf); - } else { - readFully(lfhBuf); - } - } catch (final EOFException e) { - return null; - } - - final ZipLong sig = new ZipLong(lfhBuf); - if (!sig.equals(ZipLong.LFH_SIG)) { - if (sig.equals(ZipLong.CFH_SIG) || sig.equals(ZipLong.AED_SIG) || isApkSigningBlock(lfhBuf)) { - hitCentralDirectory = true; - skipRemainderOfArchive(); - return null; - } - throw new ZipException(String.format(""Unexpected record signature: 0X%X"", sig.getValue())); - } - - int off = WORD; - current = new CurrentEntry(); - - final int versionMadeBy = ZipShort.getValue(lfhBuf, off); - off += SHORT; - current.entry.setPlatform((versionMadeBy >> ZipFile.BYTE_SHIFT) & ZipFile.NIBLET_MASK); - - final GeneralPurposeBit gpFlag = GeneralPurposeBit.parse(lfhBuf, off); - final boolean hasUTF8Flag = gpFlag.usesUTF8ForNames(); - final ZipEncoding entryEncoding = hasUTF8Flag ? ZipEncodingHelper.UTF8_ZIP_ENCODING : zipEncoding; - current.hasDataDescriptor = gpFlag.usesDataDescriptor(); - current.entry.setGeneralPurposeBit(gpFlag); - - off += SHORT; - - current.entry.setMethod(ZipShort.getValue(lfhBuf, off)); - off += SHORT; - - final long time = ZipUtil.dosToJavaTime(ZipLong.getValue(lfhBuf, off)); - current.entry.setTime(time); - off += WORD; - - ZipLong size = null, cSize = null; - if (!current.hasDataDescriptor) { - current.entry.setCrc(ZipLong.getValue(lfhBuf, off)); - off += WORD; - - cSize = new ZipLong(lfhBuf, off); - off += WORD; - - size = new ZipLong(lfhBuf, off); - off += WORD; - } else { - off += 3 * WORD; - } - - final int fileNameLen = ZipShort.getValue(lfhBuf, off); - - off += SHORT; - - final int extraLen = ZipShort.getValue(lfhBuf, off); - off += SHORT; // NOSONAR - assignment as documentation - - final byte[] fileName = new byte[fileNameLen]; - readFully(fileName); - current.entry.setName(entryEncoding.decode(fileName), fileName); - if (hasUTF8Flag) { - current.entry.setNameSource(ZipArchiveEntry.NameSource.NAME_WITH_EFS_FLAG); - } - - final byte[] extraData = new byte[extraLen]; - readFully(extraData); - current.entry.setExtra(extraData); - - if (!hasUTF8Flag && useUnicodeExtraFields) { - ZipUtil.setNameAndCommentFromExtraFields(current.entry, fileName, null); - } - - processZip64Extra(size, cSize); - - current.entry.setLocalHeaderOffset(currentHeaderOffset); - current.entry.setDataOffset(getBytesRead()); - current.entry.setStreamContiguous(true); - - ZipMethod m = ZipMethod.getMethodByCode(current.entry.getMethod()); - if (current.entry.getCompressedSize() != ArchiveEntry.SIZE_UNKNOWN) { - if (ZipUtil.canHandleEntryData(current.entry) && m != ZipMethod.STORED && m != ZipMethod.DEFLATED) { - InputStream bis = new BoundedInputStream(in, current.entry.getCompressedSize()); - switch (m) { - case UNSHRINKING: - current.in = new UnshrinkingInputStream(bis); - break; - case IMPLODING: - current.in = new ExplodingInputStream( - current.entry.getGeneralPurposeBit().getSlidingDictionarySize(), - current.entry.getGeneralPurposeBit().getNumberOfShannonFanoTrees(), - bis); - break; - case BZIP2: - current.in = new BZip2CompressorInputStream(bis); - break; - case ENHANCED_DEFLATED: - current.in = new Deflate64CompressorInputStream(bis); - break; - default: - // we should never get here as all supported methods have been covered - // will cause an error when read is invoked, don't throw an exception here so people can - // skip unsupported entries - break; - } - } - } else if (m == ZipMethod.ENHANCED_DEFLATED) { - current.in = new Deflate64CompressorInputStream(in); - } - - entriesRead++; - return current.entry; - } - - /** - * Fills the given array with the first local file header and - * deals with splitting/spanning markers that may prefix the first - * LFH. - */ -" -2,0," private static void assertCorrectConfig(User user, String unixPath) { - assertThat(user.getConfigFile().getFile().getPath(), endsWith(unixPath.replace('/', File.separatorChar))); - } - -" -3,0," public void testRepositoryCreation() throws Exception { - Client client = client(); - - File location = randomRepoPath(); - - logger.info(""--> creating repository""); - PutRepositoryResponse putRepositoryResponse = client.admin().cluster().preparePutRepository(""test-repo-1"") - .setType(""fs"").setSettings(ImmutableSettings.settingsBuilder() - .put(""location"", location) - ).get(); - assertThat(putRepositoryResponse.isAcknowledged(), equalTo(true)); - - logger.info(""--> verify the repository""); - int numberOfFiles = location.listFiles().length; - VerifyRepositoryResponse verifyRepositoryResponse = client.admin().cluster().prepareVerifyRepository(""test-repo-1"").get(); - assertThat(verifyRepositoryResponse.getNodes().length, equalTo(cluster().numDataAndMasterNodes())); - - logger.info(""--> verify that we didn't leave any files as a result of verification""); - assertThat(location.listFiles().length, equalTo(numberOfFiles)); - - logger.info(""--> check that repository is really there""); - ClusterStateResponse clusterStateResponse = client.admin().cluster().prepareState().clear().setMetaData(true).get(); - MetaData metaData = clusterStateResponse.getState().getMetaData(); - RepositoriesMetaData repositoriesMetaData = metaData.custom(RepositoriesMetaData.TYPE); - assertThat(repositoriesMetaData, notNullValue()); - assertThat(repositoriesMetaData.repository(""test-repo-1""), notNullValue()); - assertThat(repositoriesMetaData.repository(""test-repo-1"").type(), equalTo(""fs"")); - - logger.info(""--> creating another repository""); - putRepositoryResponse = client.admin().cluster().preparePutRepository(""test-repo-2"") - .setType(""fs"").setSettings(ImmutableSettings.settingsBuilder() - .put(""location"", randomRepoPath()) - ).get(); - assertThat(putRepositoryResponse.isAcknowledged(), equalTo(true)); - - logger.info(""--> check that both repositories are in cluster state""); - clusterStateResponse = client.admin().cluster().prepareState().clear().setMetaData(true).get(); - metaData = clusterStateResponse.getState().getMetaData(); - repositoriesMetaData = metaData.custom(RepositoriesMetaData.TYPE); - assertThat(repositoriesMetaData, notNullValue()); - assertThat(repositoriesMetaData.repositories().size(), equalTo(2)); - assertThat(repositoriesMetaData.repository(""test-repo-1""), notNullValue()); - assertThat(repositoriesMetaData.repository(""test-repo-1"").type(), equalTo(""fs"")); - assertThat(repositoriesMetaData.repository(""test-repo-2""), notNullValue()); - assertThat(repositoriesMetaData.repository(""test-repo-2"").type(), equalTo(""fs"")); - - logger.info(""--> check that both repositories can be retrieved by getRepositories query""); - GetRepositoriesResponse repositoriesResponse = client.admin().cluster().prepareGetRepositories().get(); - assertThat(repositoriesResponse.repositories().size(), equalTo(2)); - assertThat(findRepository(repositoriesResponse.repositories(), ""test-repo-1""), notNullValue()); - assertThat(findRepository(repositoriesResponse.repositories(), ""test-repo-2""), notNullValue()); - - logger.info(""--> delete repository test-repo-1""); - client.admin().cluster().prepareDeleteRepository(""test-repo-1"").get(); - repositoriesResponse = client.admin().cluster().prepareGetRepositories().get(); - assertThat(repositoriesResponse.repositories().size(), equalTo(1)); - assertThat(findRepository(repositoriesResponse.repositories(), ""test-repo-2""), notNullValue()); - - logger.info(""--> delete repository test-repo-2""); - client.admin().cluster().prepareDeleteRepository(""test-repo-2"").get(); - repositoriesResponse = client.admin().cluster().prepareGetRepositories().get(); - assertThat(repositoriesResponse.repositories().size(), equalTo(0)); - } - -" -4,0," protected Blob getBlob(ResultSet resultSet, int columnIndex, Metadata m) throws SQLException { - byte[] bytes = resultSet.getBytes(columnIndex); - if (!resultSet.wasNull()) { - return new SerialBlob(bytes); - } - return null; - } -" -5,0," private T run(PrivilegedAction action) { - return System.getSecurityManager() != null ? AccessController.doPrivileged( action ) : action.run(); - } -" -6,0," protected boolean statusDropsConnection(int status) { - return status == 400 /* SC_BAD_REQUEST */ || - status == 408 /* SC_REQUEST_TIMEOUT */ || - status == 411 /* SC_LENGTH_REQUIRED */ || - status == 413 /* SC_REQUEST_ENTITY_TOO_LARGE */ || - status == 414 /* SC_REQUEST_URI_TOO_LARGE */ || - status == 500 /* SC_INTERNAL_SERVER_ERROR */ || - status == 503 /* SC_SERVICE_UNAVAILABLE */ || - status == 501 /* SC_NOT_IMPLEMENTED */; - } - -" -7,0," private ControllerInfo getControllerInfo(Annotations annotation, String s) { - String[] data = s.split("":""); - if (data.length != 3) { - print(""Wrong format of the controller %s, should be in the format ::"", s); - return null; - } - String type = data[0]; - IpAddress ip = IpAddress.valueOf(data[1]); - int port = Integer.parseInt(data[2]); - if (annotation != null) { - return new ControllerInfo(ip, port, type, annotation); - } - return new ControllerInfo(ip, port, type); - } -" -8,0," public Authentication authenticate(Authentication authentication) throws AuthenticationException { - Assert.isInstanceOf(UsernamePasswordAuthenticationToken.class, authentication, - messages.getMessage(""LdapAuthenticationProvider.onlySupports"", - ""Only UsernamePasswordAuthenticationToken is supported"")); - - final UsernamePasswordAuthenticationToken userToken = (UsernamePasswordAuthenticationToken)authentication; - - String username = userToken.getName(); - String password = (String) authentication.getCredentials(); - - if (logger.isDebugEnabled()) { - logger.debug(""Processing authentication request for user: "" + username); - } - - if (!StringUtils.hasLength(username)) { - throw new BadCredentialsException(messages.getMessage(""LdapAuthenticationProvider.emptyUsername"", - ""Empty Username"")); - } - - if (!StringUtils.hasLength(password)) { - throw new BadCredentialsException(messages.getMessage(""AbstractLdapAuthenticationProvider.emptyPassword"", - ""Empty Password"")); - } - - Assert.notNull(password, ""Null password was supplied in authentication token""); - - DirContextOperations userData = doAuthentication(userToken); - - UserDetails user = userDetailsContextMapper.mapUserFromContext(userData, authentication.getName(), - loadUserAuthorities(userData, authentication.getName(), (String)authentication.getCredentials())); - - return createSuccessfulAuthentication(userToken, user); - } - -" -9,0," protected IgnoreCsrfProtectionRegistry chainRequestMatchers( - List requestMatchers) { - CsrfConfigurer.this.ignoredCsrfProtectionMatchers.addAll(requestMatchers); - return this; - } - } -}" -10,0," private String[] getParts(String encodedJWT) { - String[] parts = encodedJWT.split(""\\.""); - // Secured JWT XXXXX.YYYYY.ZZZZZ, Unsecured JWT XXXXX.YYYYY. - if (parts.length == 3 || (parts.length == 2 && encodedJWT.endsWith("".""))) { - return parts; - } - - throw new InvalidJWTException(""The encoded JWT is not properly formatted. Expected a three part dot separated string.""); - } -" -11,0," public String getAlgorithm() { - - return (this.algorithm); - - } - - - /** - * Set the message digest algorithm for this Manager. - * - * @param algorithm The new message digest algorithm - */ -" -12,0," public ChannelRequestMatcherRegistry getRegistry() { - return REGISTRY; - } - - @Override -" -13,0," public String getDefaultWebXml() { - if( defaultWebXml == null ) { - defaultWebXml=Constants.DefaultWebXml; - } - - return (this.defaultWebXml); - - } - - - /** - * Set the location of the default deployment descriptor - * - * @param path Absolute/relative path to the default web.xml - */ -" -14,0," public Collection getRequiredPermissions(String regionName) { - return Collections.singletonList(ResourcePermissions.DATA_MANAGE); - } - -" -15,0," private void enableAllocation(String index) { - client().admin().indices().prepareUpdateSettings(index).setSettings(ImmutableSettings.builder().put( - ""index.routing.allocation.enable"", ""all"" - )).get(); - } -" -16,0," public void parse(InputStream stream, ContentHandler ignore, - Metadata metadata, ParseContext context) throws IOException, - SAXException, TikaException { - //Test to see if we should avoid parsing - if (parserState.recursiveParserWrapperHandler.hasHitMaximumEmbeddedResources()) { - return; - } - // Work out what this thing is - String objectName = getResourceName(metadata, parserState); - String objectLocation = this.location + objectName; - - metadata.add(AbstractRecursiveParserWrapperHandler.EMBEDDED_RESOURCE_PATH, objectLocation); - - - //get a fresh handler - ContentHandler localHandler = parserState.recursiveParserWrapperHandler.getNewContentHandler(); - parserState.recursiveParserWrapperHandler.startEmbeddedDocument(localHandler, metadata); - - Parser preContextParser = context.get(Parser.class); - context.set(Parser.class, new EmbeddedParserDecorator(getWrappedParser(), objectLocation, parserState)); - long started = System.currentTimeMillis(); - try { - super.parse(stream, localHandler, metadata, context); - } catch (SAXException e) { - boolean wlr = isWriteLimitReached(e); - if (wlr == true) { - metadata.add(WRITE_LIMIT_REACHED, ""true""); - } else { - if (catchEmbeddedExceptions) { - ParserUtils.recordParserFailure(this, e, metadata); - } else { - throw e; - } - } - } catch(CorruptedFileException e) { - throw e; - } catch (TikaException e) { - if (catchEmbeddedExceptions) { - ParserUtils.recordParserFailure(this, e, metadata); - } else { - throw e; - } - } finally { - context.set(Parser.class, preContextParser); - long elapsedMillis = System.currentTimeMillis() - started; - metadata.set(RecursiveParserWrapperHandler.PARSE_TIME_MILLIS, Long.toString(elapsedMillis)); - parserState.recursiveParserWrapperHandler.endEmbeddedDocument(localHandler, metadata); - } - } - } - - /** - * This tracks the state of the parse of a single document. - * In future versions, this will allow the RecursiveParserWrapper to be thread safe. - */ - private class ParserState { - private int unknownCount = 0; - private final AbstractRecursiveParserWrapperHandler recursiveParserWrapperHandler; - private ParserState(AbstractRecursiveParserWrapperHandler handler) { - this.recursiveParserWrapperHandler = handler; - } - - - } -} -" -17,0," public static void beforeTests() throws Exception { - initCore(""solrconfig.xml"",""schema.xml""); - handler = new UpdateRequestHandler(); - } - - @Test -" -18,0," public void setUp() throws Exception { - interceptor = new I18nInterceptor(); - interceptor.init(); - params = new HashMap(); - session = new HashMap(); - - Map ctx = new HashMap(); - ctx.put(ActionContext.PARAMETERS, params); - ctx.put(ActionContext.SESSION, session); - ac = new ActionContext(ctx); - - Action action = new Action() { - public String execute() throws Exception { - return SUCCESS; - } - }; - mai = new MockActionInvocation(); - ((MockActionInvocation) mai).setAction(action); - ((MockActionInvocation) mai).setInvocationContext(ac); - } - - @After -" -19,0," private MockHttpServletRequestBuilder createChangePasswordRequest(ScimUser user, String code, boolean useCSRF, String password, String passwordConfirmation) throws Exception { - MockHttpServletRequestBuilder post = post(""/reset_password.do""); - if (useCSRF) { - post.with(csrf()); - } - post.param(""code"", code) - .param(""email"", user.getPrimaryEmail()) - .param(""password"", password) - .param(""password_confirmation"", passwordConfirmation); - return post; - } -" -20,0," protected Log getLog() { - return log; - } - - // ----------------------------------------------------------- Constructors - - -" -21,0," public int getCount() { - return iCount; - } - -" -22,0," public BeanDefinitionHolder decorate(Node node, BeanDefinitionHolder holder, - ParserContext parserContext) { - BeanDefinition filterChainProxy = holder.getBeanDefinition(); - - ManagedList securityFilterChains = new ManagedList(); - Element elt = (Element) node; - - MatcherType matcherType = MatcherType.fromElement(elt); - - List filterChainElts = DomUtils.getChildElementsByTagName(elt, - Elements.FILTER_CHAIN); - - for (Element chain : filterChainElts) { - String path = chain - .getAttribute(HttpSecurityBeanDefinitionParser.ATT_PATH_PATTERN); - String filters = chain - .getAttribute(HttpSecurityBeanDefinitionParser.ATT_FILTERS); - - if (!StringUtils.hasText(path)) { - parserContext.getReaderContext().error( - ""The attribute '"" - + HttpSecurityBeanDefinitionParser.ATT_PATH_PATTERN - + ""' must not be empty"", elt); - } - - if (!StringUtils.hasText(filters)) { - parserContext.getReaderContext().error( - ""The attribute '"" + HttpSecurityBeanDefinitionParser.ATT_FILTERS - + ""'must not be empty"", elt); - } - - BeanDefinition matcher = matcherType.createMatcher(parserContext, path, null); - - if (filters.equals(HttpSecurityBeanDefinitionParser.OPT_FILTERS_NONE)) { - securityFilterChains.add(createSecurityFilterChain(matcher, - new ManagedList(0))); - } - else { - String[] filterBeanNames = StringUtils - .tokenizeToStringArray(filters, "",""); - ManagedList filterChain = new ManagedList(filterBeanNames.length); - - for (String name : filterBeanNames) { - filterChain.add(new RuntimeBeanReference(name)); - } - - securityFilterChains.add(createSecurityFilterChain(matcher, filterChain)); - } - } - - filterChainProxy.getConstructorArgumentValues().addGenericArgumentValue( - securityFilterChains); - - return holder; - } - -" -23,0," public XObject execute(XPathContext xctxt) throws javax.xml.transform.TransformerException - { - - String fullName = m_arg0.execute(xctxt).str(); - int indexOfNSSep = fullName.indexOf(':'); - String result = null; - String propName = """"; - - // List of properties where the name of the - // property argument is to be looked for. - Properties xsltInfo = new Properties(); - - loadPropertyFile(XSLT_PROPERTIES, xsltInfo); - - if (indexOfNSSep > 0) - { - String prefix = (indexOfNSSep >= 0) - ? fullName.substring(0, indexOfNSSep) : """"; - String namespace; - - namespace = xctxt.getNamespaceContext().getNamespaceForPrefix(prefix); - propName = (indexOfNSSep < 0) - ? fullName : fullName.substring(indexOfNSSep + 1); - - if (namespace.startsWith(""http://www.w3.org/XSL/Transform"") - || namespace.equals(""http://www.w3.org/1999/XSL/Transform"")) - { - result = xsltInfo.getProperty(propName); - - if (null == result) - { - warn(xctxt, XPATHErrorResources.WG_PROPERTY_NOT_SUPPORTED, - new Object[]{ fullName }); //""XSL Property not supported: ""+fullName); - - return XString.EMPTYSTRING; - } - } - else - { - warn(xctxt, XPATHErrorResources.WG_DONT_DO_ANYTHING_WITH_NS, - new Object[]{ namespace, - fullName }); //""Don't currently do anything with namespace ""+namespace+"" in property: ""+fullName); - - try - { - //if secure procession is enabled only handle required properties do not not map any valid system property - if(!xctxt.isSecureProcessing()) - { - result = System.getProperty(fullName); - } - else - { - warn(xctxt, XPATHErrorResources.WG_SECURITY_EXCEPTION, - new Object[]{ fullName }); //""SecurityException when trying to access XSL system property: ""+fullName); - result = xsltInfo.getProperty(propName); - } - if (null == result) - { - return XString.EMPTYSTRING; - } - } - catch (SecurityException se) - { - warn(xctxt, XPATHErrorResources.WG_SECURITY_EXCEPTION, - new Object[]{ fullName }); //""SecurityException when trying to access XSL system property: ""+fullName); - - return XString.EMPTYSTRING; - } - } - } - else - { - try - { - //if secure procession is enabled only handle required properties do not not map any valid system property - if(!xctxt.isSecureProcessing()) - { - result = System.getProperty(fullName); - } - else - { - warn(xctxt, XPATHErrorResources.WG_SECURITY_EXCEPTION, - new Object[]{ fullName }); //""SecurityException when trying to access XSL system property: ""+fullName); - result = xsltInfo.getProperty(propName); - } - if (null == result) - { - return XString.EMPTYSTRING; - } - } - catch (SecurityException se) - { - warn(xctxt, XPATHErrorResources.WG_SECURITY_EXCEPTION, - new Object[]{ fullName }); //""SecurityException when trying to access XSL system property: ""+fullName); - - return XString.EMPTYSTRING; - } - } - - if (propName.equals(""version"") && result.length() > 0) - { - try - { - // Needs to return the version number of the spec we conform to. - return new XString(""1.0""); - } - catch (Exception ex) - { - return new XString(result); - } - } - else - return new XString(result); - } - - /** - * Retrieve a propery bundle from a specified file - * - * @param file The string name of the property file. The name - * should already be fully qualified as path/filename - * @param target The target property bag the file will be placed into. - */ -" -24,0," public boolean equals(Object obj) { - if ( this == obj ) { - return true; - } - if ( !super.equals( obj ) ) { - return false; - } - if ( getClass() != obj.getClass() ) { - return false; - } - ConstrainedExecutable other = (ConstrainedExecutable) obj; - if ( executable == null ) { - if ( other.executable != null ) { - return false; - } - } - else if ( !executable.equals( other.executable ) ) { - return false; - } - return true; - } -" -25,0," public static HierarchicalConfiguration loadXml(InputStream xmlStream) { - try { - XMLConfiguration cfg = new XMLConfiguration(); - DocumentBuilderFactory dbfactory = DocumentBuilderFactory.newInstance(); - //Disabling DTDs in order to avoid XXE xml-based attacks. - disableFeature(dbfactory, DISALLOW_DTD_FEATURE); - disableFeature(dbfactory, DISALLOW_EXTERNAL_DTD); - dbfactory.setXIncludeAware(false); - dbfactory.setExpandEntityReferences(false); - cfg.setDocumentBuilder(dbfactory.newDocumentBuilder()); - cfg.load(xmlStream); - return cfg; - } catch (ConfigurationException | ParserConfigurationException e) { - throw new IllegalArgumentException(""Cannot load xml from Stream"", e); - } - } - -" -26,0," void noteBytesRead(int pBytes) { - /* Indicates, that the given number of bytes have been read from - * the input stream. - */ - bytesRead += pBytes; - notifyListener(); - } - - /** - * Called to indicate, that a new file item has been detected. - */ -" -27,0," private static DocumentBuilder getBuilder() throws ParserConfigurationException { - ClassLoader loader = Thread.currentThread().getContextClassLoader(); - if (loader == null) { - loader = DOMUtils.class.getClassLoader(); - } - if (loader == null) { - DocumentBuilderFactory dbf = createDocumentBuilderFactory(); - return dbf.newDocumentBuilder(); - } - DocumentBuilder builder = DOCUMENT_BUILDERS.get(loader); - if (builder == null) { - DocumentBuilderFactory dbf = createDocumentBuilderFactory(); - builder = dbf.newDocumentBuilder(); - DOCUMENT_BUILDERS.put(loader, builder); - } - return builder; - } - - /** - * This function is much like getAttribute, but returns null, not """", for a nonexistent attribute. - * - * @param e - * @param attributeName - */ -" -28,0," public StandardInterceptUrlRegistry getRegistry() { - return REGISTRY; - } - - /** - * Adds an {@link ObjectPostProcessor} for this class. - * - * @param objectPostProcessor - * @return the {@link UrlAuthorizationConfigurer} for further customizations - */ -" -29,0," public synchronized XPathRecordReader addField(String name, String xpath, boolean multiValued, int flags) { - addField0(xpath, name, multiValued, false, flags); - return this; - } - - /** - * Splits the XPATH into a List of xpath segments and calls build() to - * construct a tree of Nodes representing xpath segments. The resulting - * tree structure ends up describing all the Xpaths we are interested in. - * - * @param xpath The xpath expression for this field - * @param name The name for this field in the emitted record - * @param multiValued If 'true' then the emitted record will have values in - * a List<String> - * @param isRecord Flags that this XPATH is from a forEach statement - * @param flags The only supported flag is 'FLATTEN' - */ -" -30,0," public void setConstants(ContainerBuilder builder) { - for (Object keyobj : keySet()) { - String key = (String)keyobj; - builder.factory(String.class, key, - new LocatableConstantFactory(getProperty(key), getPropertyLocation(key))); - } - } - } -} -" -31,0," public CommandLauncher launch(String host, TaskListener listener) throws IOException, InterruptedException { - return new CommandLauncher(command,new EnvVars(""SLAVE"",host)); - } - - @Extension @Symbol(""command"") -" -32,0," private void parseCSSStyleSheet(String sheet) throws SVGParseException - { - CSSParser cssp = new CSSParser(MediaType.screen); - svgDocument.addCSSRules(cssp.parse(sheet)); - } - -" -33,0," public void test_unsecuredJWT_validation() throws Exception { - JWT jwt = new JWT().setSubject(""123456789""); - Signer signer = new UnsecuredSigner(); - Verifier hmacVerifier = HMACVerifier.newVerifier(""too many secrets""); - - String encodedUnsecuredJWT = JWTEncoder.getInstance().encode(jwt, signer); - - // Ensure that attempting to decode an un-secured JWT fails when we provide a verifier - expectException(MissingVerifierException.class, () -> JWT.getDecoder().decode(encodedUnsecuredJWT, hmacVerifier)); - - String encodedUnsecuredJWT_withKid = JWTEncoder.getInstance().encode(jwt, signer, (header) -> header.set(""kid"", ""abc"")); - String encodedUnsecuredJWT_withoutKid = JWTEncoder.getInstance().encode(jwt, signer); - - Map verifierMap = new HashMap<>(); - verifierMap.put(null, hmacVerifier); - verifierMap.put(""abc"", hmacVerifier); - - // Ensure that attempting to decode an un-secured JWT fails when we provide a verifier with or without using a kid - expectException(MissingVerifierException.class, () -> JWT.getDecoder().decode(encodedUnsecuredJWT_withKid, verifierMap)); - expectException(MissingVerifierException.class, () -> JWT.getDecoder().decode(encodedUnsecuredJWT_withoutKid, verifierMap)); - } - - @Test -" -34,0," public String getConnectionName() { - return connectionName; - } - - /** - * Set the username to use to connect to the database. - * - * @param connectionName Username - */ -" -35,0," protected Log getLog() { - return log; - } - - @Override -" -36,0," public BigInteger[] decode( - byte[] encoding) - throws IOException - { - BigInteger[] sig = new BigInteger[2]; - - byte[] first = new byte[encoding.length / 2]; - byte[] second = new byte[encoding.length / 2]; - - System.arraycopy(encoding, 0, first, 0, first.length); - System.arraycopy(encoding, first.length, second, 0, second.length); - - sig[0] = new BigInteger(1, first); - sig[1] = new BigInteger(1, second); - - return sig; - } - } -}" -37,0," public ScimGroup mapRow(ResultSet rs, int rowNum) throws SQLException { - int pos = 1; - String id = rs.getString(pos++); - String name = rs.getString(pos++); - String description = rs.getString(pos++); - Date created = rs.getTimestamp(pos++); - Date modified = rs.getTimestamp(pos++); - int version = rs.getInt(pos++); - String zoneId = rs.getString(pos++); - ScimGroup group = new ScimGroup(id, name, zoneId); - group.setDescription(description); - ScimMeta meta = new ScimMeta(created, modified, version); - group.setMeta(meta); - return group; - } - } -} -" -38,0," public void testSendStringMessage() throws Exception { - sendMessageAndHaveItTransformed(""HeyHello world!""); - } - -" -39,0," public void testSingletonPatternInSerialization() { - final Object[] singletones = new Object[] { - ExceptionFactory.INSTANCE, - }; - - for (final Object original : singletones) { - TestUtils.assertSameAfterSerialization( - ""Singletone patern broken for "" + original.getClass(), - original - ); - } - } - -" -40,0," private void doTestParameterNameLengthRestriction( ParametersInterceptor parametersInterceptor, - int paramNameMaxLength ) { - StringBuilder sb = new StringBuilder(); - for (int i = 0; i < paramNameMaxLength + 1; i++) { - sb.append(""x""); - } - - Map actual = new LinkedHashMap(); - parametersInterceptor.setValueStackFactory(createValueStackFactory(actual)); - ValueStack stack = createStubValueStack(actual); - - Map parameters = new HashMap(); - parameters.put(sb.toString(), """"); - parameters.put(""huuhaa"", """"); - - Action action = new SimpleAction(); - parametersInterceptor.setParameters(action, stack, parameters); - assertEquals(1, actual.size()); - } - -" -41,0," public boolean equals(Object obj) { - if (obj instanceof CharEntry) { - return value.equals(((CharEntry) obj).value); - } - return false; - } - - } - - -} -" -42,0," protected boolean readMessage(AjpMessage message) - throws IOException { - - byte[] buf = message.getBuffer(); - int headerLength = message.getHeaderLength(); - - read(buf, 0, headerLength); - - int messageLength = message.processHeader(true); - if (messageLength < 0) { - // Invalid AJP header signature - // TODO: Throw some exception and close the connection to frontend. - return false; - } - else if (messageLength == 0) { - // Zero length message. - return true; - } - else { - if (messageLength > buf.length) { - // Message too long for the buffer - // Need to trigger a 400 response - throw new IllegalArgumentException(sm.getString( - ""ajpprocessor.header.tooLong"", - Integer.valueOf(messageLength), - Integer.valueOf(buf.length))); - } - read(buf, headerLength, messageLength); - return true; - } - } -" -43,0," public boolean allPresentAndPositive() { - return lockoutPeriodSeconds >= 0 && lockoutAfterFailures >= 0 && countFailuresWithin >= 0; - } -" -44,0," public boolean event(org.apache.coyote.Request req, - org.apache.coyote.Response res, SocketStatus status) { - - Request request = (Request) req.getNote(ADAPTER_NOTES); - Response response = (Response) res.getNote(ADAPTER_NOTES); - - if (request.getWrapper() != null) { - - boolean error = false; - try { - if (status == SocketStatus.OPEN) { - request.getEvent().setEventType(CometEvent.EventType.READ); - request.getEvent().setEventSubType(null); - } else if (status == SocketStatus.DISCONNECT) { - request.getEvent().setEventType(CometEvent.EventType.ERROR); - request.getEvent().setEventSubType(CometEvent.EventSubType.CLIENT_DISCONNECT); - error = true; - } else if (status == SocketStatus.ERROR) { - request.getEvent().setEventType(CometEvent.EventType.ERROR); - request.getEvent().setEventSubType(CometEvent.EventSubType.IOEXCEPTION); - error = true; - } else if (status == SocketStatus.STOP) { - request.getEvent().setEventType(CometEvent.EventType.END); - request.getEvent().setEventSubType(CometEvent.EventSubType.SERVER_SHUTDOWN); - } else if (status == SocketStatus.TIMEOUT) { - request.getEvent().setEventType(CometEvent.EventType.ERROR); - request.getEvent().setEventSubType(CometEvent.EventSubType.TIMEOUT); - } - - // Calling the container - connector.getContainer().getPipeline().getFirst().event(request, response, request.getEvent()); - - if (response.isClosed() || !request.isComet()) { - res.action(ActionCode.ACTION_COMET_END, null); - } - return (!error); - } catch (Throwable t) { - if (!(t instanceof IOException)) { - log.error(sm.getString(""coyoteAdapter.service""), t); - } - error = true; - // FIXME: Since there's likely some structures kept in the servlet or elsewhere, - // a cleanup event of some sort could be needed ? - return false; - } finally { - // Recycle the wrapper request and response - if (error || response.isClosed() || !request.isComet()) { - request.recycle(); - request.setFilterChain(null); - response.recycle(); - } - } - - } else { - return false; - } - } - - - /** - * Service method. - */ -" -45,0," public void testSnapshotAndRestore() throws ExecutionException, InterruptedException, IOException { - logger.info(""--> creating repository""); - assertAcked(client().admin().cluster().preparePutRepository(""test-repo"") - .setType(""fs"").setSettings(ImmutableSettings.settingsBuilder() - .put(""location"", randomRepoPath().getAbsolutePath()) - .put(""compress"", randomBoolean()) - .put(""chunk_size"", randomIntBetween(100, 1000)))); - String[] indicesBefore = new String[randomIntBetween(2,5)]; - String[] indicesAfter = new String[randomIntBetween(2,5)]; - for (int i = 0; i < indicesBefore.length; i++) { - indicesBefore[i] = ""index_before_"" + i; - createIndex(indicesBefore[i]); - } - for (int i = 0; i < indicesAfter.length; i++) { - indicesAfter[i] = ""index_after_"" + i; - createIndex(indicesAfter[i]); - } - String[] indices = new String[indicesBefore.length + indicesAfter.length]; - System.arraycopy(indicesBefore, 0, indices, 0, indicesBefore.length); - System.arraycopy(indicesAfter, 0, indices, indicesBefore.length, indicesAfter.length); - ensureYellow(); - logger.info(""--> indexing some data""); - IndexRequestBuilder[] buildersBefore = new IndexRequestBuilder[randomIntBetween(10, 200)]; - for (int i = 0; i < buildersBefore.length; i++) { - buildersBefore[i] = client().prepareIndex(RandomPicks.randomFrom(getRandom(), indicesBefore), ""foo"", Integer.toString(i)).setSource(""{ \""foo\"" : \""bar\"" } ""); - } - IndexRequestBuilder[] buildersAfter = new IndexRequestBuilder[randomIntBetween(10, 200)]; - for (int i = 0; i < buildersAfter.length; i++) { - buildersAfter[i] = client().prepareIndex(RandomPicks.randomFrom(getRandom(), indicesBefore), ""bar"", Integer.toString(i)).setSource(""{ \""foo\"" : \""bar\"" } ""); - } - indexRandom(true, buildersBefore); - indexRandom(true, buildersAfter); - assertThat(client().prepareCount(indices).get().getCount(), equalTo((long) (buildersBefore.length + buildersAfter.length))); - long[] counts = new long[indices.length]; - for (int i = 0; i < indices.length; i++) { - counts[i] = client().prepareCount(indices[i]).get().getCount(); - } - - logger.info(""--> snapshot subset of indices before upgrage""); - CreateSnapshotResponse createSnapshotResponse = client().admin().cluster().prepareCreateSnapshot(""test-repo"", ""test-snap-1"").setWaitForCompletion(true).setIndices(""index_before_*"").get(); - assertThat(createSnapshotResponse.getSnapshotInfo().successfulShards(), greaterThan(0)); - assertThat(createSnapshotResponse.getSnapshotInfo().successfulShards(), equalTo(createSnapshotResponse.getSnapshotInfo().totalShards())); - - assertThat(client().admin().cluster().prepareGetSnapshots(""test-repo"").setSnapshots(""test-snap-1"").get().getSnapshots().get(0).state(), equalTo(SnapshotState.SUCCESS)); - - logger.info(""--> delete some data from indices that were already snapshotted""); - int howMany = randomIntBetween(1, buildersBefore.length); - - for (int i = 0; i < howMany; i++) { - IndexRequestBuilder indexRequestBuilder = RandomPicks.randomFrom(getRandom(), buildersBefore); - IndexRequest request = indexRequestBuilder.request(); - client().prepareDelete(request.index(), request.type(), request.id()).get(); - } - refresh(); - final long numDocs = client().prepareCount(indices).get().getCount(); - assertThat(client().prepareCount(indices).get().getCount(), lessThan((long) (buildersBefore.length + buildersAfter.length))); - - - client().admin().indices().prepareUpdateSettings(indices).setSettings(ImmutableSettings.builder().put(EnableAllocationDecider.INDEX_ROUTING_ALLOCATION_ENABLE, ""none"")).get(); - backwardsCluster().allowOnAllNodes(indices); - logClusterState(); - boolean upgraded; - do { - logClusterState(); - CountResponse countResponse = client().prepareCount().get(); - assertHitCount(countResponse, numDocs); - upgraded = backwardsCluster().upgradeOneNode(); - ensureYellow(); - countResponse = client().prepareCount().get(); - assertHitCount(countResponse, numDocs); - } while (upgraded); - client().admin().indices().prepareUpdateSettings(indices).setSettings(ImmutableSettings.builder().put(EnableAllocationDecider.INDEX_ROUTING_ALLOCATION_ENABLE, ""all"")).get(); - - logger.info(""--> close indices""); - client().admin().indices().prepareClose(""index_before_*"").get(); - - logger.info(""--> verify repository""); - client().admin().cluster().prepareVerifyRepository(""test-repo"").get(); - - logger.info(""--> restore all indices from the snapshot""); - RestoreSnapshotResponse restoreSnapshotResponse = client().admin().cluster().prepareRestoreSnapshot(""test-repo"", ""test-snap-1"").setWaitForCompletion(true).execute().actionGet(); - assertThat(restoreSnapshotResponse.getRestoreInfo().totalShards(), greaterThan(0)); - - ensureYellow(); - assertThat(client().prepareCount(indices).get().getCount(), equalTo((long) (buildersBefore.length + buildersAfter.length))); - for (int i = 0; i < indices.length; i++) { - assertThat(counts[i], equalTo(client().prepareCount(indices[i]).get().getCount())); - } - - logger.info(""--> snapshot subset of indices after upgrade""); - createSnapshotResponse = client().admin().cluster().prepareCreateSnapshot(""test-repo"", ""test-snap-2"").setWaitForCompletion(true).setIndices(""index_*"").get(); - assertThat(createSnapshotResponse.getSnapshotInfo().successfulShards(), greaterThan(0)); - assertThat(createSnapshotResponse.getSnapshotInfo().successfulShards(), equalTo(createSnapshotResponse.getSnapshotInfo().totalShards())); - - // Test restore after index deletion - logger.info(""--> delete indices""); - String index = RandomPicks.randomFrom(getRandom(), indices); - cluster().wipeIndices(index); - logger.info(""--> restore one index after deletion""); - restoreSnapshotResponse = client().admin().cluster().prepareRestoreSnapshot(""test-repo"", ""test-snap-2"").setWaitForCompletion(true).setIndices(index).execute().actionGet(); - assertThat(restoreSnapshotResponse.getRestoreInfo().totalShards(), greaterThan(0)); - ensureYellow(); - assertThat(client().prepareCount(indices).get().getCount(), equalTo((long) (buildersBefore.length + buildersAfter.length))); - for (int i = 0; i < indices.length; i++) { - assertThat(counts[i], equalTo(client().prepareCount(indices[i]).get().getCount())); - } - } - -" -46,0," public XMSSPrivateKeyParameters getNextKey() - { - /* prepare authentication path for next leaf */ - int treeHeight = this.params.getHeight(); - if (this.getIndex() < ((1 << treeHeight) - 1)) - { - return new XMSSPrivateKeyParameters.Builder(params) - .withSecretKeySeed(secretKeySeed).withSecretKeyPRF(secretKeyPRF) - .withPublicSeed(publicSeed).withRoot(root) - .withBDSState(bdsState.getNextState(publicSeed, secretKeySeed, (OTSHashAddress)new OTSHashAddress.Builder().build())).build(); - } - else - { - return new XMSSPrivateKeyParameters.Builder(params) - .withSecretKeySeed(secretKeySeed).withSecretKeyPRF(secretKeyPRF) - .withPublicSeed(publicSeed).withRoot(root) - .withBDSState(new BDS(params, getIndex() + 1)).build(); // no more nodes left. - } - } - -" -47,0," public void addRecipients(final ExtendedEmailPublisherContext context, EnvVars env, Set to, Set cc, Set 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(); - // looking for Upstream build. - Run cur = context.getRun(); - Cause.UpstreamCause upc = cur.getCause(Cause.UpstreamCause.class); - while (upc != null) { - // UpstreamCause.getUpStreamProject() returns the full name, so use getItemByFullName - 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); - } - addUserTriggeringTheBuild(cur, to, cc, bcc, env, context, debug); - } - -" -48,0," public void setSslSupport(SSLSupport sslSupport) { - this.sslSupport = sslSupport; - } -" -49,0," public void loadPropertyFile(String file, Properties target) - { - try - { - // Use SecuritySupport class to provide privileged access to property file - InputStream is = SecuritySupport.getResourceAsStream(ObjectFactory.findClassLoader(), - file); - - // get a buffered version - BufferedInputStream bis = new BufferedInputStream(is); - - target.load(bis); // and load up the property bag from this - bis.close(); // close out after reading - } - catch (Exception ex) - { - // ex.printStackTrace(); - throw new org.apache.xml.utils.WrappedRuntimeException(ex); - } - } -" -50,0," protected MimeTypes getMimeTypes() { - return embeddedDocumentUtil.getMimeTypes(); - } - -" -51,0," public int getKDFInfo() { - final int unusedBit28 = 0x8000000; // 1000000000000000000000000000 - - // kdf version is bits 1-27, bit 28 (reserved) should be 0, and - // bits 29-32 are the MAC algorithm indicating which PRF to use for the KDF. - int kdfVers = getKDFVersion(); - assert kdfVers > 0 && kdfVers <= 99991231 : ""KDF version (YYYYMMDD, max 99991231) out of range: "" + kdfVers; - int kdfInfo = kdfVers; - int macAlg = kdfPRFAsInt(); - assert macAlg >= 0 && macAlg <= 15 : ""MAC algorithm indicator must be between 0 to 15 inclusion; value is: "" + macAlg; - - // Make sure bit28 is cleared. (Reserved for future use.) - kdfInfo &= ~unusedBit28; - - // Set MAC algorithm bits in high (MSB) nibble. - kdfInfo |= (macAlg << 28); - - return kdfInfo; - } -" -52,0," private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { - stream.defaultReadObject(); - EVIL_BIT = 1; - } - - } - -} -" -53,0," public void onStartup(Set> c, ServletContext ctx) - throws ServletException { - Servlet s; - - if (createServlet) { - s = ctx.createServlet(servlet.getClass()); - } else { - s = servlet; - } - ServletRegistration.Dynamic r = ctx.addServlet(""servlet"", s); - r.addMapping(""/""); - } - } -} -" -54,0," public ResetPasswordResponse resetPassword(String code, String newPassword) throws InvalidPasswordException { - try { - passwordValidator.validate(newPassword); - return changePasswordCodeAuthenticated(code, newPassword); - } catch (RestClientException e) { - throw new UaaException(e.getMessage()); - } - } - -" -55,0," public Api getApi() { - return new Api(this); - } - - /** - * Returns the instance of this class. - * If {@link jenkins.model.Jenkins#getInstance()} isn't available - * or the plugin class isn't registered null will be returned. - * - * @return the instance. - */ - @CheckForNull -" -56,0," protected int readMessage(AjpMessage message, boolean blockFirstRead) - throws IOException { - - byte[] buf = message.getBuffer(); - int headerLength = message.getHeaderLength(); - - int bytesRead = read(buf, 0, headerLength, blockFirstRead); - - if (bytesRead == 0) { - return 0; - } - - int messageLength = message.processHeader(true); - if (messageLength < 0) { - // Invalid AJP header signature - throw new IOException(sm.getString(""ajpmessage.invalidLength"", - Integer.valueOf(messageLength))); - } - else if (messageLength == 0) { - // Zero length message. - return bytesRead; - } - else { - if (messageLength > buf.length) { - // Message too long for the buffer - // Need to trigger a 400 response - throw new IllegalArgumentException(sm.getString( - ""ajpprocessor.header.tooLong"", - Integer.valueOf(messageLength), - Integer.valueOf(buf.length))); - } - bytesRead += read(buf, headerLength, messageLength, true); - return bytesRead; - } - } - - -" -57,0," public boolean isHA() { - return false; - } - - @Override -" -58,0," public XMSSMTPrivateKeyParameters getNextKey() - { - BDSStateMap newState = new BDSStateMap(bdsState, params, this.getIndex(), publicSeed, secretKeySeed); - - return new XMSSMTPrivateKeyParameters.Builder(params).withIndex(index + 1) - .withSecretKeySeed(secretKeySeed).withSecretKeyPRF(secretKeyPRF) - .withPublicSeed(publicSeed).withRoot(root) - .withBDSState(newState).build(); - } -" -59,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; - } - -" -60,0," long getTimeStamp(); - -" -61,0," public void init(KeyGenerationParameters param) - { - this.param = (RSAKeyGenerationParameters)param; - } - -" -62,0," public Document getMetaData(Idp config) throws RuntimeException { - try { - //Return as text/xml - Crypto crypto = CertsUtils.createCrypto(config.getCertificate()); - - W3CDOMStreamWriter writer = new W3CDOMStreamWriter(); - - writer.writeStartDocument(""UTF-8"", ""1.0""); - - String referenceID = IDGenerator.generateID(""_""); - writer.writeStartElement(""md"", ""EntityDescriptor"", SAML2_METADATA_NS); - writer.writeAttribute(""ID"", referenceID); - - writer.writeAttribute(""entityID"", config.getIdpUrl().toString()); - - 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); - - writeFederationMetadata(writer, config, crypto); - - writer.writeEndElement(); // EntityDescriptor - - writer.writeEndDocument(); - - writer.close(); - - if (LOG.isDebugEnabled()) { - String out = DOM2Writer.nodeToString(writer.getDocument()); - LOG.debug(""***************** unsigned ****************""); - LOG.debug(out); - LOG.debug(""***************** unsigned ****************""); - } - - Document result = SignatureUtils.signMetaInfo(crypto, null, config.getCertificatePassword(), - writer.getDocument(), referenceID); - if (result != null) { - return result; - } else { - throw new RuntimeException(""Failed to sign the metadata document: result=null""); - } - } catch (Exception e) { - LOG.error(""Error creating service metadata information "", e); - throw new RuntimeException(""Error creating service metadata information: "" + e.getMessage()); - } - - } - -" -63,0," protected void publish(ApplicationEvent event) { - if (publisher!=null) { - publisher.publishEvent(event); - } - } -" -64,0," private static File getUnsanitizedLegacyConfigFileFor(String id) { - return new File(getRootDir(), idStrategy().legacyFilenameOf(id) + ""/config.xml""); - } - - /** - * Gets the directory where Hudson stores user information. - */ -" -65,0," protected void _initFactories(XMLInputFactory xmlIn, XMLOutputFactory xmlOut) - { - // Better ensure namespaces get built properly, so: - xmlOut.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, Boolean.TRUE); - // and for parser, force coalescing as well (much simpler to use) - xmlIn.setProperty(XMLInputFactory.IS_COALESCING, Boolean.TRUE); - } - - /** - * Note: compared to base implementation by {@link JsonFactory}, - * here the copy will actually share underlying XML input and - * output factories, as there is no way to make copies of those. - * - * @since 2.1 - */ - @Override -" -66,0," public ScimUser retrieve(String id) { - try { - ScimUser u = jdbcTemplate.queryForObject(USER_BY_ID_QUERY, mapper, id); - return u; - } catch (EmptyResultDataAccessException e) { - throw new ScimResourceNotFoundException(""User "" + id + "" does not exist""); - } - } - - @Override -" -67,0," private T run(PrivilegedAction action) { - return System.getSecurityManager() != null ? AccessController.doPrivileged( action ) : action.run(); - } -" -68,0," public boolean getMapperDirectoryRedirectEnabled() { return false; } -" -69,0," protected void setUpResources(JAXRSServerFactoryBean sf) { - sf.setResourceClasses(TikaResource.class); - sf.setResourceProvider(TikaResource.class, - new SingletonResourceProvider(new TikaResource())); - } - - @Override -" -70,0," public HttpBinding getBinding() { - if (this.binding == null) { - this.binding = new AttachmentHttpBinding(); - this.binding.setTransferException(isTransferException()); - if (getComponent() != null) { - this.binding.setAllowJavaSerializedObject(getComponent().isAllowJavaSerializedObject()); - } - this.binding.setHeaderFilterStrategy(getHeaderFilterStrategy()); - } - return this.binding; - } - - @Override -" -71,0," public void testNamedEntity() throws Exception { - assertU(""\n""+ - ""\n]>""+ - """"+ - ""1""+ - ""&wacky;"" + - """"); - - assertU(""""); - assertQ(req(""foo_s:zzz""), - ""//*[@numFound='1']"" - ); - } - - @Test -" -72,0," private FreeStyleProject createDownstreamProject() throws Exception { - FreeStyleProject dp = createFreeStyleProject(""downstream""); - - // Hm, no setQuietPeriod, have to submit form.. - WebClient webClient = new WebClient(); - HtmlPage page = webClient.getPage(dp,""configure""); - HtmlForm form = page.getFormByName(""config""); - form.getInputByName(""hasCustomQuietPeriod"").click(); - form.getInputByName(""quiet_period"").setValueAttribute(""0""); - submit(form); - assertEquals(""set quiet period"", 0, dp.getQuietPeriod()); - - return dp; - } - -" -73,0," public void setOkStatusCodeRange(String okStatusCodeRange) { - this.okStatusCodeRange = okStatusCodeRange; - } -" -74,0," public boolean shouldParseEmbedded(Metadata metadata) { - DocumentSelector selector = context.get(DocumentSelector.class); - if (selector != null) { - return selector.select(metadata); - } - - FilenameFilter filter = context.get(FilenameFilter.class); - if (filter != null) { - String name = metadata.get(Metadata.RESOURCE_NAME_KEY); - if (name != null) { - return filter.accept(ABSTRACT_PATH, name); - } - } - - return true; - } - -" -75,0," public void testLockTryingToDelete() throws Exception { - String lockType = ""native""; // test does not work with simple locks - Settings nodeSettings = ImmutableSettings.builder() - .put(""gateway.type"", ""local"") // don't delete things! - .put(""index.store.fs.fs_lock"", lockType) - .build(); - String IDX = ""test""; - logger.info(""--> lock type: {}"", lockType); - - internalCluster().startNode(nodeSettings); - Settings idxSettings = ImmutableSettings.builder() - .put(IndexMetaData.SETTING_NUMBER_OF_SHARDS, 1) - .put(IndexMetaData.SETTING_NUMBER_OF_REPLICAS, 0) - .put(""index.store.fs.fs_lock"", lockType) - .build(); - - // only one node, so all primaries will end up on node1 - prepareCreate(IDX).setSettings(idxSettings).addMapping(""doc"", ""foo"", ""type=string,index=not_analyzed"").get(); - ensureGreen(IDX); - client().prepareIndex(IDX, ""doc"").setSource(""foo"", ""bar"").get(); - flushAndRefresh(IDX); - NodeEnvironment env = internalCluster().getDataNodeInstance(NodeEnvironment.class); - logger.info(""--> data paths: [{}]"", env.nodeDataPaths()); - Path[] shardPaths = env.shardDataPaths(new ShardId(""test"", 0), ImmutableSettings.builder().build()); - logger.info(""--> paths: [{}]"", shardPaths); - // Should not be able to acquire the lock because it's already open - try { - NodeEnvironment.acquireFSLockForPaths(ImmutableSettings.EMPTY, shardPaths); - fail(""should not have been able to acquire the lock""); - } catch (ElasticsearchException e) { - assertTrue(""msg: "" + e.getMessage(), e.getMessage().contains(""unable to acquire write.lock"")); - } - // Test without the regular shard lock to assume we can acquire it - // (worst case, meaning that the shard lock could be acquired and - // we're green to delete the shard's directory) - ShardLock sLock = new DummyShardLock(new ShardId(""test"", 0)); - try { - env.deleteShardDirectoryUnderLock(sLock, ImmutableSettings.builder().build()); - fail(""should not have been able to delete the directory""); - } catch (ElasticsearchException e) { - assertTrue(""msg: "" + e.getMessage(), e.getMessage().contains(""unable to acquire write.lock"")); - } - } -" -76,0," public KeyPair generateKeyPair() - { - if (!initialised) - { - Integer paramStrength = Integers.valueOf(strength); - - if (params.containsKey(paramStrength)) - { - param = (DSAKeyGenerationParameters)params.get(paramStrength); - } - else - { - synchronized (lock) - { - // we do the check again in case we were blocked by a generator for - // our key size. - if (params.containsKey(paramStrength)) - { - param = (DSAKeyGenerationParameters)params.get(paramStrength); - } - else - { - DSAParametersGenerator pGen; - DSAParameterGenerationParameters dsaParams; - - // Typical combination of keysize and size of q. - // keysize = 1024, q's size = 160 - // keysize = 2048, q's size = 224 - // keysize = 2048, q's size = 256 - // keysize = 3072, q's size = 256 - // For simplicity if keysize is greater than 1024 then we choose q's size to be 256. - // For legacy keysize that is less than 1024-bit, we just use the 186-2 style parameters - if (strength == 1024) - { - pGen = new DSAParametersGenerator(); - if (Properties.isOverrideSet(""org.bouncycastle.dsa.FIPS186-2for1024bits"")) - { - pGen.init(strength, certainty, random); - } - else - { - dsaParams = new DSAParameterGenerationParameters(1024, 160, certainty, random); - pGen.init(dsaParams); - } - } - else if (strength > 1024) - { - dsaParams = new DSAParameterGenerationParameters(strength, 256, certainty, random); - pGen = new DSAParametersGenerator(new SHA256Digest()); - pGen.init(dsaParams); - } - else - { - pGen = new DSAParametersGenerator(); - pGen.init(strength, certainty, random); - } - param = new DSAKeyGenerationParameters(random, pGen.generateParameters()); - - params.put(paramStrength, param); - } - } - } - - engine.init(param); - initialised = true; - } - - AsymmetricCipherKeyPair pair = engine.generateKeyPair(); - DSAPublicKeyParameters pub = (DSAPublicKeyParameters)pair.getPublic(); - DSAPrivateKeyParameters priv = (DSAPrivateKeyParameters)pair.getPrivate(); - - return new KeyPair(new BCDSAPublicKey(pub), new BCDSAPrivateKey(priv)); - } -" -77,0," Attributes setPropertiesFromAttributes( - StylesheetHandler handler, String rawName, Attributes attributes, - ElemTemplateElement target, boolean throwError) - throws org.xml.sax.SAXException - { - - XSLTElementDef def = getElemDef(); - AttributesImpl undefines = null; - boolean isCompatibleMode = ((null != handler.getStylesheet() - && handler.getStylesheet().getCompatibleMode()) - || !throwError); - if (isCompatibleMode) - undefines = new AttributesImpl(); - - - // Keep track of which XSLTAttributeDefs have been processed, so - // I can see which default values need to be set. - List processedDefs = new ArrayList(); - - // Keep track of XSLTAttributeDefs that were invalid - List errorDefs = new ArrayList(); - int nAttrs = attributes.getLength(); - - for (int i = 0; i < nAttrs; i++) - { - String attrUri = attributes.getURI(i); - // Hack for Crimson. -sb - if((null != attrUri) && (attrUri.length() == 0) - && (attributes.getQName(i).startsWith(""xmlns:"") || - attributes.getQName(i).equals(""xmlns""))) - { - attrUri = org.apache.xalan.templates.Constants.S_XMLNAMESPACEURI; - } - String attrLocalName = attributes.getLocalName(i); - XSLTAttributeDef attrDef = def.getAttributeDef(attrUri, attrLocalName); - - if (null == attrDef) - { - if (!isCompatibleMode) - { - - // Then barf, because this element does not allow this attribute. - handler.error(XSLTErrorResources.ER_ATTR_NOT_ALLOWED, new Object[]{attributes.getQName(i), rawName}, null);//""\""""+attributes.getQName(i)+""\"""" - //+ "" attribute is not allowed on the "" + rawName - // + "" element!"", null); - } - else - { - undefines.addAttribute(attrUri, attrLocalName, - attributes.getQName(i), - attributes.getType(i), - attributes.getValue(i)); - } - } - else - { - //handle secure processing - if(handler.getStylesheetProcessor()==null) - System.out.println(""stylesheet processor null""); - if(attrDef.getName().compareTo(""*"")==0 && handler.getStylesheetProcessor().isSecureProcessing()) - { - //foreign attributes are not allowed in secure processing mode - // Then barf, because this element does not allow this attribute. - handler.error(XSLTErrorResources.ER_ATTR_NOT_ALLOWED, new Object[]{attributes.getQName(i), rawName}, null);//""\""""+attributes.getQName(i)+""\"""" - //+ "" attribute is not allowed on the "" + rawName - // + "" element!"", null); - } - else - { - - - boolean success = attrDef.setAttrValue(handler, attrUri, attrLocalName, - attributes.getQName(i), attributes.getValue(i), - target); - - // Now we only add the element if it passed a validation check - if (success) - processedDefs.add(attrDef); - else - errorDefs.add(attrDef); - } - } - } - - XSLTAttributeDef[] attrDefs = def.getAttributes(); - int nAttrDefs = attrDefs.length; - - for (int i = 0; i < nAttrDefs; i++) - { - XSLTAttributeDef attrDef = attrDefs[i]; - String defVal = attrDef.getDefault(); - - if (null != defVal) - { - if (!processedDefs.contains(attrDef)) - { - attrDef.setDefAttrValue(handler, target); - } - } - - if (attrDef.getRequired()) - { - if ((!processedDefs.contains(attrDef)) && (!errorDefs.contains(attrDef))) - handler.error( - XSLMessages.createMessage( - XSLTErrorResources.ER_REQUIRES_ATTRIB, new Object[]{ rawName, - attrDef.getName() }), null); - } - } - - return undefines; - } -" -78,0," public static void beforeClass() throws Exception { - SUITE_SEED = randomLong(); - initializeSuiteScope(); - } - -" -79,0," public void connect(HttpConsumer consumer) throws Exception { - } - - /** - * Disconnects the URL specified on the endpoint from the specified processor. - * - * @param consumer the consumer - * @throws Exception can be thrown - */ -" -80,0," private void writeAttribute(SessionAttribute sessionAttribute) throws IOException { - write(""""); - writeDirectly(htmlEncodeButNotSpace(sessionAttribute.getName())); - write(""""); - write(String.valueOf(sessionAttribute.getType())); - write(""""); - if (sessionAttribute.isSerializable()) { - write(""#oui#""); - } else { - write(""#non#""); - } - write(""""); - write(integerFormat.format(sessionAttribute.getSerializedSize())); - write(""""); - writeDirectly(htmlEncodeButNotSpace(String.valueOf(sessionAttribute.getContent()))); - write(""""); - } -" -81,0," public boolean isUseRouteBuilder() { - return false; - } - - @Test - @Ignore -" -82,0," public String getDisplayName() { - return ""Developers""; - } - } -} -" -83,0," private T run(PrivilegedExceptionAction action) throws JAXBException { - try { - return System.getSecurityManager() != null ? AccessController.doPrivileged( action ) : action.run(); - } - catch ( JAXBException e ) { - throw e; - } - catch ( Exception e ) { - throw log.getErrorParsingMappingFileException( e ); - } - } - - // JAXB closes the underlying input stream -" -84,0," protected void checkIllegalTypes(DeserializationContext ctxt, JavaType type, - BeanDescription beanDesc) - throws JsonMappingException - { - // There are certain nasty classes that could cause problems, mostly - // via default typing -- catch them here. - String full = type.getRawClass().getName(); - - if (_cfgIllegalClassNames.contains(full)) { - throw JsonMappingException.from(ctxt, - String.format(""Illegal type (%s) to deserialize: prevented for security reasons"", full)); - } - } -" -85,0," public FileVisitResult postVisitDirectory(Path dir, IOException ioe) - throws IOException { - // NO-OP - return FileVisitResult.CONTINUE; - }}); - } -} -" -86,0," public JettyHttpEndpoint getEndpoint() { - return (JettyHttpEndpoint) super.getEndpoint(); - } - -" -87,0," public static File randomRepoPath(Settings settings) { - Environment environment = new Environment(settings); - File[] repoFiles = environment.repoFiles(); - assert repoFiles.length > 0; - File path; - do { - path = new File(repoFiles[0], randomAsciiOfLength(10)); - } while (path.exists()); - return path; - } - -" -88,0," public void setup() { - this.request = new MockHttpServletRequest(); - this.request.setMethod(""GET""); - this.response = new MockHttpServletResponse(); - this.chain = new MockFilterChain(); - } - - @After -" -89,0," public static Context getCurrentContext() - { - return __context.get(); - } - -" -90,0," protected Log getLog() { - return log; - } - - // ----------------------------------------------------------- Constructors - - -" -91,0," protected void checkIllegalTypes(DeserializationContext ctxt, JavaType type, - BeanDescription beanDesc) - throws JsonMappingException - { - // There are certain nasty classes that could cause problems, mostly - // via default typing -- catch them here. - String full = type.getRawClass().getName(); - - if (_cfgIllegalClassNames.contains(full)) { - ctxt.reportBadTypeDefinition(beanDesc, - ""Illegal type (%s) to deserialize: prevented for security reasons"", full); - } - } -" -92,0," public String toString() { - return xpathExpression; - } -" -93,0," protected void setLocale(HttpServletRequest request) { - if (defaultLocale == null) { - defaultLocale = request.getLocale(); - } - } - -" -94,0," protected boolean isWithinLengthLimit( String name ) { - return name.length() <= paramNameMaxLength; - } - -" -95,0," private CoderResult decodeHasArray(ByteBuffer in, CharBuffer out) { - int outRemaining = out.remaining(); - int pos = in.position(); - int limit = in.limit(); - final byte[] bArr = in.array(); - final char[] cArr = out.array(); - final int inIndexLimit = limit + in.arrayOffset(); - int inIndex = pos + in.arrayOffset(); - int outIndex = out.position() + out.arrayOffset(); - // if someone would change the limit in process, - // he would face consequences - for (; inIndex < inIndexLimit && outRemaining > 0; inIndex++) { - int jchar = bArr[inIndex]; - if (jchar < 0) { - jchar = jchar & 0x7F; - int tail = remainingBytes[jchar]; - if (tail == -1) { - in.position(inIndex - in.arrayOffset()); - out.position(outIndex - out.arrayOffset()); - return CoderResult.malformedForLength(1); - } - if (inIndexLimit - inIndex < 1 + tail) { - // Apache Tomcat added tests - detect invalid sequences as - // early as possible - if (jchar == 0x74 && inIndexLimit > inIndex + 1) { - if ((bArr[inIndex + 1] & 0xFF) > 0x8F) { - // 11110100 1yyyxxxx xxxxxxxx xxxxxxxx - // Any non-zero y is > max code point - return CoderResult.unmappableForLength(4); - } - } - if (jchar == 0x60 && inIndexLimit > inIndex +1) { - if ((bArr[inIndex + 1] & 0x7F) == 0) { - // 11100000 10000000 10xxxxxx - // should have been - // 00xxxxxx - return CoderResult.malformedForLength(3); - } - } - if (jchar == 0x70 && inIndexLimit > inIndex +1) { - if ((bArr[inIndex + 1] & 0x7F) < 0x10) { - // 11110000 1000zzzz 1oyyyyyy 1oxxxxxx - // should have been - // 111ozzzz 1oyyyyyy 1oxxxxxx - return CoderResult.malformedForLength(4); - } - } - break; - } - for (int i = 0; i < tail; i++) { - int nextByte = bArr[inIndex + i + 1] & 0xFF; - if ((nextByte & 0xC0) != 0x80) { - in.position(inIndex - in.arrayOffset()); - out.position(outIndex - out.arrayOffset()); - return CoderResult.malformedForLength(1 + i); - } - jchar = (jchar << 6) + nextByte; - } - jchar -= remainingNumbers[tail]; - if (jchar < lowerEncodingLimit[tail]) { - // Should have been encoded in fewer octets - in.position(inIndex - in.arrayOffset()); - out.position(outIndex - out.arrayOffset()); - return CoderResult.malformedForLength(1); - } - inIndex += tail; - } - // Apache Tomcat added test - if (jchar >= 0xD800 && jchar <= 0xDFFF) { - return CoderResult.unmappableForLength(3); - } - // Apache Tomcat added test - if (jchar > 0x10FFFF) { - return CoderResult.unmappableForLength(4); - } - if (jchar <= 0xffff) { - cArr[outIndex++] = (char) jchar; - outRemaining--; - } else { - if (outRemaining < 2) { - return CoderResult.OVERFLOW; - } - cArr[outIndex++] = (char) ((jchar >> 0xA) + 0xD7C0); - cArr[outIndex++] = (char) ((jchar & 0x3FF) + 0xDC00); - outRemaining -= 2; - } - } - in.position(inIndex - in.arrayOffset()); - out.position(outIndex - out.arrayOffset()); - return (outRemaining == 0 && inIndex < inIndexLimit) ? CoderResult.OVERFLOW - : CoderResult.UNDERFLOW; - } -" -96,0," public static CipherText fromPortableSerializedBytes(byte[] bytes) - throws EncryptionException - { - CipherTextSerializer cts = new CipherTextSerializer(bytes); - return cts.asCipherText(); - } - - ///////////////////////// P U B L I C M E T H O D S //////////////////// - - /** - * Obtain the String representing the cipher transformation used to encrypt - * the plaintext. The cipher transformation represents the cipher algorithm, - * the cipher mode, and the padding scheme used to do the encryption. An - * example would be ""AES/CBC/PKCS5Padding"". See Appendix A in the - * - * Java Cryptography Architecture Reference Guide - * for information about standard supported cipher transformation names. - *

- * The cipher transformation name is usually sufficient to be passed to - * {@link javax.crypto.Cipher#getInstance(String)} to create a - * Cipher object to decrypt the ciphertext. - * - * @return The cipher transformation name used to encrypt the plaintext - * resulting in this ciphertext. - */ -" -97,0," protected void _verifyException(Throwable t, Class expExcType, - String... patterns) throws Exception - { - Class actExc = t.getClass(); - if (!expExcType.isAssignableFrom(actExc)) { - fail(""Expected Exception of type '""+expExcType.getName()+""', got '"" - +actExc.getName()+""', message: ""+t.getMessage()); - } - for (String pattern : patterns) { - verifyException(t, pattern); - } - } -" -98,0," public String getCompression() { - switch (compressionLevel) { - case 0: - return ""off""; - case 1: - return ""on""; - case 2: - return ""force""; - } - return ""off""; - } - - - /** - * Set compression level. - */ -" -99,0," public void close() throws IOException { - if (authFilter != null) { - authFilter.destroy(); - } - } -" -100,0," public void destroy() { - } - }; - -" -101,0," public O getOrBuild() { - if (isUnbuilt()) { - try { - return build(); - } - catch (Exception e) { - logger.debug(""Failed to perform build. Returning null"", e); - return null; - } - } - else { - return getObject(); - } - } - - /** - * Applies a {@link SecurityConfigurerAdapter} to this {@link SecurityBuilder} and - * invokes {@link SecurityConfigurerAdapter#setBuilder(SecurityBuilder)}. - * - * @param configurer - * @return - * @throws Exception - */ - @SuppressWarnings(""unchecked"") -" -102,0," private void testModified() - throws Exception - { - ECNamedCurveParameterSpec namedCurve = ECNamedCurveTable.getParameterSpec(""P-256""); - org.bouncycastle.jce.spec.ECPublicKeySpec pubSpec = new org.bouncycastle.jce.spec.ECPublicKeySpec(namedCurve.getCurve().createPoint(PubX, PubY), namedCurve); - KeyFactory kFact = KeyFactory.getInstance(""EC"", ""BC""); - PublicKey pubKey = kFact.generatePublic(pubSpec); - Signature sig = Signature.getInstance(""SHA256WithECDSA"", ""BC""); - - for (int i = 0; i != MODIFIED_SIGNATURES.length; i++) - { - sig.initVerify(pubKey); - - sig.update(Strings.toByteArray(""Hello"")); - - boolean failed; - - try - { - failed = !sig.verify(Hex.decode(MODIFIED_SIGNATURES[i])); - System.err.println(ASN1Dump.dumpAsString(ASN1Primitive.fromByteArray(Hex.decode(MODIFIED_SIGNATURES[i])))); - } - catch (SignatureException e) - { - failed = true; - } - - isTrue(""sig verified when shouldn't: "" + i, failed); - } - } - -" -103,0," protected void populateParams() { - super.populateParams(); - - UIBean uiBean = (UIBean) component; - uiBean.setCssClass(cssClass); - uiBean.setCssStyle(cssStyle); - uiBean.setCssErrorClass(cssErrorClass); - uiBean.setCssErrorStyle(cssErrorStyle); - uiBean.setTitle(title); - uiBean.setDisabled(disabled); - uiBean.setLabel(label); - uiBean.setLabelSeparator(labelSeparator); - uiBean.setLabelposition(labelposition); - uiBean.setRequiredPosition(requiredPosition); - uiBean.setErrorPosition(errorPosition); - uiBean.setName(name); - uiBean.setRequiredLabel(requiredLabel); - uiBean.setTabindex(tabindex); - uiBean.setValue(value); - uiBean.setTemplate(template); - uiBean.setTheme(theme); - uiBean.setTemplateDir(templateDir); - uiBean.setOnclick(onclick); - uiBean.setOndblclick(ondblclick); - uiBean.setOnmousedown(onmousedown); - uiBean.setOnmouseup(onmouseup); - uiBean.setOnmouseover(onmouseover); - uiBean.setOnmousemove(onmousemove); - uiBean.setOnmouseout(onmouseout); - uiBean.setOnfocus(onfocus); - uiBean.setOnblur(onblur); - uiBean.setOnkeypress(onkeypress); - uiBean.setOnkeydown(onkeydown); - uiBean.setOnkeyup(onkeyup); - uiBean.setOnselect(onselect); - uiBean.setOnchange(onchange); - uiBean.setTooltip(tooltip); - uiBean.setTooltipConfig(tooltipConfig); - uiBean.setJavascriptTooltip(javascriptTooltip); - uiBean.setTooltipCssClass(tooltipCssClass); - uiBean.setTooltipDelay(tooltipDelay); - uiBean.setTooltipIconPath(tooltipIconPath); - uiBean.setAccesskey(accesskey); - uiBean.setKey(key); - uiBean.setId(id); - - uiBean.setDynamicAttributes(dynamicAttributes); - } - -" -104,0," public long getTimestamp() { - return timestamp; - } - } -} -" -105,0," public boolean isUseRouteBuilder() { - return false; - } - - @Test -" -106,0," public ServerSocket createSocket (int port, int backlog, - InetAddress ifAddress) - throws IOException - { - if (!initialized) init(); - ServerSocket socket = sslProxy.createServerSocket(port, backlog, - ifAddress); - initServerSocket(socket); - return socket; - } - -" -107,0," public static void init() throws Exception { - - idpHttpsPort = System.getProperty(""idp.https.port""); - Assert.assertNotNull(""Property 'idp.https.port' null"", idpHttpsPort); - rpHttpsPort = System.getProperty(""rp.https.port""); - Assert.assertNotNull(""Property 'rp.https.port' null"", rpHttpsPort); - - idpServer = startServer(true, idpHttpsPort); - - WSSConfig.init(); - } - -" -108,0," public void testPrivateKeySerialisation() - throws Exception - { - String stream = ""AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAArO0ABXNyACJzdW4ucm1pLnNlcnZlci5BY3RpdmF0aW9uR3JvdXBJbXBsT+r9SAwuMqcCAARaAA1ncm91cEluYWN0aXZlTAAGYWN0aXZldAAVTGphdmEvdXRpbC9IYXNodGFibGU7TAAHZ3JvdXBJRHQAJ0xqYXZhL3JtaS9hY3RpdmF0aW9uL0FjdGl2YXRpb25Hcm91cElEO0wACWxvY2tlZElEc3QAEExqYXZhL3V0aWwvTGlzdDt4cgAjamF2YS5ybWkuYWN0aXZhdGlvbi5BY3RpdmF0aW9uR3JvdXCVLvKwBSnVVAIAA0oAC2luY2FybmF0aW9uTAAHZ3JvdXBJRHEAfgACTAAHbW9uaXRvcnQAJ0xqYXZhL3JtaS9hY3RpdmF0aW9uL0FjdGl2YXRpb25Nb25pdG9yO3hyACNqYXZhLnJtaS5zZXJ2ZXIuVW5pY2FzdFJlbW90ZU9iamVjdEUJEhX14n4xAgADSQAEcG9ydEwAA2NzZnQAKExqYXZhL3JtaS9zZXJ2ZXIvUk1JQ2xpZW50U29ja2V0RmFjdG9yeTtMAANzc2Z0AChMamF2YS9ybWkvc2VydmVyL1JNSVNlcnZlclNvY2tldEZhY3Rvcnk7eHIAHGphdmEucm1pLnNlcnZlci5SZW1vdGVTZXJ2ZXLHGQcSaPM5+wIAAHhyABxqYXZhLnJtaS5zZXJ2ZXIuUmVtb3RlT2JqZWN002G0kQxhMx4DAAB4cHcSABBVbmljYXN0U2VydmVyUmVmeAAAFbNwcAAAAAAAAAAAcHAAcHBw""; - - XMSSParameters params = new XMSSParameters(10, new SHA256Digest()); - - byte[] output = Base64.decode(new String(stream).getBytes(""UTF-8"")); - - - //Simple Exploit - - try - { - new XMSSPrivateKeyParameters.Builder(params).withPrivateKey(output, params).build(); - } - catch (IllegalArgumentException e) - { - assertTrue(e.getCause() instanceof IOException); - } - - //Same Exploit other method - - XMSS xmss2 = new XMSS(params, new SecureRandom()); - - xmss2.generateKeys(); - - byte[] publicKey = xmss2.exportPublicKey(); - - try - { - xmss2.importState(output, publicKey); - } - catch (IllegalArgumentException e) - { - assertTrue(e.getCause() instanceof IOException); - } - } - -" -109,0," public void setAllowJavaSerializedObject(boolean allowJavaSerializedObject) { - this.allowJavaSerializedObject = allowJavaSerializedObject; - } - -" -110,0," public Collection getRequiredPermissions(String regionName) { - return Collections.singletonList(new ResourcePermission(ResourcePermission.Resource.DATA, - ResourcePermission.Operation.READ, regionName)); - } - -" -111,0," abstract protected JDBCTableReader getTableReader(Connection connection, - String tableName, - EmbeddedDocumentUtil embeddedDocumentUtil); - -" -112,0," public FederationConfig getFederationConfig() { - return federationConfig; - } - -" -113,0," protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) - throws ServletException, IOException { - - String identityZoneId = request.getHeader(HEADER); - if (StringUtils.hasText(identityZoneId)) { - if (!isAuthorizedToSwitchToIdentityZone(identityZoneId)) { - response.sendError(HttpServletResponse.SC_FORBIDDEN, ""User is not authorized to switch to IdentityZone with id ""+identityZoneId); - return; - } - IdentityZone originalIdentityZone = IdentityZoneHolder.get(); - try { - - IdentityZone identityZone = null; - try { - identityZone = dao.retrieve(identityZoneId); - } catch (ZoneDoesNotExistsException ex) { - } catch (EmptyResultDataAccessException ex) { - } catch (Exception ex) { - throw ex; - } - if (identityZone == null) { - response.sendError(HttpServletResponse.SC_NOT_FOUND, ""Identity zone with id ""+identityZoneId+"" does not exist""); - return; - } - stripScopesFromAuthentication(identityZoneId, request); - IdentityZoneHolder.set(identityZone); - filterChain.doFilter(request, response); - } finally { - IdentityZoneHolder.set(originalIdentityZone); - } - } else { - filterChain.doFilter(request, response); - } - } -" -114,0," public BeanDefinition createMatcher(ParserContext pc, String path, String method) { - if ((""/**"".equals(path) || ""**"".equals(path)) && method == null) { - return new RootBeanDefinition(AnyRequestMatcher.class); - } - - BeanDefinitionBuilder matcherBldr = BeanDefinitionBuilder - .rootBeanDefinition(type); - - if (this == mvc) { - if (!pc.getRegistry().isBeanNameInUse(HANDLER_MAPPING_INTROSPECTOR_BEAN_NAME)) { - BeanDefinitionBuilder hmifb = BeanDefinitionBuilder - .rootBeanDefinition(HandlerMappingIntrospectorFactoryBean.class); - pc.getRegistry().registerBeanDefinition(HANDLER_MAPPING_INTROSPECTOR_FACTORY_BEAN_NAME, - hmifb.getBeanDefinition()); - - RootBeanDefinition hmi = new RootBeanDefinition(HANDLER_MAPPING_INTROSPECTOR_BEAN_NAME); - hmi.setFactoryBeanName(HANDLER_MAPPING_INTROSPECTOR_FACTORY_BEAN_NAME); - hmi.setFactoryMethodName(""createHandlerMappingIntrospector""); - pc.getRegistry().registerBeanDefinition(HANDLER_MAPPING_INTROSPECTOR_BEAN_NAME, hmi); - } - matcherBldr.addConstructorArgReference(HANDLER_MAPPING_INTROSPECTOR_BEAN_NAME); - } - - matcherBldr.addConstructorArgValue(path); - if (this == mvc) { - matcherBldr.addPropertyValue(""method"", method); - } - else { - matcherBldr.addConstructorArgValue(method); - } - - if (this == ciRegex) { - matcherBldr.addConstructorArgValue(true); - } - - return matcherBldr.getBeanDefinition(); - } - -" -115,0," protected Settings nodeSettings(int nodeOrdinal) { - return ImmutableSettings.builder() - // we really need local GW here since this also checks for corruption etc. - // and we need to make sure primaries are not just trashed if we don't have replicas - .put(super.nodeSettings(nodeOrdinal)).put(""gateway.type"", ""local"") - .put(TransportModule.TRANSPORT_SERVICE_TYPE_KEY, MockTransportService.class.getName()) - // speed up recoveries - .put(RecoverySettings.INDICES_RECOVERY_CONCURRENT_STREAMS, 10) - .put(RecoverySettings.INDICES_RECOVERY_CONCURRENT_SMALL_FILE_STREAMS, 10) - .put(ThrottlingAllocationDecider.CLUSTER_ROUTING_ALLOCATION_NODE_CONCURRENT_RECOVERIES, 5) - .build(); - } - - /** - * Tests that we can actually recover from a corruption on the primary given that we have replica shards around. - */ - @Test -" -116,0," private void writeFederationMetadata( - XMLStreamWriter writer, Idp config, Crypto crypto - ) throws XMLStreamException { - - writer.writeStartElement(""md"", ""RoleDescriptor"", WS_FEDERATION_NS); - writer.writeAttribute(SCHEMA_INSTANCE_NS, ""type"", ""fed:SecurityTokenServiceType""); - writer.writeAttribute(""protocolSupportEnumeration"", WS_FEDERATION_NS); - if (config.getServiceDescription() != null && config.getServiceDescription().length() > 0 ) { - writer.writeAttribute(""ServiceDescription"", config.getServiceDescription()); - } - if (config.getServiceDisplayName() != null && config.getServiceDisplayName().length() > 0 ) { - writer.writeAttribute(""ServiceDisplayName"", config.getServiceDisplayName()); - } - - //http://docs.oasis-open.org/security/saml/v2.0/saml-schema-metadata-2.0.xsd - //missing organization, contactperson - - //KeyDescriptor - writer.writeStartElement("""", ""KeyDescriptor"", SAML2_METADATA_NS); - writer.writeAttribute(""use"", ""signing""); - writer.writeStartElement("""", ""KeyInfo"", ""http://www.w3.org/2000/09/xmldsig#""); - writer.writeStartElement("""", ""X509Data"", ""http://www.w3.org/2000/09/xmldsig#""); - writer.writeStartElement("""", ""X509Certificate"", ""http://www.w3.org/2000/09/xmldsig#""); - - try { - String keyAlias = crypto.getDefaultX509Identifier(); - X509Certificate cert = CertsUtils.getX509Certificate(crypto, keyAlias); - writer.writeCharacters(Base64.encode(cert.getEncoded())); - } catch (Exception ex) { - LOG.error(""Failed to add certificate information to metadata. Metadata incomplete"", ex); - } - - writer.writeEndElement(); // X509Certificate - writer.writeEndElement(); // X509Data - writer.writeEndElement(); // KeyInfo - writer.writeEndElement(); // KeyDescriptor - - - // SecurityTokenServiceEndpoint - writer.writeStartElement(""fed"", ""SecurityTokenServiceEndpoint"", WS_FEDERATION_NS); - writer.writeStartElement(""wsa"", ""EndpointReference"", WS_ADDRESSING_NS); - - writer.writeStartElement(""wsa"", ""Address"", WS_ADDRESSING_NS); - writer.writeCharacters(config.getStsUrl().toString()); - - writer.writeEndElement(); // Address - writer.writeEndElement(); // EndpointReference - writer.writeEndElement(); // SecurityTokenServiceEndpoint - - - // PassiveRequestorEndpoint - writer.writeStartElement(""fed"", ""PassiveRequestorEndpoint"", WS_FEDERATION_NS); - writer.writeStartElement(""wsa"", ""EndpointReference"", WS_ADDRESSING_NS); - - writer.writeStartElement(""wsa"", ""Address"", WS_ADDRESSING_NS); - writer.writeCharacters(config.getIdpUrl().toString()); - - writer.writeEndElement(); // Address - writer.writeEndElement(); // EndpointReference - writer.writeEndElement(); // PassiveRequestorEndpoint - - - // create ClaimsType section - if (config.getClaimTypesOffered() != null && config.getClaimTypesOffered().size() > 0) { - writer.writeStartElement(""fed"", ""ClaimTypesOffered"", WS_FEDERATION_NS); - for (Claim claim : config.getClaimTypesOffered()) { - - writer.writeStartElement(""auth"", ""ClaimType"", WS_FEDERATION_NS); - writer.writeAttribute(""Uri"", claim.getClaimType().toString()); - writer.writeAttribute(""Optional"", ""true""); - writer.writeEndElement(); // ClaimType - - } - writer.writeEndElement(); // ClaimTypesOffered - } - - writer.writeEndElement(); // RoleDescriptor - } - - -" -117,0," public Set getSupportedTypes(ParseContext context) { - return null; - } - - @Override -" -118,0," public Container getContainer() { - - return (container); - - } - - - /** - * Set the Container with which this Realm has been associated. - * - * @param container The associated Container - */ -" -119,0," public Set getSupportedTypes(ParseContext context) { - return null; - } - - @Override -" -120,0," public void testSendEntityMessage() throws Exception { - - MockEndpoint endpoint = getMockEndpoint(""mock:result""); - endpoint.expectedMessageCount(1); - //String message = ""]>&xxe;""; - - String message = """"; - template.sendBody(""direct:start2"", message); - - assertMockEndpointsSatisfied(); - - List list = endpoint.getReceivedExchanges(); - Exchange exchange = list.get(0); - String xml = exchange.getIn().getBody(String.class); - - System.out.println(xml); - } - -" -121,0," public void execute(FunctionContext context) { - RegionFunctionContext rfc = (RegionFunctionContext) context; - context.getResultSender().lastResult(rfc.getDataSet().size()); - } - - @Override -" -122,0," public DescriptorImpl getDescriptor() { - return Hudson.getInstance().getDescriptorByType(DescriptorImpl.class); - } - - /** - * Returns the Missed Events playback manager. - * @return GerritMissedEventsPlaybackManager - */ -" -123,0," public void setAllowJavaSerializedObject(boolean allowJavaSerializedObject) { - this.allowJavaSerializedObject = allowJavaSerializedObject; - } - -" -124,0," public int doRead(ByteChunk chunk, Request req) throws IOException { - checkError(); - - if (endChunk) { - return -1; - } - - if(needCRLFParse) { - needCRLFParse = false; - parseCRLF(false); - } - - if (remaining <= 0) { - if (!parseChunkHeader()) { - throwIOException(sm.getString(""chunkedInputFilter.invalidHeader"")); - } - if (endChunk) { - parseEndChunk(); - return -1; - } - } - - int result = 0; - - if (pos >= lastValid) { - if (readBytes() < 0) { - throwIOException(sm.getString(""chunkedInputFilter.eos"")); - } - } - - if (remaining > (lastValid - pos)) { - result = lastValid - pos; - remaining = remaining - result; - chunk.setBytes(buf, pos, result); - pos = lastValid; - } else { - result = remaining; - chunk.setBytes(buf, pos, remaining); - pos = pos + remaining; - remaining = 0; - //we need a CRLF - if ((pos+1) >= lastValid) { - //if we call parseCRLF we overrun the buffer here - //so we defer it to the next call BZ 11117 - needCRLFParse = true; - } else { - parseCRLF(false); //parse the CRLF immediately - } - } - - return result; - } - - - // ---------------------------------------------------- InputFilter Methods - - /** - * Read the content length from the request. - */ - @Override -" -125,0," public byte getValue() { return value; } -" -126,0," public final Permission getRequiredPermission() { - return Jenkins.ADMINISTER; - } - - /** - * Starts the server's project list updater, send command queue and event manager. - * - */ -" -127,0," public Object compile(String expression, Map context) throws OgnlException { - Object tree; - if (enableExpressionCache) { - tree = expressions.get(expression); - if (tree == null) { - tree = Ognl.parseExpression(expression); - expressions.putIfAbsent(expression, tree); - } - } else { - tree = Ognl.parseExpression(expression); - } - - if (!enableEvalExpression && isEvalExpression(tree, context)) { - throw new OgnlException(""Eval expressions has been disabled""); - } - - return tree; - } - - /** - * Copies the properties in the object ""from"" and sets them in the object ""to"" - * using specified type converter, or {@link com.opensymphony.xwork2.conversion.impl.XWorkConverter} if none - * is specified. - * - * @param from the source object - * @param to the target object - * @param context the action context we're running under - * @param exclusions collection of method names to excluded from copying ( can be null) - * @param inclusions collection of method names to included copying (can be null) - * note if exclusions AND inclusions are supplied and not null nothing will get copied. - */ -" -128,0," public SolrInputDocument readDoc(XMLStreamReader parser) throws XMLStreamException { - SolrInputDocument doc = new SolrInputDocument(); - - String attrName = """"; - for (int i = 0; i < parser.getAttributeCount(); i++) { - attrName = parser.getAttributeLocalName(i); - if (""boost"".equals(attrName)) { - doc.setDocumentBoost(Float.parseFloat(parser.getAttributeValue(i))); - } else { - log.warn(""Unknown attribute doc/@"" + attrName); - } - } - - StringBuilder text = new StringBuilder(); - String name = null; - float boost = 1.0f; - boolean isNull = false; - String update = null; - - while (true) { - int event = parser.next(); - switch (event) { - // Add everything to the text - case XMLStreamConstants.SPACE: - case XMLStreamConstants.CDATA: - case XMLStreamConstants.CHARACTERS: - text.append(parser.getText()); - break; - - case XMLStreamConstants.END_ELEMENT: - if (""doc"".equals(parser.getLocalName())) { - return doc; - } else if (""field"".equals(parser.getLocalName())) { - Object v = isNull ? null : text.toString(); - if (update != null) { - Map extendedValue = new HashMap(1); - extendedValue.put(update, v); - v = extendedValue; - } - doc.addField(name, v, boost); - boost = 1.0f; - } - break; - - case XMLStreamConstants.START_ELEMENT: - text.setLength(0); - String localName = parser.getLocalName(); - if (!""field"".equals(localName)) { - log.warn(""unexpected XML tag doc/"" + localName); - throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, - ""unexpected XML tag doc/"" + localName); - } - boost = 1.0f; - update = null; - String attrVal = """"; - for (int i = 0; i < parser.getAttributeCount(); i++) { - attrName = parser.getAttributeLocalName(i); - attrVal = parser.getAttributeValue(i); - if (""name"".equals(attrName)) { - name = attrVal; - } else if (""boost"".equals(attrName)) { - boost = Float.parseFloat(attrVal); - } else if (""null"".equals(attrName)) { - isNull = StrUtils.parseBoolean(attrVal); - } else if (""update"".equals(attrName)) { - update = attrVal; - } else { - log.warn(""Unknown attribute doc/field/@"" + attrName); - } - } - break; - } - } - } -" -129,0," private AsymmetricCipherKeyPair genKeyPair() - { - if (!initialized) - { - initializeDefault(); - } - - // initialize authenticationPaths and treehash instances - byte[][][] currentAuthPaths = new byte[numLayer][][]; - byte[][][] nextAuthPaths = new byte[numLayer - 1][][]; - Treehash[][] currentTreehash = new Treehash[numLayer][]; - Treehash[][] nextTreehash = new Treehash[numLayer - 1][]; - - Vector[] currentStack = new Vector[numLayer]; - Vector[] nextStack = new Vector[numLayer - 1]; - - Vector[][] currentRetain = new Vector[numLayer][]; - Vector[][] nextRetain = new Vector[numLayer - 1][]; - - for (int i = 0; i < numLayer; i++) - { - currentAuthPaths[i] = new byte[heightOfTrees[i]][mdLength]; - currentTreehash[i] = new Treehash[heightOfTrees[i] - K[i]]; - - if (i > 0) - { - nextAuthPaths[i - 1] = new byte[heightOfTrees[i]][mdLength]; - nextTreehash[i - 1] = new Treehash[heightOfTrees[i] - K[i]]; - } - - currentStack[i] = new Vector(); - if (i > 0) - { - nextStack[i - 1] = new Vector(); - } - } - - // initialize roots - byte[][] currentRoots = new byte[numLayer][mdLength]; - byte[][] nextRoots = new byte[numLayer - 1][mdLength]; - // initialize seeds - byte[][] seeds = new byte[numLayer][mdLength]; - // initialize seeds[] by copying starting-seeds of first trees of each - // layer - for (int i = 0; i < numLayer; i++) - { - System.arraycopy(currentSeeds[i], 0, seeds[i], 0, mdLength); - } - - // initialize rootSigs - currentRootSigs = new byte[numLayer - 1][mdLength]; - - // ------------------------- - // ------------------------- - // --- calculation of current authpaths and current rootsigs (AUTHPATHS, - // SIG)------ - // from bottom up to the root - for (int h = numLayer - 1; h >= 0; h--) - { - GMSSRootCalc tree; - - // on lowest layer no lower root is available, so just call - // the method with null as first parameter - if (h == numLayer - 1) - { - tree = this.generateCurrentAuthpathAndRoot(null, currentStack[h], seeds[h], h); - } - else - // otherwise call the method with the former computed root - // value - { - tree = this.generateCurrentAuthpathAndRoot(currentRoots[h + 1], currentStack[h], seeds[h], h); - } - - // set initial values needed for the private key construction - for (int i = 0; i < heightOfTrees[h]; i++) - { - System.arraycopy(tree.getAuthPath()[i], 0, currentAuthPaths[h][i], 0, mdLength); - } - currentRetain[h] = tree.getRetain(); - currentTreehash[h] = tree.getTreehash(); - System.arraycopy(tree.getRoot(), 0, currentRoots[h], 0, mdLength); - } - - // --- calculation of next authpaths and next roots (AUTHPATHS+, ROOTS+) - // ------ - for (int h = numLayer - 2; h >= 0; h--) - { - GMSSRootCalc tree = this.generateNextAuthpathAndRoot(nextStack[h], seeds[h + 1], h + 1); - - // set initial values needed for the private key construction - for (int i = 0; i < heightOfTrees[h + 1]; i++) - { - System.arraycopy(tree.getAuthPath()[i], 0, nextAuthPaths[h][i], 0, mdLength); - } - nextRetain[h] = tree.getRetain(); - nextTreehash[h] = tree.getTreehash(); - System.arraycopy(tree.getRoot(), 0, nextRoots[h], 0, mdLength); - - // create seed for the Merkle tree after next (nextNextSeeds) - // SEEDs++ - System.arraycopy(seeds[h + 1], 0, this.nextNextSeeds[h], 0, mdLength); - } - // ------------ - - // generate JDKGMSSPublicKey - GMSSPublicKeyParameters publicKey = new GMSSPublicKeyParameters(currentRoots[0], gmssPS); - - // generate the JDKGMSSPrivateKey - GMSSPrivateKeyParameters privateKey = new GMSSPrivateKeyParameters(currentSeeds, nextNextSeeds, currentAuthPaths, - nextAuthPaths, currentTreehash, nextTreehash, currentStack, nextStack, currentRetain, nextRetain, nextRoots, currentRootSigs, gmssPS, digestProvider); - - // return the KeyPair - return (new AsymmetricCipherKeyPair(publicKey, privateKey)); - } - - /** - * calculates the authpath for tree in layer h which starts with seed[h] - * additionally computes the rootSignature of underlaying root - * - * @param currentStack stack used for the treehash instance created by this method - * @param lowerRoot stores the root of the lower tree - * @param seed starting seeds - * @param h actual layer - */ -" -130,0," public static void redirectToSavedRequest(ServletRequest request, ServletResponse response, String fallbackUrl) - throws IOException { - String successUrl = null; - boolean contextRelative = true; - SavedRequest savedRequest = WebUtils.getAndClearSavedRequest(request); - if (savedRequest != null && savedRequest.getMethod().equalsIgnoreCase(AccessControlFilter.GET_METHOD)) { - successUrl = savedRequest.getRequestUrl(); - contextRelative = false; - } - - if (successUrl == null) { - successUrl = fallbackUrl; - } - - if (successUrl == null) { - throw new IllegalStateException(""Success URL not available via saved request or via the "" + - ""successUrlFallback method parameter. One of these must be non-null for "" + - ""issueSuccessRedirect() to work.""); - } - - WebUtils.issueRedirect(request, response, successUrl, null, contextRelative); - } - -" -131,0," private void doTestRewrite(String config, String request, String expectedURI) throws Exception { - Tomcat tomcat = getTomcatInstance(); - - // No file system docBase required - Context ctx = tomcat.addContext("""", null); - - RewriteValve rewriteValve = new RewriteValve(); - ctx.getPipeline().addValve(rewriteValve); - - rewriteValve.setConfiguration(config); - - // Note: URLPatterns should be URL encoded - // (http://svn.apache.org/r285186) - Tomcat.addServlet(ctx, ""snoop"", new SnoopServlet()); - ctx.addServletMapping(""/a/%255A"", ""snoop""); - ctx.addServletMapping(""/c/*"", ""snoop""); - Tomcat.addServlet(ctx, ""default"", new DefaultServlet()); - ctx.addServletMapping(""/"", ""default""); - - tomcat.start(); - - ByteChunk res = getUrl(""http://localhost:"" + getPort() + request); - - String body = res.toString(); - RequestDescriptor requestDesc = SnoopResult.parse(body); - String requestURI = requestDesc.getRequestInfo(""REQUEST-URI""); - Assert.assertEquals(expectedURI, requestURI); - } -" -132,0," protected void setLocation(String location) { - this.location = location; - } - -" -133,0," protected String adjustFilterForJoin(String filter) { - if (StringUtils.hasText(filter)) { - filter = filter.replace(""displayName"", ""g.displayName""); - filter = filter.replace(""externalGroup"", ""gm.external_group""); - filter = filter.replace(""groupId"", ""g.id""); - filter = filter.replace(""origin"", ""gm.origin""); - } - return filter; - } - - @Override -" -134,0," private static void disableFeature(DocumentBuilderFactory dbfactory, String feature) { - try { - dbfactory.setFeature(feature, true); - } catch (ParserConfigurationException e) { - // This should catch a failed setFeature feature - log.info(""ParserConfigurationException was thrown. The feature '"" + - feature + ""' is probably not supported by your XML processor.""); - } - } -" -135,0," private static LinkedHashMap> processMap( - LinkedHashMap> requestMap, - ExpressionParser parser) { - Assert.notNull(parser, ""SecurityExpressionHandler returned a null parser object""); - - LinkedHashMap> requestToExpressionAttributesMap = new LinkedHashMap>( - requestMap); - - for (Map.Entry> entry : requestMap - .entrySet()) { - RequestMatcher request = entry.getKey(); - Assert.isTrue(entry.getValue().size() == 1, - ""Expected a single expression attribute for "" + request); - ArrayList attributes = new ArrayList(1); - String expression = entry.getValue().toArray(new ConfigAttribute[1])[0] - .getAttribute(); - logger.debug(""Adding web access control expression '"" + expression + ""', for "" - + request); - - AbstractVariableEvaluationContextPostProcessor postProcessor = createPostProcessor( - request); - try { - attributes.add(new WebExpressionConfigAttribute( - parser.parseExpression(expression), postProcessor)); - } - catch (ParseException e) { - throw new IllegalArgumentException( - ""Failed to parse expression '"" + expression + ""'""); - } - - requestToExpressionAttributesMap.put(request, attributes); - } - - return requestToExpressionAttributesMap; - } - -" -136,0," public T create() { - final ByteArrayOutputStream baos = new ByteArrayOutputStream(512); - ByteArrayInputStream bais = null; - try { - final ObjectOutputStream out = new ObjectOutputStream(baos); - out.writeObject(iPrototype); - - bais = new ByteArrayInputStream(baos.toByteArray()); - final ObjectInputStream in = new ObjectInputStream(bais); - return (T) in.readObject(); - - } catch (final ClassNotFoundException ex) { - throw new FunctorException(ex); - } catch (final IOException ex) { - throw new FunctorException(ex); - } finally { - try { - if (bais != null) { - bais.close(); - } - } catch (final IOException ex) { - // ignore - } - try { - baos.close(); - } catch (final IOException ex) { - // ignore - } - } - } - } - -} -" -137,0," private File getFile(String fn) throws IOException { - File tmp = null; - - String path = System.getProperty(""java.io.tmpdir"") + TMP; - File dir = new File(path); - if (!dir.exists()) { - LOGGER.fine(""Creating directory. Path: "" + dir.getCanonicalPath()); - Files.createDirectories(dir.toPath()); - } - tmp = new File(dir, fn); - LOGGER.fine(""Temp file: "" + tmp.getCanonicalPath()); - - return tmp; - } -" -138,0," private Object readResolve() { - throw new UnsupportedOperationException(); - } - - /* Traverseproc implementation */ - @Override -" -139,0," public Document getMetaData(Idp config, TrustedIdp serviceConfig) throws ProcessingException { - - try { - Crypto crypto = CertsUtils.createCrypto(config.getCertificate()); - - W3CDOMStreamWriter writer = new W3CDOMStreamWriter(); - - writer.writeStartDocument(""UTF-8"", ""1.0""); - - String referenceID = IDGenerator.generateID(""_""); - writer.writeStartElement(""md"", ""EntityDescriptor"", SAML2_METADATA_NS); - writer.writeAttribute(""ID"", referenceID); - - String serviceURL = config.getIdpUrl().toString(); - 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 (""http://docs.oasis-open.org/wsfed/federation/200706"".equals(serviceConfig.getProtocol())) { - writeFederationMetadata(writer, serviceConfig, serviceURL); - } else if (""urn:oasis:names:tc:SAML:2.0:profiles:SSO:browser"".equals(serviceConfig.getProtocol())) { - writeSAMLMetadata(writer, serviceConfig, serviceURL, crypto); - } - - writer.writeEndElement(); // EntityDescriptor - - writer.writeEndDocument(); - - writer.close(); - - if (LOG.isDebugEnabled()) { - String out = DOM2Writer.nodeToString(writer.getDocument()); - LOG.debug(""***************** unsigned ****************""); - LOG.debug(out); - LOG.debug(""***************** unsigned ****************""); - } - - Document result = SignatureUtils.signMetaInfo(crypto, null, config.getCertificatePassword(), - writer.getDocument(), referenceID); - if (result != null) { - return result; - } else { - throw new RuntimeException(""Failed to sign the metadata document: result=null""); - } - } 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()); - } - - } - -" -140,0," protected BlobStore blobStore() { - return blobStore; - } - - /** - * {@inheritDoc} - */ - @Override -" -141,0," public void recycle(boolean socketClosing) { - super.recycle(socketClosing); - - inputBuffer.clear(); - inputBuffer.limit(0); - outputBuffer.clear(); - - } -" -142,0," public void winzipBackSlashWorkaround() throws Exception { - ZipArchiveInputStream in = null; - try { - in = new ZipArchiveInputStream(new FileInputStream(getFile(""test-winzip.zip""))); - ZipArchiveEntry zae = in.getNextZipEntry(); - zae = in.getNextZipEntry(); - zae = in.getNextZipEntry(); - assertEquals(""\u00e4/"", zae.getName()); - } finally { - if (in != null) { - in.close(); - } - } - } - - /** - * @see ""https://issues.apache.org/jira/browse/COMPRESS-189"" - */ - @Test -" -143,0," public long getAvailable() { - - return (this.available); - - } - - - /** - * Set the available date/time for this servlet, in milliseconds since the - * epoch. If this date/time is Long.MAX_VALUE, it is considered to mean - * that unavailability is permanent and any request for this servlet will return - * an SC_NOT_FOUND error. If this date/time is in the future, any request for - * this servlet will return an SC_SERVICE_UNAVAILABLE error. - * - * @param available The new available date/time - */ - @Override -" -144,0," public String toString() - { - return name; - } - } - -} -" -145,0," public T transform(final Class input) { - try { - if (input == null) { - throw new FunctorException( - ""InstantiateTransformer: Input object was not an instanceof Class, it was a null object""); - } - final Constructor con = input.getConstructor(iParamTypes); - return con.newInstance(iArgs); - } catch (final NoSuchMethodException ex) { - throw new FunctorException(""InstantiateTransformer: The constructor must exist and be public ""); - } catch (final InstantiationException ex) { - throw new FunctorException(""InstantiateTransformer: InstantiationException"", ex); - } catch (final IllegalAccessException ex) { - throw new FunctorException(""InstantiateTransformer: Constructor must be public"", ex); - } catch (final InvocationTargetException ex) { - throw new FunctorException(""InstantiateTransformer: Constructor threw an exception"", ex); - } - } - -" -146,0," public String getTreeDigest() - { - return DigestUtil.getXMSSDigestName(treeDigest); - } -" -147,0," public void run() { - try { - LOGGER.info(""Initiating a re-keying of secrets. See ""+getLogFile()); - StreamTaskListener listener = new StreamTaskListener(getLogFile()); - try { - PrintStream log = listener.getLogger(); - log.println(""Started re-keying "" + new Date()); - int count = rewriter.rewriteRecursive(Jenkins.getInstance().getRootDir(), listener); - log.printf(""Completed re-keying %d files on %s\n"",count,new Date()); - new RekeySecretAdminMonitor().done.on(); - LOGGER.info(""Secret re-keying completed""); - } catch (Exception e) { - LOGGER.log(Level.SEVERE, ""Fatal failure in re-keying secrets"",e); - e.printStackTrace(listener.error(""Fatal failure in rewriting secrets"")); - } - } catch (IOException e) { - LOGGER.log(Level.SEVERE, ""Catastrophic failure to rewrite secrets"",e); - } - } - } - - private static final Logger LOGGER = Logger.getLogger(RekeySecretAdminMonitor.class.getName()); - -} -" -148,0," protected BlobPath basePath() { - return basePath; - } -" -149,0," public ServerSocket createServerSocket(int port) throws IOException { - SSLServerSocket sslServerSocket = - (SSLServerSocket) sslServerSocketFactory.createServerSocket(port, 0, bindAddress); - if (getEnabledCipherSuites() != null) { - sslServerSocket.setEnabledCipherSuites(getEnabledCipherSuites()); - } - if (getEnabledProtocols() == null) { - sslServerSocket.setEnabledProtocols(defaultProtocols); - } else { - sslServerSocket.setEnabledProtocols(getEnabledProtocols()); - } - sslServerSocket.setNeedClientAuth(getNeedClientAuth()); - return sslServerSocket; - } - } -} -" -150,0," protected boolean statusDropsConnection(int status) { - return status == 400 /* SC_BAD_REQUEST */ || - status == 408 /* SC_REQUEST_TIMEOUT */ || - status == 411 /* SC_LENGTH_REQUIRED */ || - status == 413 /* SC_REQUEST_ENTITY_TOO_LARGE */ || - status == 414 /* SC_REQUEST_URI_TOO_LARGE */ || - status == 500 /* SC_INTERNAL_SERVER_ERROR */ || - status == 503 /* SC_SERVICE_UNAVAILABLE */ || - status == 501 /* SC_NOT_IMPLEMENTED */; - } - -" -151,0," public void setExpressionParser(ExpressionParser expressionParser) { - this.expressionParser = expressionParser; - } - - /** - * Sets the service to use to expose formatters for field values. - * @param conversionService the conversion service - */ -" -152,0," void setAllowJavaSerializedObject(boolean allowJavaSerializedObject); - - /** - * Gets the header filter strategy - * - * @return the strategy - */ -" -153,0," protected String savedRequestURL(Session session) { - - SavedRequest saved = - (SavedRequest) session.getNote(Constants.FORM_REQUEST_NOTE); - if (saved == null) { - return (null); - } - StringBuilder sb = new StringBuilder(saved.getRequestURI()); - if (saved.getQueryString() != null) { - sb.append('?'); - sb.append(saved.getQueryString()); - } - return (sb.toString()); - - } - - -" -154,0," public static String getAttributeValueEmptyNull(Element e, String attributeName) { - Attr node = e.getAttributeNode(attributeName); - if (node == null) { - return null; - } - return node.getValue(); - } - - /** - * Get the trimmed text content of a node or null if there is no text - */ -" -155,0," private boolean evaluate(String text) { - try { - InputSource inputSource = new InputSource(new StringReader(text)); - Document inputDocument = builder.parse(inputSource); - return ((Boolean) xpath.evaluate(xpathExpression, inputDocument, XPathConstants.BOOLEAN)).booleanValue(); - } catch (Exception e) { - return false; - } - } - - @Override -" -156,0," public void destroy() { - // NO-OP - } - -" -157,0," public void initialize( - AlgorithmParameterSpec params, - SecureRandom random) - throws InvalidAlgorithmParameterException - { - if (!(params instanceof DSAParameterSpec)) - { - throw new InvalidAlgorithmParameterException(""parameter object not a DSAParameterSpec""); - } - DSAParameterSpec dsaParams = (DSAParameterSpec)params; - - param = new DSAKeyGenerationParameters(random, new DSAParameters(dsaParams.getP(), dsaParams.getQ(), dsaParams.getG())); - - engine.init(param); - initialised = true; - } - -" -158,0," public static String nodeMode() { - Builder builder = ImmutableSettings.builder(); - if (Strings.isEmpty(System.getProperty(""es.node.mode"")) && Strings.isEmpty(System.getProperty(""es.node.local""))) { - return ""local""; // default if nothing is specified - } - if (Strings.hasLength(System.getProperty(""es.node.mode""))) { - builder.put(""node.mode"", System.getProperty(""es.node.mode"")); - } - if (Strings.hasLength(System.getProperty(""es.node.local""))) { - builder.put(""node.local"", System.getProperty(""es.node.local"")); - } - if (DiscoveryNode.localNode(builder.build())) { - return ""local""; - } else { - return ""network""; - } - } - - @Override -" -159,0," public AsymmetricCipherKeyPair generateKeyPair() - { - return genKeyPair(); - } -" -160,0," public synchronized void save() throws IOException { - super.save(); - updateTransientActions(); - } - - @Override -" -161,0," public static ASN1Integer getInstance( - ASN1TaggedObject obj, - boolean explicit) - { - ASN1Primitive o = obj.getObject(); - - if (explicit || o instanceof ASN1Integer) - { - return getInstance(o); - } - else - { - return new ASN1Integer(ASN1OctetString.getInstance(obj.getObject()).getOctets()); - } - } - -" -162,0," public void testNoRewrite() throws Exception { - doTestRewrite("""", ""/a/%255A"", ""/a/%255A""); - } - - @Test -" -163,0," public void execute(String key, ActionMapping mapping) { - String name = key.substring(ACTION_PREFIX.length()); - if (allowDynamicMethodCalls) { - int bang = name.indexOf('!'); - if (bang != -1) { - String method = name.substring(bang + 1); - mapping.setMethod(method); - name = name.substring(0, bang); - } - } - mapping.setName(cleanupActionName(name)); - } - }); - - } - }; - } - - /** - * Adds a parameter action. Should only be called during initialization - * - * @param prefix The string prefix to trigger the action - * @param parameterAction The parameter action to execute - * @since 2.1.0 - */ -" -164,0," public Collection getRequiredPermissions(String regionName) { - return Collections.singletonList(new ResourcePermission(ResourcePermission.Resource.DATA, - ResourcePermission.Operation.READ, regionName)); - } - -" -165,0," public T create() { - // needed for post-serialization - if (iConstructor == null) { - findConstructor(); - } - - try { - return iConstructor.newInstance(iArgs); - } catch (final InstantiationException ex) { - throw new FunctorException(""InstantiateFactory: InstantiationException"", ex); - } catch (final IllegalAccessException ex) { - throw new FunctorException(""InstantiateFactory: Constructor must be public"", ex); - } catch (final InvocationTargetException ex) { - throw new FunctorException(""InstantiateFactory: Constructor threw an exception"", ex); - } - } - -" -166,0," public void parseEmbedded( - InputStream stream, ContentHandler handler, Metadata metadata, boolean outputHtml) - throws SAXException, IOException { - if(outputHtml) { - AttributesImpl attributes = new AttributesImpl(); - attributes.addAttribute("""", ""class"", ""class"", ""CDATA"", ""package-entry""); - handler.startElement(XHTML, ""div"", ""div"", attributes); - } - - String name = metadata.get(Metadata.RESOURCE_NAME_KEY); - if (name != null && name.length() > 0 && outputHtml) { - handler.startElement(XHTML, ""h1"", ""h1"", new AttributesImpl()); - char[] chars = name.toCharArray(); - handler.characters(chars, 0, chars.length); - handler.endElement(XHTML, ""h1"", ""h1""); - } - - // Use the delegate parser to parse this entry - try (TemporaryResources tmp = new TemporaryResources()) { - final TikaInputStream newStream = TikaInputStream.get(new CloseShieldInputStream(stream), tmp); - if (stream instanceof TikaInputStream) { - final Object container = ((TikaInputStream) stream).getOpenContainer(); - if (container != null) { - newStream.setOpenContainer(container); - } - } - DELEGATING_PARSER.parse( - newStream, - new EmbeddedContentHandler(new BodyContentHandler(handler)), - metadata, context); - } catch (EncryptedDocumentException ede) { - // TODO: can we log a warning that we lack the password? - // For now, just skip the content - } catch (CorruptedFileException e) { - throw new IOExceptionWithCause(e); - } catch (TikaException e) { - // TODO: can we log a warning somehow? - // Could not parse the entry, just skip the content - } - - if(outputHtml) { - handler.endElement(XHTML, ""div"", ""div""); - } - } - -" -167,0," private void checkParams() - { - if (vi == null) - { - throw new IllegalArgumentException(""no layers defined.""); - } - if (vi.length > 1) - { - for (int i = 0; i < vi.length - 1; i++) - { - if (vi[i] >= vi[i + 1]) - { - throw new IllegalArgumentException( - ""v[i] has to be smaller than v[i+1]""); - } - } - } - else - { - throw new IllegalArgumentException( - ""Rainbow needs at least 1 layer, such that v1 < v2.""); - } - } - - /** - * Getter for the number of layers - * - * @return the number of layers - */ -" -168,0," public void markPaused() { - paused = true; - } - } - - // ---------------------------------------------------- Wrapper Inner Class - - - protected static class MappedWrapper extends MapElement { - - public final boolean jspWildCard; - public final boolean resourceOnly; - - public MappedWrapper(String name, Wrapper wrapper, boolean jspWildCard, - boolean resourceOnly) { - super(name, wrapper); - this.jspWildCard = jspWildCard; - this.resourceOnly = resourceOnly; - } - } -} -" -169,0," public String getUsername() { - return username; - } - -" -170,0," public boolean isMapHeaders() { - return mapHeaders; - } - - /** - * If this option is enabled, then during binding from Spark to Camel Message then the headers will be mapped as well - * (eg added as header to the Camel Message as well). You can turn off this option to disable this. - * The headers can still be accessed from the org.apache.camel.component.sparkrest.SparkMessage message with the - * method getRequest() that returns the Spark HTTP request instance. - */ -" -171,0," public int[] getVi() - { - return this.vi; - } -" -172,0," public void setUp() throws Exception { - int randomInt = new SecureRandom().nextInt(); - - String adminAccessToken = testClient.getOAuthAccessToken(""admin"", ""adminsecret"", ""client_credentials"", ""clients.read clients.write clients.secret""); - - String scimClientId = ""scim"" + randomInt; - testClient.createScimClient(adminAccessToken, scimClientId); - - String scimAccessToken = testClient.getOAuthAccessToken(scimClientId, ""scimsecret"", ""client_credentials"", ""scim.read scim.write password.write""); - - userEmail = ""user"" + randomInt + ""@example.com""; - testClient.createUser(scimAccessToken, userEmail, userEmail, PASSWORD, true); - } - - @Test -" -173,0," public final void invoke(Request request, Response response) - throws IOException, ServletException { - - // Select the Context to be used for this Request - Context context = request.getContext(); - if (context == null) { - response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, - sm.getString(""standardHost.noContext"")); - return; - } - - if (request.isAsyncSupported()) { - request.setAsyncSupported(context.getPipeline().isAsyncSupported()); - } - - boolean asyncAtStart = request.isAsync(); - boolean asyncDispatching = request.isAsyncDispatching(); - - try { - context.bind(Globals.IS_SECURITY_ENABLED, MY_CLASSLOADER); - - if (!asyncAtStart && !context.fireRequestInitEvent(request.getRequest())) { - // Don't fire listeners during async processing (the listener - // fired for the request that called startAsync()). - // If a request init listener throws an exception, the request - // is aborted. - return; - } - - // Ask this Context to process this request. Requests that are in - // async mode and are not being dispatched to this resource must be - // in error and have been routed here to check for application - // defined error pages. - try { - if (!asyncAtStart || asyncDispatching) { - context.getPipeline().getFirst().invoke(request, response); - } else { - // Make sure this request/response is here because an error - // report is required. - if (!response.isErrorReportRequired()) { - throw new IllegalStateException(sm.getString(""standardHost.asyncStateError"")); - } - } - } catch (Throwable t) { - ExceptionUtils.handleThrowable(t); - container.getLogger().error(""Exception Processing "" + request.getRequestURI(), t); - // If a new error occurred while trying to report a previous - // error allow the original error to be reported. - if (!response.isErrorReportRequired()) { - request.setAttribute(RequestDispatcher.ERROR_EXCEPTION, t); - throwable(request, response, t); - } - } - - // Now that the request/response pair is back under container - // control lift the suspension so that the error handling can - // complete and/or the container can flush any remaining data - response.setSuspended(false); - - Throwable t = (Throwable) request.getAttribute(RequestDispatcher.ERROR_EXCEPTION); - - // Protect against NPEs if the context was destroyed during a - // long running request. - if (!context.getState().isAvailable()) { - return; - } - - // Look for (and render if found) an application level error page - if (response.isErrorReportRequired()) { - if (t != null) { - throwable(request, response, t); - } else { - status(request, response); - } - } - - if (!request.isAsync() && !asyncAtStart) { - context.fireRequestDestroyEvent(request.getRequest()); - } - } finally { - // Access a session (if present) to update last accessed time, based - // on a strict interpretation of the specification - if (ACCESS_SESSION) { - request.getSession(false); - } - - context.unbind(Globals.IS_SECURITY_ENABLED, MY_CLASSLOADER); - } - } - - - // -------------------------------------------------------- Private Methods - - /** - * Handle the HTTP status code (and corresponding message) generated - * while processing the specified Request to produce the specified - * Response. Any exceptions that occur during generation of the error - * report are logged and swallowed. - * - * @param request The request being processed - * @param response The response being generated - */ -" -174,0," private T run(PrivilegedExceptionAction action) throws Exception { - return System.getSecurityManager() != null ? AccessController.doPrivileged( action ) : action.run(); - } -" -175,0," public void setUp() throws Exception { - sshKey = SshdServerMock.generateKeyPair(); - System.setProperty(PluginImpl.TEST_SSH_KEYFILE_LOCATION_PROPERTY, sshKey.getPrivateKey().getAbsolutePath()); - server = new SshdServerMock(); - sshd = SshdServerMock.startServer(server); - server.returnCommandFor(""gerrit ls-projects"", SshdServerMock.EofCommandMock.class); - server.returnCommandFor(GERRIT_STREAM_EVENTS, SshdServerMock.CommandMock.class); - server.returnCommandFor(""gerrit review.*"", SshdServerMock.EofCommandMock.class); - server.returnCommandFor(""gerrit version"", SshdServerMock.EofCommandMock.class); - } - - /** - * Runs after test method. - * - * @throws Exception throw if so. - */ - @After -" -176,0," public boolean getSource_location() { - return m_source_location; - } - -" -177,0," public void setCoyoteRequest(org.apache.coyote.Request coyoteRequest) { - this.coyoteRequest = coyoteRequest; - inputBuffer.setRequest(coyoteRequest); - } - - /** - * Get the Coyote request. - */ -" -178,0," public ExpressionInterceptUrlRegistry access(String attribute) { - if (not) { - attribute = ""!"" + attribute; - } - interceptUrl(requestMatchers, SecurityConfig.createList(attribute)); - return ExpressionUrlAuthorizationConfigurer.this.REGISTRY; - } - } -} -" -179,0," private @CheckForNull File getDirectChild(File parentFile, String childPath){ - File current = new File(parentFile, childPath); - while (current != null && !parentFile.equals(current.getParentFile())) { - current = current.getParentFile(); - } - return current; - } - } - - private static final SoloFilePathFilter UNRESTRICTED = SoloFilePathFilter.wrap(FilePathFilter.UNRESTRICTED); -} -" -180,0," public static boolean containsExpression(String expr) { - return expr.contains(""%{"") && expr.contains(""}""); - } - -" -181,0," public void derIntegerTest() - throws Exception - { - try - { - new ASN1Integer(new byte[] { 0, 0, 0, 1}); - } - catch (IllegalArgumentException e) - { - isTrue(""wrong exc"", ""malformed integer"".equals(e.getMessage())); - } - - try - { - new ASN1Integer(new byte[] {(byte)0xff, (byte)0x80, 0, 1}); - } - catch (IllegalArgumentException e) - { - isTrue(""wrong exc"", ""malformed integer"".equals(e.getMessage())); - } - - try - { - new ASN1Enumerated(new byte[] { 0, 0, 0, 1}); - } - catch (IllegalArgumentException e) - { - isTrue(""wrong exc"", ""malformed enumerated"".equals(e.getMessage())); - } - - try - { - new ASN1Enumerated(new byte[] {(byte)0xff, (byte)0x80, 0, 1}); - } - catch (IllegalArgumentException e) - { - isTrue(""wrong exc"", ""malformed enumerated"".equals(e.getMessage())); - } - } - -" -182,0," public void cleanUp() { - Set names = files.keySet(); - for (String name : names) { - List items = files.get(name); - for (FileItem item : items) { - if (LOG.isDebugEnabled()) { - String msg = LocalizedTextUtil.findText(this.getClass(), ""struts.messages.removing.file"", - Locale.ENGLISH, ""no.message.found"", new Object[]{name, item}); - LOG.debug(msg); - } - if (!item.isInMemory()) { - item.delete(); - } - } - } - } - -" -183,0," protected JDBCTableReader getTableReader(Connection connection, String tableName, EmbeddedDocumentUtil embeddedDocumentUtil) { - return new SQLite3TableReader(connection, tableName, embeddedDocumentUtil); - } -" -184,0," public Character decodeCharacter( PushbackString input ) { - input.mark(); - Character first = input.next(); - if ( first == null ) { - input.reset(); - return null; - } - - // if this is not an encoded character, return null - if (first != '%' ) { - input.reset(); - return null; - } - - // Search for exactly 2 hex digits following - StringBuilder sb = new StringBuilder(); - for ( int i=0; i<2; i++ ) { - Character c = input.nextHex(); - if ( c != null ) sb.append( c ); - } - if ( sb.length() == 2 ) { - try { - // parse the hex digit and create a character - int i = Integer.parseInt(sb.toString(), 16); - if (Character.isValidCodePoint(i)) { - return (char) i; - } - } catch( NumberFormatException ignored ) { } - } - input.reset(); - return null; - } - -" -185,0," public String getPathname() { - - return pathname; - - } - - - /** - * Set the pathname of our XML file containing user definitions. If a - * relative pathname is specified, it is resolved against ""catalina.base"". - * - * @param pathname The new pathname - */ -" -186,0," public boolean isSecureProcessing() - { - return m_isSecureProcessing; - } -" -187,0," public void write(OutputStream outputStream) - throws IOException, WebApplicationException { - Writer writer = new OutputStreamWriter(outputStream, UTF_8); - ContentHandler content; - - try { - SAXTransformerFactory factory = (SAXTransformerFactory) SAXTransformerFactory.newInstance(); - TransformerHandler handler = factory.newTransformerHandler(); - handler.getTransformer().setOutputProperty(OutputKeys.METHOD, format); - handler.getTransformer().setOutputProperty(OutputKeys.INDENT, ""yes""); - handler.getTransformer().setOutputProperty(OutputKeys.ENCODING, UTF_8.name()); - handler.setResult(new StreamResult(writer)); - content = new ExpandedTitleContentHandler(handler); - } catch (TransformerConfigurationException e) { - throw new WebApplicationException(e); - } - - parse(parser, LOG, info.getPath(), is, content, metadata, context); - } - }; - } -} -" -188,0," private boolean isSameAs( - byte[] a, - byte[] b) - { - if (a.length != b.length) - { - return false; - } - - for (int i = 0; i != a.length; i++) - { - if (a[i] != b[i]) - { - return false; - } - } - - return true; - } - -" -189,0," private void testModified() - throws Exception - { - KeyFactory kFact = KeyFactory.getInstance(""DSA"", ""BC""); - PublicKey pubKey = kFact.generatePublic(PUBLIC_KEY); - Signature sig = Signature.getInstance(""DSA"", ""BC""); - - for (int i = 0; i != MODIFIED_SIGNATURES.length; i++) - { - sig.initVerify(pubKey); - - sig.update(Strings.toByteArray(""Hello"")); - - boolean failed; - - try - { - failed = !sig.verify(Hex.decode(MODIFIED_SIGNATURES[i])); - } - catch (SignatureException e) - { - failed = true; - } - - isTrue(""sig verified when shouldn't"", failed); - } - } - -" -190,0," public LockoutPolicyRetriever getLockoutPolicyRetriever() { - return lockoutPolicyRetriever; - } -" -191,0," public void close() throws IOException { - if (!closed) { - synchronized (this) { - if (!closed) { - closed = true; - socket.close(); - } - } - } - } - -" -192,0," protected abstract void recycleInternal(); -" -193,0," public static JWTDecoder getInstance() { - if (instance == null) { - instance = new JWTDecoder(); - } - - return instance; - } - - /** - * Decode the JWT using one of they provided verifiers. One more verifiers may be provided, the first verifier found - * supporting the algorithm reported by the JWT header will be utilized. - *

- * A JWT that is expired or not yet valid will not be decoded, instead a {@link JWTExpiredException} or {@link - * JWTUnavailableForProcessingException} exception will be thrown respectively. - * - * @param encodedJWT The encoded JWT in string format. - * @param verifiers A map of verifiers. - * @return a decoded JWT. - */ -" -194,0," public boolean check(String path, Resource resource) - { - int slash = path.lastIndexOf('/'); - if (slash<0 || resource.exists()) - return false; - String suffix=path.substring(slash); - return resource.getAlias().toString().endsWith(suffix); - } - } -} -" -195,0," public void setMaxParameterCount(int maxParameterCount) { - this.maxParameterCount = maxParameterCount; - } - - - /** - * Return the maximum size of a POST which will be automatically - * parsed by the container. - */ -" -196,0," protected boolean requiresAuthentication(final HttpServletRequest request, final HttpServletResponse response) { - boolean result = request.getRequestURI().contains(getFilterProcessesUrl()); - result |= isTokenExpired(); - if (logger.isDebugEnabled()) { - logger.debug(""requiresAuthentication = "" + result); - } - return result; - } - -" -197,0," public JettyContentExchange createContentExchange() { - return new JettyContentExchange9(); - } -" -198,0," protected void populateResponse(Exchange exchange, JettyContentExchange httpExchange, - Message in, HeaderFilterStrategy strategy, int responseCode) throws IOException { - Message answer = exchange.getOut(); - - answer.setHeader(Exchange.HTTP_RESPONSE_CODE, responseCode); - - // must use response fields to get the http headers as - // httpExchange.getHeaders() does not work well with multi valued headers - Map> headers = httpExchange.getResponseHeaders(); - for (Map.Entry> ent : headers.entrySet()) { - String name = ent.getKey(); - Collection values = ent.getValue(); - for (String value : values) { - if (name.toLowerCase().equals(""content-type"")) { - name = Exchange.CONTENT_TYPE; - exchange.setProperty(Exchange.CHARSET_NAME, IOHelper.getCharsetNameFromContentType(value)); - } - if (strategy != null && !strategy.applyFilterToExternalHeaders(name, value, exchange)) { - HttpHelper.appendHeader(answer.getHeaders(), name, value); - } - } - } - - // preserve headers from in by copying any non existing headers - // to avoid overriding existing headers with old values - // We also need to apply the httpProtocolHeaderFilterStrategy to filter the http protocol header - MessageHelper.copyHeaders(exchange.getIn(), answer, httpProtocolHeaderFilterStrategy, false); - - // extract body after headers has been set as we want to ensure content-type from Jetty HttpExchange - // has been populated first - answer.setBody(extractResponseBody(exchange, httpExchange)); - } - -" -199,0," protected boolean isAuthorizedToSwitchToIdentityZone(String identityZoneId) { - Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); - boolean hasScope = OAuth2ExpressionUtils.hasAnyScope(authentication, getZoneSwitchingScopes(identityZoneId)); - boolean isUaa = IdentityZoneHolder.isUaa(); - boolean isTokenAuth = (authentication instanceof OAuth2Authentication); - return isTokenAuth && isUaa && hasScope; - } - -" -200,0," protected static void copyBytes(byte[] b, int dest, int src, int len) { - for (int pos = 0; pos < len; pos++) { - b[pos + dest] = b[pos + src]; - } - } - - -" -201,0," public String getSessionId() - throws IOException { - // Look up the current SSLSession - SSLSession session = ssl.getSession(); - if (session == null) - return null; - // Expose ssl_session (getId) - byte [] ssl_session = session.getId(); - if ( ssl_session == null) - return null; - StringBuffer buf=new StringBuffer(""""); - for(int x=0; x2) digit=digit.substring(digit.length()-2); - buf.append(digit); - } - return buf.toString(); - } - - -" -202,0," private void login(String clientId) throws Exception { - getMockMvc().perform(post(""/oauth/token"") - .accept(MediaType.APPLICATION_JSON_VALUE) - .header(""Authorization"", ""Basic "" + new String(Base64.encode((clientId + "":"" + SECRET).getBytes()))) - .param(""grant_type"", ""client_credentials"") - ) - .andExpect(status().isOk()) - .andReturn().getResponse().getContentAsString(); - } - - @Test -" -203,0," public abstract JettyContentExchange createContentExchange(); - -" -204,0," public void testParameterNameAware() { - ParametersInterceptor pi = createParametersInterceptor(); - final Map actual = injectValueStackFactory(pi); - ValueStack stack = createStubValueStack(actual); - final Map expected = new HashMap() { - { - put(""fooKey"", ""fooValue""); - put(""barKey"", ""barValue""); - } - }; - Object a = new ParameterNameAware() { - public boolean acceptableParameterName(String parameterName) { - return expected.containsKey(parameterName); - } - }; - Map parameters = new HashMap() { - { - put(""fooKey"", ""fooValue""); - put(""barKey"", ""barValue""); - put(""error"", ""error""); - } - }; - pi.setParameters(a, stack, parameters); - assertEquals(expected, actual); - } - -" -205,0," protected CloseButtonBehavior newCloseButtonBehavior() - { - return new CloseButtonBehavior(); - } -" -206,0," public void repositoryVerificationTimeoutTest() throws Exception { - Client client = client(); - - Settings settings = ImmutableSettings.settingsBuilder() - .put(""location"", randomRepoPath()) - .put(""random_control_io_exception_rate"", 1.0).build(); - logger.info(""--> creating repository that cannot write any files - should fail""); - assertThrows(client.admin().cluster().preparePutRepository(""test-repo-1"") - .setType(MockRepositoryModule.class.getCanonicalName()).setSettings(settings), - RepositoryVerificationException.class); - - logger.info(""--> creating repository that cannot write any files, but suppress verification - should be acked""); - assertAcked(client.admin().cluster().preparePutRepository(""test-repo-1"") - .setType(MockRepositoryModule.class.getCanonicalName()).setSettings(settings).setVerify(false)); - - logger.info(""--> verifying repository""); - assertThrows(client.admin().cluster().prepareVerifyRepository(""test-repo-1""), RepositoryVerificationException.class); - - File location = randomRepoPath(); - - logger.info(""--> creating repository""); - try { - client.admin().cluster().preparePutRepository(""test-repo-1"") - .setType(MockRepositoryModule.class.getCanonicalName()) - .setSettings(ImmutableSettings.settingsBuilder() - .put(""location"", location) - .put(""localize_location"", true) - ).get(); - fail(""RepositoryVerificationException wasn't generated""); - } catch (RepositoryVerificationException ex) { - assertThat(ex.getMessage(), containsString(""is not shared"")); - } - } - -" -207,0," private static void log( String s ) { - if (log.isDebugEnabled()) - log.debug(""URLDecoder: "" + s ); - } - -" -208,0," private boolean evaluate(String text) { - try { - InputSource inputSource = new InputSource(new StringReader(text)); - Document inputDocument = builder.parse(inputSource); - return ((Boolean)xpath.evaluate(xpathExpression, inputDocument, XPathConstants.BOOLEAN)).booleanValue(); - } catch (Exception e) { - return false; - } - } - - @Override -" -209,0," public void basicWorkFlowTest() throws Exception { - Client client = client(); - - logger.info(""--> creating repository""); - assertAcked(client.admin().cluster().preparePutRepository(""test-repo"") - .setType(""fs"").setSettings(ImmutableSettings.settingsBuilder() - .put(""location"", randomRepoPath()) - .put(""compress"", randomBoolean()) - .put(""chunk_size"", randomIntBetween(100, 1000)))); - - createIndex(""test-idx-1"", ""test-idx-2"", ""test-idx-3""); - ensureGreen(); - - logger.info(""--> indexing some data""); - for (int i = 0; i < 100; i++) { - index(""test-idx-1"", ""doc"", Integer.toString(i), ""foo"", ""bar"" + i); - index(""test-idx-2"", ""doc"", Integer.toString(i), ""foo"", ""baz"" + i); - index(""test-idx-3"", ""doc"", Integer.toString(i), ""foo"", ""baz"" + i); - } - refresh(); - assertHitCount(client.prepareCount(""test-idx-1"").get(), 100L); - assertHitCount(client.prepareCount(""test-idx-2"").get(), 100L); - assertHitCount(client.prepareCount(""test-idx-3"").get(), 100L); - - ListenableActionFuture flushResponseFuture = null; - if (randomBoolean()) { - ArrayList indicesToFlush = newArrayList(); - for (int i = 1; i < 4; i++) { - if (randomBoolean()) { - indicesToFlush.add(""test-idx-"" + i); - } - } - if (!indicesToFlush.isEmpty()) { - String[] indices = indicesToFlush.toArray(new String[indicesToFlush.size()]); - logger.info(""--> starting asynchronous flush for indices {}"", Arrays.toString(indices)); - flushResponseFuture = client.admin().indices().prepareFlush(indices).execute(); - } - } - logger.info(""--> snapshot""); - CreateSnapshotResponse createSnapshotResponse = client.admin().cluster().prepareCreateSnapshot(""test-repo"", ""test-snap"").setWaitForCompletion(true).setIndices(""test-idx-*"", ""-test-idx-3"").get(); - assertThat(createSnapshotResponse.getSnapshotInfo().successfulShards(), greaterThan(0)); - assertThat(createSnapshotResponse.getSnapshotInfo().successfulShards(), equalTo(createSnapshotResponse.getSnapshotInfo().totalShards())); - - assertThat(client.admin().cluster().prepareGetSnapshots(""test-repo"").setSnapshots(""test-snap"").get().getSnapshots().get(0).state(), equalTo(SnapshotState.SUCCESS)); - - logger.info(""--> delete some data""); - for (int i = 0; i < 50; i++) { - client.prepareDelete(""test-idx-1"", ""doc"", Integer.toString(i)).get(); - } - for (int i = 50; i < 100; i++) { - client.prepareDelete(""test-idx-2"", ""doc"", Integer.toString(i)).get(); - } - for (int i = 0; i < 100; i += 2) { - client.prepareDelete(""test-idx-3"", ""doc"", Integer.toString(i)).get(); - } - refresh(); - assertHitCount(client.prepareCount(""test-idx-1"").get(), 50L); - assertHitCount(client.prepareCount(""test-idx-2"").get(), 50L); - assertHitCount(client.prepareCount(""test-idx-3"").get(), 50L); - - logger.info(""--> close indices""); - client.admin().indices().prepareClose(""test-idx-1"", ""test-idx-2"").get(); - - logger.info(""--> restore all indices from the snapshot""); - RestoreSnapshotResponse restoreSnapshotResponse = client.admin().cluster().prepareRestoreSnapshot(""test-repo"", ""test-snap"").setWaitForCompletion(true).execute().actionGet(); - assertThat(restoreSnapshotResponse.getRestoreInfo().totalShards(), greaterThan(0)); - - ensureGreen(); - for (int i=0; i<5; i++) { - assertHitCount(client.prepareCount(""test-idx-1"").get(), 100L); - assertHitCount(client.prepareCount(""test-idx-2"").get(), 100L); - assertHitCount(client.prepareCount(""test-idx-3"").get(), 50L); - } - - // Test restore after index deletion - logger.info(""--> delete indices""); - cluster().wipeIndices(""test-idx-1"", ""test-idx-2""); - logger.info(""--> restore one index after deletion""); - restoreSnapshotResponse = client.admin().cluster().prepareRestoreSnapshot(""test-repo"", ""test-snap"").setWaitForCompletion(true).setIndices(""test-idx-*"", ""-test-idx-2"").execute().actionGet(); - assertThat(restoreSnapshotResponse.getRestoreInfo().totalShards(), greaterThan(0)); - - ensureGreen(); - for (int i=0; i<5; i++) { - assertHitCount(client.prepareCount(""test-idx-1"").get(), 100L); - } - ClusterState clusterState = client.admin().cluster().prepareState().get().getState(); - assertThat(clusterState.getMetaData().hasIndex(""test-idx-1""), equalTo(true)); - assertThat(clusterState.getMetaData().hasIndex(""test-idx-2""), equalTo(false)); - - if (flushResponseFuture != null) { - // Finish flush - flushResponseFuture.actionGet(); - } - } - - - @Test -" -210,0," public ReturnValueDescriptor asDescriptor(boolean defaultGroupSequenceRedefined, List> defaultGroupSequence) { - return new ReturnValueDescriptorImpl( - getType(), - asDescriptors( getConstraints() ), - isCascading(), - defaultGroupSequenceRedefined, - defaultGroupSequence, - groupConversionHelper.asDescriptors() - ); - } -" -211,0," static final PyObject function___new__(PyNewWrapper new_, boolean init, PyType subtype, - PyObject[] args, String[] keywords) { - ArgParser ap = new ArgParser(""function"", args, keywords, - new String[] {""code"", ""globals"", ""name"", ""argdefs"", - ""closure""}, 0); - PyObject code = ap.getPyObject(0); - PyObject globals = ap.getPyObject(1); - PyObject name = ap.getPyObject(2, Py.None); - PyObject defaults = ap.getPyObject(3, Py.None); - PyObject closure = ap.getPyObject(4, Py.None); - - if (!(code instanceof PyBaseCode)) { - throw Py.TypeError(""function() argument 1 must be code, not "" + - code.getType().fastGetName()); - } - if (name != Py.None && !Py.isInstance(name, PyString.TYPE)) { - throw Py.TypeError(""arg 3 (name) must be None or string""); - } - if (defaults != Py.None && !(defaults instanceof PyTuple)) { - throw Py.TypeError(""arg 4 (defaults) must be None or tuple""); - } - - PyBaseCode tcode = (PyBaseCode)code; - int nfree = tcode.co_freevars == null ? 0 : tcode.co_freevars.length; - if (!(closure instanceof PyTuple)) { - if (nfree > 0 && closure == Py.None) { - throw Py.TypeError(""arg 5 (closure) must be tuple""); - } else if (closure != Py.None) { - throw Py.TypeError(""arg 5 (closure) must be None or tuple""); - } - } - - int nclosure = closure == Py.None ? 0 : closure.__len__(); - if (nfree != nclosure) { - throw Py.ValueError(String.format(""%s requires closure of length %d, not %d"", - tcode.co_name, nfree, nclosure)); - } - if (nclosure > 0) { - for (PyObject o : ((PyTuple)closure).asIterable()) { - if (!(o instanceof PyCell)) { - throw Py.TypeError(String.format(""arg 5 (closure) expected cell, found %s"", - o.getType().fastGetName())); - } - } - } - - PyFunction function = new PyFunction(globals, - defaults == Py.None - ? null : ((PyTuple)defaults).getArray(), - tcode, null, - closure == Py.None - ? null : ((PyTuple)closure).getArray()); - if (name != Py.None) { - function.__name__ = name.toString(); - } - return function; - } - - @ExposedSet(name = ""__name__"") -" -212,0," private static byte[] toUtf8Bytes(String str) - { - try - { - return str.getBytes(""UTF-8""); - } - catch(UnsupportedEncodingException e) - { - throw new IllegalStateException(""The Java spec requires UTF-8 support."", e); - } - } - - /** - * Append the two upper case hex characters for a byte. - * @param sb The string buffer to append to. - * @param b The byte to hexify - * @return sb with the hex characters appended. - */ - // rfc3986 2.1: For consistency, URI producers - // should use uppercase hexadecimal digits for all percent- - // encodings. -" -213,0," void getElUnsupported(String expression); - -" -214,0," public String toString() { - return xpathExpression; - } -" -215,0," public Descriptor getDescriptor() { - throw new UnsupportedOperationException(); - } - } -} -" -216,1," public void getAllPropertiesRequiresAdmin() { - j.jenkins.setAuthorizationStrategy(new MockAuthorizationStrategy() - .grant(Jenkins.ADMINISTER).everywhere().to(""admin"") - .grant(Jenkins.READ).everywhere().toEveryone()); - j.jenkins.setSecurityRealm(j.createDummySecurityRealm()); - - User admin = User.get(""admin""); - User alice = User.get(""alice""); - User bob = User.get(""bob""); - - // Admin can access user properties for all users - try (ACLContext as = ACL.as(admin)) { - assertThat(alice.getAllProperties(), not(empty())); - assertThat(bob.getAllProperties(), not(empty())); - assertThat(admin.getAllProperties(), not(empty())); - } - - // Non admins can only view their own - try (ACLContext as = ACL.as(alice)) { - assertThat(alice.getAllProperties(), not(empty())); - assertThat(bob.getAllProperties(), empty()); - assertThat(admin.getAllProperties(), empty()); - } - } - -" -217,1," protected

P postProcess(P object) { - return (P) this.objectPostProcessor.postProcess(object); - } - - /** - * Executes the build using the {@link SecurityConfigurer}'s that have been applied - * using the following steps: - * - *

    - *
  • Invokes {@link #beforeInit()} for any subclass to hook into
  • - *
  • Invokes {@link SecurityConfigurer#init(SecurityBuilder)} for any - * {@link SecurityConfigurer} that was applied to this builder.
  • - *
  • Invokes {@link #beforeConfigure()} for any subclass to hook into
  • - *
  • Invokes {@link #performBuild()} which actually builds the Object
  • - *
- */ - @Override -" -218,1," public SAXSource toSAXSourceFromStream(StreamSource source, Exchange exchange) throws SAXException { - InputSource inputSource; - if (source.getReader() != null) { - inputSource = new InputSource(source.getReader()); - } else { - inputSource = new InputSource(source.getInputStream()); - } - inputSource.setSystemId(source.getSystemId()); - inputSource.setPublicId(source.getPublicId()); - XMLReader xmlReader = null; - SAXParserFactory sfactory = null; - //Need to setup XMLReader security feature by default - try { - // use the SAXPaserFactory which is set from exchange - if (exchange != null) { - sfactory = exchange.getProperty(Exchange.SAXPARSER_FACTORY, SAXParserFactory.class); - } - if (sfactory == null) { - sfactory = SAXParserFactory.newInstance(); - try { - sfactory.setFeature(javax.xml.XMLConstants.FEATURE_SECURE_PROCESSING, true); - } catch (Exception e) { - LOG.warn(""SAXParser doesn't support the feature {} with value {}, due to {}."", new Object[]{javax.xml.XMLConstants.FEATURE_SECURE_PROCESSING, ""true"", e}); - } - } - sfactory.setNamespaceAware(true); - SAXParser parser = sfactory.newSAXParser(); - xmlReader = parser.getXMLReader(); - } catch (Exception ex) { - LOG.warn(""Cannot create the SAXParser XMLReader, due to {}"", ex); - } - return new SAXSource(xmlReader, inputSource); - } - - /** - * @deprecated will be removed in Camel 3.0. Use the method which has 2 parameters. - */ - @Deprecated -" -219,1," public String getDisplayName() { - return Messages.CommandLauncher_displayName(); - } - } -} -" -220,1," public SSOValidatorResponse validateSamlResponse( - org.opensaml.saml.saml2.core.Response samlResponse, - boolean postBinding - ) throws WSSecurityException { - // Check the Issuer - validateIssuer(samlResponse.getIssuer()); - - // The Response must contain at least one Assertion. - if (samlResponse.getAssertions() == null || samlResponse.getAssertions().isEmpty()) { - LOG.fine(""The Response must contain at least one Assertion""); - throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, ""invalidSAMLsecurity""); - } - - // The Response must contain a Destination that matches the assertionConsumerURL if it is - // signed - String destination = samlResponse.getDestination(); - if (samlResponse.isSigned() - && (destination == null || !destination.equals(assertionConsumerURL))) { - LOG.fine(""The Response must contain a destination that matches the assertion consumer URL""); - throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, ""invalidSAMLsecurity""); - } - - // Validate Assertions - boolean foundValidSubject = false; - Date sessionNotOnOrAfter = null; - for (org.opensaml.saml.saml2.core.Assertion assertion : samlResponse.getAssertions()) { - // Check the Issuer - if (assertion.getIssuer() == null) { - LOG.fine(""Assertion Issuer must not be null""); - throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, ""invalidSAMLsecurity""); - } - validateIssuer(assertion.getIssuer()); - - if (enforceAssertionsSigned && postBinding && assertion.getSignature() == null) { - LOG.fine(""If the HTTP Post binding is used to deliver the Response, "" - + ""the enclosed assertions must be signed""); - throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, ""invalidSAMLsecurity""); - } - - // Check for AuthnStatements and validate the Subject accordingly - if (assertion.getAuthnStatements() != null - && !assertion.getAuthnStatements().isEmpty()) { - org.opensaml.saml.saml2.core.Subject subject = assertion.getSubject(); - if (validateAuthenticationSubject(subject, assertion.getID(), postBinding)) { - validateAudienceRestrictionCondition(assertion.getConditions()); - foundValidSubject = true; - // Store Session NotOnOrAfter - for (AuthnStatement authnStatment : assertion.getAuthnStatements()) { - if (authnStatment.getSessionNotOnOrAfter() != null) { - sessionNotOnOrAfter = authnStatment.getSessionNotOnOrAfter().toDate(); - } - } - } - } - - } - - if (!foundValidSubject) { - LOG.fine(""The Response did not contain any Authentication Statement that matched "" - + ""the Subject Confirmation criteria""); - throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, ""invalidSAMLsecurity""); - } - - SSOValidatorResponse validatorResponse = new SSOValidatorResponse(); - validatorResponse.setResponseId(samlResponse.getID()); - validatorResponse.setSessionNotOnOrAfter(sessionNotOnOrAfter); - if (samlResponse.getIssueInstant() != null) { - validatorResponse.setCreated(samlResponse.getIssueInstant().toDate()); - } - - // the assumption for now is that SAMLResponse will contain only a single assertion - Element assertionElement = samlResponse.getAssertions().get(0).getDOM(); - Element clonedAssertionElement = (Element)assertionElement.cloneNode(true); - validatorResponse.setAssertionElement(clonedAssertionElement); - validatorResponse.setAssertion(DOM2Writer.nodeToString(clonedAssertionElement)); - - return validatorResponse; - } - - /** - * Validate the Issuer (if it exists) - */ -" -221,1," private JWT decode(String encodedJWT, Header header, String[] parts, Verifier verifier) { - int index = encodedJWT.lastIndexOf("".""); - // The message comprises the first two segments of the entire JWT, the signature is the last segment. - byte[] message = encodedJWT.substring(0, index).getBytes(StandardCharsets.UTF_8); - - // If a signature is provided and verifier must be provided. - if (parts.length == 3 && verifier == null) { - throw new MissingVerifierException(""No Verifier has been provided for verify a signature signed using ["" + header.algorithm.getName() + ""]""); - } - - // A verifier was provided but no signature exists, this is treated as an invalid signature. - if (parts.length == 2 && verifier != null) { - throw new InvalidJWTSignatureException(); - } - - if (parts.length == 3) { - // Verify the signature before de-serializing the payload. - byte[] signature = base64Decode(parts[2].getBytes(StandardCharsets.UTF_8)); - verifier.verify(header.algorithm, message, signature); - } - - JWT jwt = Mapper.deserialize(base64Decode(parts[1].getBytes(StandardCharsets.UTF_8)), JWT.class); - - // Verify expiration claim - if (jwt.isExpired()) { - throw new JWTExpiredException(); - } - - // Verify the notBefore claim - if (jwt.isUnavailableForProcessing()) { - throw new JWTUnavailableForProcessingException(); - } - - return jwt; - } - -" -222,1," String postProcessVariableName(String variableName) { - return this.matcher.postProcessVariableName(variableName); - } - } - -} -" -223,1," public String toString() { - - StringBuilder sb = new StringBuilder("" 0) { - sb.append("" groups=\""""); - int n = 0; - Iterator 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 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()); - - } - - -" -224,1," public void processParameters( String str ) { - int end=str.length(); - int pos=0; - if( debug > 0) - log(""String: "" + str ); - - do { - boolean noEq=false; - int valStart=-1; - int valEnd=-1; - - int nameStart=pos; - int nameEnd=str.indexOf('=', nameStart ); - int nameEnd2=str.indexOf('&', nameStart ); - if( nameEnd2== -1 ) nameEnd2=end; - if( (nameEnd2!=-1 ) && - ( nameEnd==-1 || nameEnd > nameEnd2) ) { - nameEnd=nameEnd2; - noEq=true; - valStart=nameEnd; - valEnd=nameEnd; - if(debug>0) log(""no equal "" + nameStart + "" "" + nameEnd + "" "" + - str.substring(nameStart, nameEnd)); - } - - if( nameEnd== -1 ) nameEnd=end; - - if( ! noEq ) { - valStart=nameEnd+1; - valEnd=str.indexOf('&', valStart); - if( valEnd== -1 ) valEnd = (valStart < end) ? end : valStart; - } - - pos=valEnd+1; - - if( nameEnd<=nameStart ) { - continue; - } - if( debug>0) - log( ""XXX "" + nameStart + "" "" + nameEnd + "" "" - + valStart + "" "" + valEnd ); - - try { - tmpNameC.append(str, nameStart, nameEnd-nameStart ); - tmpValueC.append(str, valStart, valEnd-valStart ); - - if( debug > 0 ) - log( tmpNameC + ""= "" + tmpValueC); - - if( urlDec==null ) { - urlDec=new UDecoder(); - } - - urlDec.convert( tmpNameC ); - urlDec.convert( tmpValueC ); - - if( debug > 0 ) - log( tmpNameC + ""= "" + tmpValueC); - - addParam( tmpNameC.toString(), tmpValueC.toString() ); - } catch( IOException ex ) { - ex.printStackTrace(); - } - - tmpNameC.recycle(); - tmpValueC.recycle(); - - } while( pos users = userProvisioning.query(""username eq \""marissa\""""); - assertNotNull(users); - assertEquals(1, users.size()); - ScimUser user = users.get(0); - - ExpiringCode code = codeStore.generateCode(user.getId(), new Timestamp(System.currentTimeMillis() + UaaResetPasswordService.PASSWORD_RESET_LIFETIME), null); - getMockMvc().perform(createChangePasswordRequest(user, code, true, ""d3faultPasswd"", ""d3faultPasswd"")); - - code = codeStore.generateCode(user.getId(), new Timestamp(System.currentTimeMillis() + UaaResetPasswordService.PASSWORD_RESET_LIFETIME), null); - getMockMvc().perform(createChangePasswordRequest(user, code, true, ""d3faultPasswd"", ""d3faultPasswd"")) - .andExpect(status().isUnprocessableEntity()) - .andExpect(view().name(""forgot_password"")) - .andExpect(model().attribute(""message"", ""Your new password cannot be the same as the old password."")); - } - -" -227,1," public void recycle() { - if (buffered.getBuffer().length > 65536) { - buffered = null; - } else { - buffered.recycle(); - } - tempRead.recycle(); - hasRead = false; - buffer = null; - } - -" -228,1," public XMLLoader init(SolrParams args) { - inputFactory = XMLInputFactory.newInstance(); - 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); - } - inputFactory.setXMLReporter(xmllog); - - xsltCacheLifetimeSeconds = XSLT_CACHE_DEFAULT; - if(args != null) { - xsltCacheLifetimeSeconds = args.getInt(XSLT_CACHE_PARAM,XSLT_CACHE_DEFAULT); - log.info(""xsltCacheLifetimeSeconds="" + xsltCacheLifetimeSeconds); - } - return this; - } - -" -229,1," protected void execute() { - - Arrays.asList(controllersListStrings).forEach( - cInfoString -> controllers.add(parseCInfoString(cInfoString))); - 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 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()); - } - - -" -230,1," protected boolean parseChunkHeader() - throws IOException { - - int result = 0; - boolean eol = false; - boolean readDigit = false; - boolean trailer = false; - - while (!eol) { - - if (pos >= lastValid) { - if (readBytes() <= 0) - return false; - } - - if (buf[pos] == Constants.CR || buf[pos] == Constants.LF) { - parseCRLF(false); - eol = true; - } else if (buf[pos] == Constants.SEMI_COLON) { - trailer = true; - } else if (!trailer) { - //don't read data after the trailer - int charValue = HexUtils.getDec(buf[pos]); - if (charValue != -1) { - readDigit = true; - result *= 16; - result += charValue; - } else { - //we shouldn't allow invalid, non hex characters - //in the chunked header - return false; - } - } - - // Parsing the CRLF increments pos - if (!eol) { - pos++; - } - - } - - if (!readDigit) - return false; - - if (result == 0) - endChunk = true; - - remaining = result; - if (remaining < 0) - return false; - - return true; - - } - - - /** - * Parse CRLF at end of chunk. - * - * @param tolerant Should tolerant parsing (LF and CRLF) be used? This - * is recommended (RFC2616, section 19.3) for message - * headers. - */ -" -231,1," private static DocumentBuilder getBuilder() throws ParserConfigurationException { - ClassLoader loader = Thread.currentThread().getContextClassLoader(); - if (loader == null) { - loader = DOMUtils.class.getClassLoader(); - } - if (loader == null) { - return XMLUtils.getParser(); - } - DocumentBuilder builder = DOCUMENT_BUILDERS.get(loader); - if (builder == null) { - builder = XMLUtils.getParser(); - DOCUMENT_BUILDERS.put(loader, builder); - } - return builder; - } - - /** - * This function is much like getAttribute, but returns null, not """", for a nonexistent attribute. - * - * @param e - * @param attributeName - */ -" -232,1," public void init(Map 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) { - throw new SolrException(ErrorCode.SERVER_ERROR, ""Error initializing "" + getClass().getName() + "": ""+e); - } - } - - @SuppressWarnings(""unchecked"") -" -233,1," public void addRecipients(final ExtendedEmailPublisherContext context, EnvVars env, Set to, Set cc, Set 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.getListener(), 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 - */ -" -234,1," public void test_noVerification() throws Exception { - // Sign a JWT and then attempt to verify it using None. - JWT jwt = new JWT().setSubject(""art""); - String encodedJWT = JWT.getEncoder().encode(jwt, HMACSigner.newSHA256Signer(""secret"")); - - expectException(MissingVerifierException.class, () - -> JWT.getDecoder().decode(encodedJWT)); - } - - @Test -" -235,1," protected void configure(HttpSecurity http) throws Exception { - // This config is also on UrlAuthorizationConfigurer javadoc - http - .apply(new UrlAuthorizationConfigurer()).getRegistry() - .antMatchers(""/users**"",""/sessions/**"").hasRole(""USER"") - .antMatchers(""/signup"").hasRole(""ANONYMOUS"") - .anyRequest().hasRole(""USER""); - } - // @formatter:on -" -236,1," 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.RELOAD_XML_CONFIGURATION, Boolean.FALSE.toString()); - } - -" -237,1," public void fireOnComplete() { - List listenersCopy = new ArrayList<>(); - listenersCopy.addAll(listeners); - - ClassLoader oldCL = context.bind(Globals.IS_SECURITY_ENABLED, null); - try { - for (AsyncListenerWrapper listener : listenersCopy) { - try { - listener.fireOnComplete(event); - } catch (Throwable t) { - ExceptionUtils.handleThrowable(t); - log.warn(""onComplete() failed for listener of type ["" + - listener.getClass().getName() + ""]"", t); - } - } - } finally { - context.fireRequestDestroyEvent(request); - clearServletRequestResponse(); - context.unbind(Globals.IS_SECURITY_ENABLED, oldCL); - } - } - - -" -238,1," public void testExcludedTrickyParameters() throws Exception { - Map params = new HashMap() { - { - put(""blah"", ""This is blah""); - put(""name"", ""try_1""); - put(""(name)"", ""try_2""); - put(""['name']"", ""try_3""); - put(""['na' + 'me']"", ""try_4""); - put(""{name}[0]"", ""try_5""); - put(""(new string{'name'})[0]"", ""try_6""); - put(""#{key: 'name'}.key"", ""try_7""); - - } - }; - - HashMap extraContext = new HashMap(); - extraContext.put(ActionContext.PARAMETERS, params); - - ActionProxy proxy = actionProxyFactory.createActionProxy("""", MockConfigurationProvider.PARAM_INTERCEPTOR_ACTION_NAME, extraContext); - - ActionConfig config = configuration.getRuntimeConfiguration().getActionConfig("""", MockConfigurationProvider.PARAM_INTERCEPTOR_ACTION_NAME); - ParametersInterceptor pi =(ParametersInterceptor) config.getInterceptors().get(0).getInterceptor(); - pi.setExcludeParams(""name""); - - proxy.execute(); - - SimpleAction action = (SimpleAction) proxy.getAction(); - assertNull(action.getName()); - assertEquals(""This is blah"", (action).getBlah()); - } - -" -239,1," protected BindResult process(final LDAPConnection connection, final int depth) - throws LDAPException - { - if (connection.synchronousMode()) - { - @SuppressWarnings(""deprecation"") - final boolean autoReconnect = - connection.getConnectionOptions().autoReconnect(); - return processSync(connection, autoReconnect); - } - - // See if a bind DN was provided without a password. If that is the case - // and this should not be allowed, then throw an exception. - if (password != null) - { - if ((bindDN.getValue().length > 0) && (password.getValue().length == 0) && - connection.getConnectionOptions().bindWithDNRequiresPassword()) - { - final LDAPException le = new LDAPException(ResultCode.PARAM_ERROR, - ERR_SIMPLE_BIND_DN_WITHOUT_PASSWORD.get()); - debugCodingError(le); - throw le; - } - } - - - // Create the LDAP message. - messageID = connection.nextMessageID(); - final LDAPMessage message = new LDAPMessage(messageID, this, getControls()); - - - // Register with the connection reader to be notified of responses for the - // request that we've created. - connection.registerResponseAcceptor(messageID, this); - - - try - { - // Send the request to the server. - final long responseTimeout = getResponseTimeoutMillis(connection); - debugLDAPRequest(Level.INFO, this, messageID, connection); - final long requestTime = System.nanoTime(); - connection.getConnectionStatistics().incrementNumBindRequests(); - connection.sendMessage(message, responseTimeout); - - // Wait for and process the response. - final LDAPResponse response; - try - { - if (responseTimeout > 0) - { - response = responseQueue.poll(responseTimeout, TimeUnit.MILLISECONDS); - } - else - { - response = responseQueue.take(); - } - } - catch (final InterruptedException ie) - { - debugException(ie); - Thread.currentThread().interrupt(); - throw new LDAPException(ResultCode.LOCAL_ERROR, - ERR_BIND_INTERRUPTED.get(connection.getHostPort()), ie); - } - - return handleResponse(connection, response, requestTime, false); - } - finally - { - connection.deregisterResponseAcceptor(messageID); - } - } - - - - /** - * Processes this bind operation in synchronous mode, in which the same - * thread will send the request and read the response. - * - * @param connection The connection to use to communicate with the directory - * server. - * @param allowRetry Indicates whether the request may be re-tried on a - * re-established connection if the initial attempt fails - * in a way that indicates the connection is no longer - * valid and autoReconnect is true. - * - * @return An LDAP result object that provides information about the result - * of the bind processing. - * - * @throws LDAPException If a problem occurs while sending the request or - * reading the response. - */ -" -240,1," public Set getControllerServices(final boolean recursive) { - readLock.lock(); - try { - final Set services = new HashSet<>(); - services.addAll(controllerServices.values()); - - if (recursive && parent.get() != null) { - services.addAll(parent.get().getControllerServices(true)); - } - - return services; - } finally { - readLock.unlock(); - } - } - - @Override -" -241,1," public boolean getValidateClientProvidedNewSessionId() { - return validateClientProvidedNewSessionId; - } - - @Override -" -242,1," private static void doZipDir(File dir, ZipOutputStream out) throws IOException { - File[] children = dir.listFiles(); - if (children == null) { - throw new IllegalStateException(""Fail to list files of directory "" + dir.getAbsolutePath()); - } - for (File child : children) { - doZip(child.getName(), child, out); - } - } - - /** - * @see #unzip(File, File, Predicate) - * @deprecated replaced by {@link Predicate} in 6.2. - */ - @Deprecated - @FunctionalInterface -" -243,1," public H and() { - return ChannelSecurityConfigurer.this.and(); - } - -" -244,1," public boolean isLockoutEnabled() { - return countFailuresWithin > 0; - } - -" -245,1," protected synchronized void authenticatorConfig() { - - // Always need an authenticator to support @ServletSecurity annotations - LoginConfig loginConfig = context.getLoginConfig(); - if (loginConfig == null) { - loginConfig = DUMMY_LOGIN_CONFIG; - context.setLoginConfig(loginConfig); - } - - // Has an authenticator been configured already? - if (context.getAuthenticator() != null) - return; - - if (!(context instanceof ContainerBase)) { - return; // Cannot install a Valve even if it would be needed - } - - // Has a Realm been configured for us to authenticate against? - if (context.getRealm() == null) { - log.error(sm.getString(""contextConfig.missingRealm"")); - ok = false; - return; - } - - /* - * First check to see if there is a custom mapping for the login - * method. If so, use it. Otherwise, check if there is a mapping in - * org/apache/catalina/startup/Authenticators.properties. - */ - Valve authenticator = null; - if (customAuthenticators != null) { - authenticator = (Valve) - customAuthenticators.get(loginConfig.getAuthMethod()); - } - if (authenticator == null) { - // Load our mapping properties if necessary - if (authenticators == null) { - try { - InputStream is=this.getClass().getClassLoader().getResourceAsStream(""org/apache/catalina/startup/Authenticators.properties""); - if( is!=null ) { - authenticators = new Properties(); - authenticators.load(is); - } else { - log.error(sm.getString( - ""contextConfig.authenticatorResources"")); - ok=false; - return; - } - } catch (IOException e) { - log.error(sm.getString( - ""contextConfig.authenticatorResources""), e); - ok = false; - return; - } - } - - // Identify the class name of the Valve we should configure - String authenticatorName = null; - authenticatorName = - authenticators.getProperty(loginConfig.getAuthMethod()); - if (authenticatorName == null) { - log.error(sm.getString(""contextConfig.authenticatorMissing"", - loginConfig.getAuthMethod())); - ok = false; - return; - } - - // Instantiate and install an Authenticator of the requested class - try { - Class authenticatorClass = Class.forName(authenticatorName); - authenticator = (Valve) authenticatorClass.newInstance(); - } catch (Throwable t) { - ExceptionUtils.handleThrowable(t); - log.error(sm.getString( - ""contextConfig.authenticatorInstantiate"", - authenticatorName), - t); - ok = false; - } - } - - if (authenticator != null && context instanceof ContainerBase) { - Pipeline pipeline = ((ContainerBase) context).getPipeline(); - if (pipeline != null) { - ((ContainerBase) context).getPipeline().addValve(authenticator); - if (log.isDebugEnabled()) { - log.debug(sm.getString( - ""contextConfig.authenticatorConfigured"", - loginConfig.getAuthMethod())); - } - } - } - - } - - - /** - * Create (if necessary) and return a Digester configured to process the - * web application deployment descriptor (web.xml). - */ -" -246,1," private void processInternal(Exchange exchange, AsyncCallback callback) throws Exception { - // creating the url to use takes 2-steps - String url = HttpHelper.createURL(exchange, getEndpoint()); - URI uri = HttpHelper.createURI(exchange, url, getEndpoint()); - // get the url from the uri - url = uri.toASCIIString(); - - // execute any custom url rewrite - String rewriteUrl = HttpHelper.urlRewrite(exchange, url, getEndpoint(), this); - if (rewriteUrl != null) { - // update url and query string from the rewritten url - url = rewriteUrl; - } - - String methodName = HttpHelper.createMethod(exchange, getEndpoint(), exchange.getIn().getBody() != null).name(); - - JettyContentExchange httpExchange = getEndpoint().createContentExchange(); - httpExchange.init(exchange, getBinding(), client, callback); - httpExchange.setURL(url); // Url has to be set first - httpExchange.setMethod(methodName); - - if (getEndpoint().getHttpClientParameters() != null) { - // For jetty 9 these parameters can not be set on the client - // so we need to set them on the httpExchange - String timeout = (String)getEndpoint().getHttpClientParameters().get(""timeout""); - if (timeout != null) { - httpExchange.setTimeout(new Long(timeout)); - } - String supportRedirect = (String)getEndpoint().getHttpClientParameters().get(""supportRedirect""); - if (supportRedirect != null) { - httpExchange.setSupportRedirect(Boolean.valueOf(supportRedirect)); - } - } - - LOG.trace(""Using URL: {} with method: {}"", url, methodName); - - // if there is a body to send as data - if (exchange.getIn().getBody() != null) { - String contentType = ExchangeHelper.getContentType(exchange); - if (contentType != null) { - httpExchange.setRequestContentType(contentType); - } - - if (contentType != null && HttpConstants.CONTENT_TYPE_JAVA_SERIALIZED_OBJECT.equals(contentType)) { - // serialized java object - Serializable obj = exchange.getIn().getMandatoryBody(Serializable.class); - // write object to output stream - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - try { - HttpHelper.writeObjectToStream(bos, obj); - httpExchange.setRequestContent(bos.toByteArray()); - } finally { - IOHelper.close(bos, ""body"", LOG); - } - } else { - Object body = exchange.getIn().getBody(); - if (body instanceof String) { - String data = (String) body; - // be a bit careful with String as any type can most likely be converted to String - // so we only do an instanceof check and accept String if the body is really a String - // do not fallback to use the default charset as it can influence the request - // (for example application/x-www-form-urlencoded forms being sent) - String charset = IOHelper.getCharsetName(exchange, false); - httpExchange.setRequestContent(data, charset); - } else { - // then fallback to input stream - InputStream is = exchange.getContext().getTypeConverter().mandatoryConvertTo(InputStream.class, exchange, exchange.getIn().getBody()); - httpExchange.setRequestContent(is); - // setup the content length if it is possible - String length = exchange.getIn().getHeader(Exchange.CONTENT_LENGTH, String.class); - if (ObjectHelper.isNotEmpty(length)) { - httpExchange.addRequestHeader(Exchange.CONTENT_LENGTH, length); - } - } - } - } - - // 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 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""); - } - - // propagate headers as HTTP headers - Message in = exchange.getIn(); - HeaderFilterStrategy strategy = getEndpoint().getHeaderFilterStrategy(); - for (Map.Entry 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 values to add as a request header - final List values = new ArrayList(); - - // 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); - httpExchange.addRequestHeader(key, s); - } - } - } - - // set the callback, which will handle all the response logic - if (LOG.isDebugEnabled()) { - LOG.debug(""Sending HTTP request to: {}"", httpExchange.getUrl()); - } - httpExchange.send(client); - } - -" -247,1," public void send(final String format, final Object... args) { - descriptor.debug(logger, format, args); - } - } - final Debug debug = new Debug(); - - Set users = null; - - final Run currentRun = context.getRun(); - if (currentRun == null) { - debug.send(""currentRun was null""); - } else { - if (!Objects.equals(currentRun.getResult(), Result.FAILURE)) { - debug.send(""currentBuild did not fail""); - } else { - users = new HashSet<>(); - debug.send(""Collecting builds with suspects...""); - final HashSet> buildsWithSuspects = new HashSet<>(); - Run firstFailedBuild = currentRun; - Run candidate = currentRun; - while (candidate != null) { - final Result candidateResult = candidate.getResult(); - if ( candidateResult == null || !candidateResult.isWorseOrEqualTo(Result.FAILURE) ) { - break; - } - firstFailedBuild = candidate; - candidate = candidate.getPreviousCompletedBuild(); - } - if (firstFailedBuild instanceof AbstractBuild) { - buildsWithSuspects.add(firstFailedBuild); - } else { - debug.send("" firstFailedBuild was not an instance of AbstractBuild""); - } - debug.send(""Collecting suspects...""); - users.addAll(RecipientProviderUtilities.getChangeSetAuthors(buildsWithSuspects, debug)); - users.addAll(RecipientProviderUtilities.getUsersTriggeringTheBuilds(buildsWithSuspects, debug)); - } - } - if (users != null) { - RecipientProviderUtilities.addUsers(users, context.getListener(), env, to, cc, bcc, debug); - } - } - - @Extension - public static final class DescriptorImpl extends RecipientProviderDescriptor { - @Override - public String getDisplayName() { - return ""Suspects Causing the Build to Begin Failing""; - } - } - -} -" -248,1," public Document getMetaData(Idp config) throws RuntimeException { - //Return as text/xml - try { - Crypto crypto = CertsUtils.createCrypto(config.getCertificate()); - - ByteArrayOutputStream bout = new ByteArrayOutputStream(4096); - Writer streamWriter = new OutputStreamWriter(bout, ""UTF-8""); - XMLStreamWriter writer = XML_OUTPUT_FACTORY.createXMLStreamWriter(streamWriter); - - writer.writeStartDocument(""UTF-8"", ""1.0""); - - String referenceID = IDGenerator.generateID(""_""); - writer.writeStartElement(""md"", ""EntityDescriptor"", SAML2_METADATA_NS); - writer.writeAttribute(""ID"", referenceID); - - writer.writeAttribute(""entityID"", config.getIdpUrl().toString()); - - 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); - - writeFederationMetadata(writer, config, crypto); - - 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()); - - Document result = SignatureUtils.signMetaInfo(crypto, null, config.getCertificatePassword(), is, referenceID); - if (result != null) { - return result; - } else { - throw new RuntimeException(""Failed to sign the metadata document: result=null""); - } - } catch (RuntimeException e) { - throw e; - } catch (Exception e) { - LOG.error(""Error creating service metadata information "", e); - throw new RuntimeException(""Error creating service metadata information: "" + e.getMessage()); - } - - } - -" -249,1," public void chaosSnapshotTest() throws Exception { - final List indices = new CopyOnWriteArrayList<>(); - Settings settings = settingsBuilder().put(""action.write_consistency"", ""one"").build(); - int initialNodes = between(1, 3); - logger.info(""--> start {} nodes"", initialNodes); - for (int i = 0; i < initialNodes; i++) { - internalCluster().startNode(settings); - } - - logger.info(""--> creating repository""); - assertAcked(client().admin().cluster().preparePutRepository(""test-repo"") - .setType(""fs"").setSettings(ImmutableSettings.settingsBuilder() - .put(""location"", newTempDir(LifecycleScope.SUITE)) - .put(""compress"", randomBoolean()) - .put(""chunk_size"", randomIntBetween(100, 1000)))); - - int initialIndices = between(1, 3); - logger.info(""--> create {} indices"", initialIndices); - for (int i = 0; i < initialIndices; i++) { - createTestIndex(""test-"" + i); - indices.add(""test-"" + i); - } - - int asyncNodes = between(0, 5); - logger.info(""--> start {} additional nodes asynchronously"", asyncNodes); - ListenableFuture> asyncNodesFuture = internalCluster().startNodesAsync(asyncNodes, settings); - - int asyncIndices = between(0, 10); - logger.info(""--> create {} additional indices asynchronously"", asyncIndices); - Thread[] asyncIndexThreads = new Thread[asyncIndices]; - for (int i = 0; i < asyncIndices; i++) { - final int cur = i; - asyncIndexThreads[i] = new Thread(new Runnable() { - @Override - public void run() { - createTestIndex(""test-async-"" + cur); - indices.add(""test-async-"" + cur); - - } - }); - asyncIndexThreads[i].start(); - } - - logger.info(""--> snapshot""); - - ListenableActionFuture snapshotResponseFuture = client().admin().cluster().prepareCreateSnapshot(""test-repo"", ""test-snap"").setWaitForCompletion(true).setIndices(""test-*"").setPartial(true).execute(); - - long start = System.currentTimeMillis(); - // Produce chaos for 30 sec or until snapshot is done whatever comes first - int randomIndices = 0; - while (System.currentTimeMillis() - start < 30000 && !snapshotIsDone(""test-repo"", ""test-snap"")) { - Thread.sleep(100); - int chaosType = randomInt(10); - if (chaosType < 4) { - // Randomly delete an index - if (indices.size() > 0) { - String index = indices.remove(randomInt(indices.size() - 1)); - logger.info(""--> deleting random index [{}]"", index); - internalCluster().wipeIndices(index); - } - } else if (chaosType < 6) { - // Randomly shutdown a node - if (cluster().size() > 1) { - logger.info(""--> shutting down random node""); - internalCluster().stopRandomDataNode(); - } - } else if (chaosType < 8) { - // Randomly create an index - String index = ""test-rand-"" + randomIndices; - logger.info(""--> creating random index [{}]"", index); - createTestIndex(index); - randomIndices++; - } else { - // Take a break - logger.info(""--> noop""); - } - } - - logger.info(""--> waiting for async indices creation to finish""); - for (int i = 0; i < asyncIndices; i++) { - asyncIndexThreads[i].join(); - } - - logger.info(""--> update index settings to back to normal""); - assertAcked(client().admin().indices().prepareUpdateSettings(""test-*"").setSettings(ImmutableSettings.builder() - .put(AbstractIndexStore.INDEX_STORE_THROTTLE_TYPE, ""node"") - )); - - // Make sure that snapshot finished - doesn't matter if it failed or succeeded - try { - CreateSnapshotResponse snapshotResponse = snapshotResponseFuture.get(); - SnapshotInfo snapshotInfo = snapshotResponse.getSnapshotInfo(); - assertNotNull(snapshotInfo); - logger.info(""--> snapshot is done with state [{}], total shards [{}], successful shards [{}]"", snapshotInfo.state(), snapshotInfo.totalShards(), snapshotInfo.successfulShards()); - } catch (Exception ex) { - logger.info(""--> snapshot didn't start properly"", ex); - } - - asyncNodesFuture.get(); - logger.info(""--> done""); - } - -" -250,1," public Principal authenticate(String username, String credentials) { - - // No user or no credentials - // Can't possibly authenticate, don't bother the database then - if (username == null || credentials == null) { - if (log.isDebugEnabled()) - log.debug(sm.getString(""memoryRealm.authenticateFailure"", username)); - return null; - } - - GenericPrincipal principal = principals.get(username); - - if(principal == null || principal.getPassword() == null) { - // User was not found in the database of the password was null - - if (log.isDebugEnabled()) - log.debug(sm.getString(""memoryRealm.authenticateFailure"", username)); - return null; - } - - boolean validated = getCredentialHandler().matches(credentials, principal.getPassword()); - - if (validated) { - if (log.isDebugEnabled()) - log.debug(sm.getString(""memoryRealm.authenticateSuccess"", username)); - return principal; - } else { - if (log.isDebugEnabled()) - log.debug(sm.getString(""memoryRealm.authenticateFailure"", username)); - return null; - } - } - - - // -------------------------------------------------------- Package Methods - - - /** - * Add a new user to the in-memory database. - * - * @param username User's username - * @param password User's password (clear text) - * @param roles Comma-delimited set of roles associated with this user - */ -" -251,1," public Object getValue(Object o) { - if ( location.getMember() == null ) { - return o; - } - else { - return ReflectionHelper.getValue( location.getMember(), o ); - } - } - - @Override -" -252,1," private String buildErrorMessage(Throwable e, Object[] args) { - String errorKey = ""struts.message.upload.error."" + e.getClass().getSimpleName(); - if (LOG.isDebugEnabled()) - LOG.debug(""Preparing error message for key: [#0]"", errorKey); - return LocalizedTextUtil.findText(this.getClass(), errorKey, defaultLocale, e.getMessage(), args); - } - - /** - * Build action message. - * - * @param e - * @param args - * @return - */ -" -253,1," private void resetContext() throws Exception { - // Restore the original state ( pre reading web.xml in start ) - // If you extend this - override this method and make sure to clean up - - // Don't reset anything that is read from a element since - // elements are read at initialisation will not be read - // again for this object - children = new HashMap(); - startupTime = 0; - startTime = 0; - tldScanTime = 0; - - // Bugzilla 32867 - distributable = false; - - applicationListeners = new String[0]; - applicationEventListenersObjects = new Object[0]; - applicationLifecycleListenersObjects = new Object[0]; - jspConfigDescriptor = new ApplicationJspConfigDescriptor(); - - initializers.clear(); - - if(log.isDebugEnabled()) - log.debug(""resetContext "" + getObjectName()); - } - - /** - * Return a String representation of this component. - */ - @Override -" -254,1," public void testRestoreToShadow() throws ExecutionException, InterruptedException { - Settings nodeSettings = nodeSettings(); - - internalCluster().startNodesAsync(3, nodeSettings).get(); - final Path dataPath = newTempDir().toPath(); - Settings idxSettings = ImmutableSettings.builder() - .put(IndexMetaData.SETTING_NUMBER_OF_SHARDS, 1) - .put(IndexMetaData.SETTING_NUMBER_OF_REPLICAS, 0).build(); - assertAcked(prepareCreate(""foo"").setSettings(idxSettings)); - ensureGreen(); - final int numDocs = randomIntBetween(10, 100); - for (int i = 0; i < numDocs; i++) { - client().prepareIndex(""foo"", ""doc"", """"+i).setSource(""foo"", ""bar"").get(); - } - assertNoFailures(client().admin().indices().prepareFlush().setForce(true).setWaitIfOngoing(true).execute().actionGet()); - - assertAcked(client().admin().cluster().preparePutRepository(""test-repo"") - .setType(""fs"").setSettings(ImmutableSettings.settingsBuilder() - .put(""location"", newTempDir().toPath()))); - CreateSnapshotResponse createSnapshotResponse = client().admin().cluster().prepareCreateSnapshot(""test-repo"", ""test-snap"").setWaitForCompletion(true).setIndices(""foo"").get(); - assertThat(createSnapshotResponse.getSnapshotInfo().successfulShards(), greaterThan(0)); - assertThat(createSnapshotResponse.getSnapshotInfo().successfulShards(), equalTo(createSnapshotResponse.getSnapshotInfo().totalShards())); - assertThat(client().admin().cluster().prepareGetSnapshots(""test-repo"").setSnapshots(""test-snap"").get().getSnapshots().get(0).state(), equalTo(SnapshotState.SUCCESS)); - - Settings shadowSettings = ImmutableSettings.builder() - .put(IndexMetaData.SETTING_DATA_PATH, dataPath.toAbsolutePath().toString()) - .put(IndexMetaData.SETTING_SHADOW_REPLICAS, true) - .put(IndexMetaData.SETTING_SHARED_FILESYSTEM, true) - .put(IndexMetaData.SETTING_NUMBER_OF_REPLICAS, 2).build(); - - logger.info(""--> restore the index into shadow replica index""); - RestoreSnapshotResponse restoreSnapshotResponse = client().admin().cluster().prepareRestoreSnapshot(""test-repo"", ""test-snap"") - .setIndexSettings(shadowSettings).setWaitForCompletion(true) - .setRenamePattern(""(.+)"").setRenameReplacement(""$1-copy"") - .execute().actionGet(); - assertThat(restoreSnapshotResponse.getRestoreInfo().totalShards(), greaterThan(0)); - ensureGreen(); - refresh(); - - for (IndicesService service : internalCluster().getDataNodeInstances(IndicesService.class)) { - if (service.hasIndex(""foo-copy"")) { - IndexShard shard = service.indexServiceSafe(""foo-copy"").shard(0); - if (shard.routingEntry().primary()) { - assertFalse(shard instanceof ShadowIndexShard); - } else { - assertTrue(shard instanceof ShadowIndexShard); - } - } - } - logger.info(""--> performing query""); - SearchResponse resp = client().prepareSearch(""foo-copy"").setQuery(matchAllQuery()).get(); - assertHitCount(resp, numDocs); - - } - - @Test -" -255,1," public KeyPair generateKeyPair() - { - if (!initialised) - { - DSAParametersGenerator pGen = new DSAParametersGenerator(); - - pGen.init(strength, certainty, random); - param = new DSAKeyGenerationParameters(random, pGen.generateParameters()); - engine.init(param); - initialised = true; - } - - AsymmetricCipherKeyPair pair = engine.generateKeyPair(); - DSAPublicKeyParameters pub = (DSAPublicKeyParameters)pair.getPublic(); - DSAPrivateKeyParameters priv = (DSAPrivateKeyParameters)pair.getPrivate(); - - return new KeyPair(new BCDSAPublicKey(pub), new BCDSAPrivateKey(priv)); - } -" -256,1," public void testInvalidate() throws IOException { - ProjectWorkspace workspace = - TestDataHelper.createProjectWorkspaceForScenario(this, ""parser_with_cell"", tmp); - workspace.setUp(); - - // Warm the parser cache. - TestContext context = new TestContext(); - ProcessResult runBuckResult = - workspace.runBuckdCommand(context, ""query"", ""deps(//Apps:TestAppsLibrary)""); - runBuckResult.assertSuccess(); - assertThat( - runBuckResult.getStdout(), - Matchers.containsString( - ""//Apps:TestAppsLibrary\n"" - + ""//Libraries/Dep1:Dep1_1\n"" - + ""//Libraries/Dep1:Dep1_2\n"" - + ""bar//Dep2:Dep2"")); - - // Save the parser cache to a file. - NamedTemporaryFile tempFile = new NamedTemporaryFile(""parser_data"", null); - runBuckResult = - workspace.runBuckdCommand(context, ""parser-cache"", ""--save"", tempFile.get().toString()); - runBuckResult.assertSuccess(); - - // Write an empty content to Apps/BUCK. - Path path = tmp.getRoot().resolve(""Apps/BUCK""); - byte[] data = {}; - Files.write(path, data); - - // Write an empty content to Apps/BUCK. - Path invalidationJsonPath = tmp.getRoot().resolve(""invalidation-data.json""); - String jsonData = ""[{\""path\"":\""Apps/BUCK\"",\""status\"":\""M\""}]""; - Files.write(invalidationJsonPath, jsonData.getBytes(StandardCharsets.UTF_8)); - - context = new TestContext(); - // Load the parser cache to a new buckd context. - runBuckResult = - workspace.runBuckdCommand( - context, - ""parser-cache"", - ""--load"", - tempFile.get().toString(), - ""--changes"", - invalidationJsonPath.toString()); - runBuckResult.assertSuccess(); - - // Perform the query again. - try { - workspace.runBuckdCommand(context, ""query"", ""deps(//Apps:TestAppsLibrary)""); - } catch (HumanReadableException e) { - assertThat( - e.getMessage(), Matchers.containsString(""//Apps:TestAppsLibrary could not be found"")); - } - } -" -257,1," public void send(final String format, final Object... args) { - descriptor.debug(logger, format, args); - } - } - final Debug debug = new Debug(); - Set users = RecipientProviderUtilities.getChangeSetAuthors(Collections.>singleton(context.getRun()), debug); - RecipientProviderUtilities.addUsers(users, context.getListener(), env, to, cc, bcc, debug); - } - - @Extension - public static final class DescriptorImpl extends RecipientProviderDescriptor { - @Override - public String getDisplayName() { - return ""Developers""; - } - } -} -" -258,1," public void testRejectBindWithDNButNoPassword() - throws Exception - { - if (! isDirectoryInstanceAvailable()) - { - return; - } - - LDAPConnection conn = getUnauthenticatedConnection(); - SimpleBindRequest bindRequest = new SimpleBindRequest(getTestBindDN(), """"); - - try - { - bindRequest.process(conn, 1); - fail(""Expected an exception when binding with a DN but no password""); - } - catch (LDAPException le) - { - assertEquals(le.getResultCode(), ResultCode.PARAM_ERROR); - } - - - // Reconfigure the connection so that it will allow binds with a DN but no - // password. - conn.getConnectionOptions().setBindWithDNRequiresPassword(false); - try - { - bindRequest.process(conn, 1); - } - catch (LDAPException le) - { - // The server will still likely reject the operation, but we should at - // least verify that it wasn't a parameter error. - assertFalse(le.getResultCode() == ResultCode.PARAM_ERROR); - } - - conn.getConnectionOptions().setBindWithDNRequiresPassword(true); - conn.close(); - } -" -259,1," public LockoutPolicy getLockoutPolicy() { - LockoutPolicy res = IdentityZoneHolder.get().getConfig().getClientLockoutPolicy(); - return res.getLockoutAfterFailures() != -1 ? res : defaultLockoutPolicy; - } - - @Override -" -260,1," private void detectJPA() { - // check whether we have Persistence on the classpath - Class persistenceClass; - try { - persistenceClass = run( LoadClass.action( PERSISTENCE_CLASS_NAME, this.getClass() ) ); - } - catch ( ValidationException e ) { - log.debugf( - ""Cannot find %s on classpath. Assuming non JPA 2 environment. All properties will per default be traversable."", - PERSISTENCE_CLASS_NAME - ); - return; - } - - // check whether Persistence contains getPersistenceUtil - Method persistenceUtilGetter = run( GetMethod.action( persistenceClass, PERSISTENCE_UTIL_METHOD ) ); - if ( persistenceUtilGetter == null ) { - log.debugf( - ""Found %s on classpath, but no method '%s'. Assuming JPA 1 environment. All properties will per default be traversable."", - PERSISTENCE_CLASS_NAME, - PERSISTENCE_UTIL_METHOD - ); - return; - } - - // try to invoke the method to make sure that we are dealing with a complete JPA2 implementation - // unfortunately there are several incomplete implementations out there (see HV-374) - try { - Object persistence = run( NewInstance.action( persistenceClass, ""persistence provider"" ) ); - ReflectionHelper.getValue(persistenceUtilGetter, persistence ); - } - catch ( Exception e ) { - log.debugf( - ""Unable to invoke %s.%s. Inconsistent JPA environment. All properties will per default be traversable."", - PERSISTENCE_CLASS_NAME, - PERSISTENCE_UTIL_METHOD - ); - } - - log.debugf( - ""Found %s on classpath containing '%s'. Assuming JPA 2 environment. Trying to instantiate JPA aware TraversableResolver"", - PERSISTENCE_CLASS_NAME, - PERSISTENCE_UTIL_METHOD - ); - - try { - @SuppressWarnings(""unchecked"") - Class jpaAwareResolverClass = (Class) - run( LoadClass.action( JPA_AWARE_TRAVERSABLE_RESOLVER_CLASS_NAME, this.getClass() ) ); - jpaTraversableResolver = run( NewInstance.action( jpaAwareResolverClass, """" ) ); - log.debugf( - ""Instantiated JPA aware TraversableResolver of type %s."", JPA_AWARE_TRAVERSABLE_RESOLVER_CLASS_NAME - ); - } - catch ( ValidationException e ) { - log.debugf( - ""Unable to load or instantiate JPA aware resolver %s. All properties will per default be traversable."", - JPA_AWARE_TRAVERSABLE_RESOLVER_CLASS_NAME - ); - } - } - - @Override -" -261,1," public void addRecipients(final ExtendedEmailPublisherContext context, EnvVars env, Set to, Set cc, Set 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(); - Run run = context.getRun(); - final Result runResult = run.getResult(); - if (run instanceof AbstractBuild) { - Set users = ((AbstractBuild)run).getCulprits(); - RecipientProviderUtilities.addUsers(users, context.getListener(), env, to, cc, bcc, debug); - } else if (runResult != null) { - List> builds = new ArrayList<>(); - Run build = run; - builds.add(build); - build = build.getPreviousCompletedBuild(); - while (build != null) { - final Result buildResult = build.getResult(); - if (buildResult != null) { - if (buildResult.isWorseThan(Result.SUCCESS)) { - debug.send(""Including build %s with status %s"", build.getId(), buildResult); - builds.add(build); - } else { - break; - } - } - build = build.getPreviousCompletedBuild(); - } - Set users = RecipientProviderUtilities.getChangeSetAuthors(builds, debug); - RecipientProviderUtilities.addUsers(users, context.getListener(), env, to, cc, bcc, debug); - } - } - - @Extension -" -262,1," protected boolean isProbablePrime(BigInteger x) - { - /* - * Primes class for FIPS 186-4 C.3 primality checking - */ - return !Primes.hasAnySmallFactors(x) && Primes.isMRProbablePrime(x, param.getRandom(), iterations); - } - -" -263,1," public void batchingShardUpdateTaskTest() throws Exception { - - final Client client = client(); - - logger.info(""--> creating repository""); - assertAcked(client.admin().cluster().preparePutRepository(""test-repo"") - .setType(""fs"").setSettings(ImmutableSettings.settingsBuilder() - .put(""location"", newTempDir()) - .put(""compress"", randomBoolean()) - .put(""chunk_size"", randomIntBetween(100, 1000)))); - - assertAcked(prepareCreate(""test-idx"", 0, settingsBuilder().put(""number_of_shards"", between(1, 20)) - .put(""number_of_replicas"", 0))); - ensureGreen(); - - logger.info(""--> indexing some data""); - final int numdocs = randomIntBetween(10, 100); - IndexRequestBuilder[] builders = new IndexRequestBuilder[numdocs]; - for (int i = 0; i < builders.length; i++) { - builders[i] = client().prepareIndex(""test-idx"", ""type1"", Integer.toString(i)).setSource(""field1"", ""bar "" + i); - } - indexRandom(true, builders); - flushAndRefresh(); - - final int numberOfShards = getNumShards(""test-idx"").numPrimaries; - logger.info(""number of shards: {}"", numberOfShards); - - final ClusterService clusterService = internalCluster().clusterService(internalCluster().getMasterName()); - BlockingClusterStateListener snapshotListener = new BlockingClusterStateListener(clusterService, ""update_snapshot ["", ""update snapshot state"", Priority.HIGH); - try { - clusterService.addFirst(snapshotListener); - logger.info(""--> snapshot""); - ListenableActionFuture snapshotFuture = client.admin().cluster().prepareCreateSnapshot(""test-repo"", ""test-snap"").setWaitForCompletion(true).setIndices(""test-idx"").execute(); - - // Await until shard updates are in pending state. - assertBusyPendingTasks(""update snapshot state"", numberOfShards); - snapshotListener.unblock(); - - // Check that the snapshot was successful - CreateSnapshotResponse createSnapshotResponse = snapshotFuture.actionGet(); - assertEquals(SnapshotState.SUCCESS, createSnapshotResponse.getSnapshotInfo().state()); - assertEquals(numberOfShards, createSnapshotResponse.getSnapshotInfo().totalShards()); - assertEquals(numberOfShards, createSnapshotResponse.getSnapshotInfo().successfulShards()); - - } finally { - clusterService.remove(snapshotListener); - } - - // Check that we didn't timeout - assertFalse(snapshotListener.timedOut()); - // Check that cluster state update task was called only once - assertEquals(1, snapshotListener.count()); - - logger.info(""--> close indices""); - client.admin().indices().prepareClose(""test-idx"").get(); - - BlockingClusterStateListener restoreListener = new BlockingClusterStateListener(clusterService, ""restore_snapshot["", ""update snapshot state"", Priority.HIGH); - - try { - clusterService.addFirst(restoreListener); - logger.info(""--> restore snapshot""); - ListenableActionFuture futureRestore = client.admin().cluster().prepareRestoreSnapshot(""test-repo"", ""test-snap"").setWaitForCompletion(true).execute(); - - // Await until shard updates are in pending state. - assertBusyPendingTasks(""update snapshot state"", numberOfShards); - restoreListener.unblock(); - - RestoreSnapshotResponse restoreSnapshotResponse = futureRestore.actionGet(); - assertThat(restoreSnapshotResponse.getRestoreInfo().totalShards(), equalTo(numberOfShards)); - - } finally { - clusterService.remove(restoreListener); - } - - // Check that we didn't timeout - assertFalse(restoreListener.timedOut()); - // Check that cluster state update task was called only once - assertEquals(1, restoreListener.count()); - } - -" -264,1," private File getLocationUnderBuild(AbstractBuild build) { - return new File(build.getRootDir(), ""fileParameters/"" + location); - } - - /** - * Default implementation from {@link File}. - */ -" -265,1," protected Details authenticate(String username, String password) throws AuthenticationException { - Details u = loadUserByUsername(username); - if (!u.isPasswordCorrect(password)) - throw new BadCredentialsException(""Failed to login as ""+username); - return u; - } - - /** - * Show the sign up page with the data from the identity. - */ - @Override -" -266,1," public void resetPassword_InvalidPasswordException_NewPasswordSameAsOld() { - ScimUser user = new ScimUser(""user-id"", ""username"", ""firstname"", ""lastname""); - user.setMeta(new ScimMeta(new Date(), new Date(), 0)); - user.setPrimaryEmail(""foo@example.com""); - ExpiringCode expiringCode = new ExpiringCode(""good_code"", - new Timestamp(System.currentTimeMillis() + UaaResetPasswordService.PASSWORD_RESET_LIFETIME), ""user-id"", null); - when(codeStore.retrieveCode(""good_code"")).thenReturn(expiringCode); - when(scimUserProvisioning.retrieve(""user-id"")).thenReturn(user); - when(scimUserProvisioning.checkPasswordMatches(""user-id"", ""Passwo3dAsOld"")) - .thenThrow(new InvalidPasswordException(""Your new password cannot be the same as the old password."", UNPROCESSABLE_ENTITY)); - SecurityContext securityContext = mock(SecurityContext.class); - when(securityContext.getAuthentication()).thenReturn(new MockAuthentication()); - SecurityContextHolder.setContext(securityContext); - try { - emailResetPasswordService.resetPassword(""good_code"", ""Passwo3dAsOld""); - fail(); - } catch (InvalidPasswordException e) { - assertEquals(""Your new password cannot be the same as the old password."", e.getMessage()); - assertEquals(UNPROCESSABLE_ENTITY, e.getStatus()); - } - } - - @Test -" -267,1," public boolean getValidateClientProvidedNewSessionId() { return false; } -" -268,1," protected Http11AprProcessor createProcessor() { - Http11AprProcessor processor = new Http11AprProcessor( - proto.getMaxHttpHeaderSize(), (AprEndpoint)proto.endpoint, - proto.getMaxTrailerSize()); - processor.setAdapter(proto.getAdapter()); - processor.setMaxKeepAliveRequests(proto.getMaxKeepAliveRequests()); - processor.setKeepAliveTimeout(proto.getKeepAliveTimeout()); - processor.setConnectionUploadTimeout( - proto.getConnectionUploadTimeout()); - processor.setDisableUploadTimeout(proto.getDisableUploadTimeout()); - processor.setCompressionMinSize(proto.getCompressionMinSize()); - processor.setCompression(proto.getCompression()); - processor.setNoCompressionUserAgents(proto.getNoCompressionUserAgents()); - processor.setCompressableMimeTypes(proto.getCompressableMimeTypes()); - processor.setRestrictedUserAgents(proto.getRestrictedUserAgents()); - processor.setSocketBuffer(proto.getSocketBuffer()); - processor.setMaxSavePostSize(proto.getMaxSavePostSize()); - processor.setServer(proto.getServer()); - processor.setClientCertProvider(proto.getClientCertProvider()); - register(processor); - return processor; - } - - @Override -" -269,1," public synchronized Servlet loadServlet() throws ServletException { - - // Nothing to do if we already have an instance or an instance pool - if (!singleThreadModel && (instance != null)) - return instance; - - PrintStream out = System.out; - if (swallowOutput) { - SystemLogHandler.startCapture(); - } - - Servlet servlet; - try { - long t1=System.currentTimeMillis(); - // Complain if no servlet class has been specified - if (servletClass == null) { - unavailable(null); - throw new ServletException - (sm.getString(""standardWrapper.notClass"", getName())); - } - - InstanceManager instanceManager = ((StandardContext)getParent()).getInstanceManager(); - try { - servlet = (Servlet) instanceManager.newInstance(servletClass); - } catch (ClassCastException e) { - unavailable(null); - // Restore the context ClassLoader - throw new ServletException - (sm.getString(""standardWrapper.notServlet"", servletClass), e); - } catch (Throwable e) { - ExceptionUtils.handleThrowable(e); - unavailable(null); - - // Added extra log statement for Bugzilla 36630: - // http://issues.apache.org/bugzilla/show_bug.cgi?id=36630 - if(log.isDebugEnabled()) { - log.debug(sm.getString(""standardWrapper.instantiate"", servletClass), e); - } - - // Restore the context ClassLoader - throw new ServletException - (sm.getString(""standardWrapper.instantiate"", servletClass), e); - } - - if (multipartConfigElement == null) { - MultipartConfig annotation = - servlet.getClass().getAnnotation(MultipartConfig.class); - if (annotation != null) { - multipartConfigElement = - new MultipartConfigElement(annotation); - } - } - - ServletSecurity secAnnotation = - servlet.getClass().getAnnotation(ServletSecurity.class); - Context ctxt = (Context) getParent(); - if (secAnnotation != null) { - ctxt.addServletSecurity( - new ApplicationServletRegistration(this, ctxt), - new ServletSecurityElement(secAnnotation)); - } - - - // Special handling for ContainerServlet instances - if ((servlet instanceof ContainerServlet) && - (isContainerProvidedServlet(servletClass) || - ctxt.getPrivileged() )) { - ((ContainerServlet) servlet).setWrapper(this); - } - - classLoadTime=(int) (System.currentTimeMillis() -t1); - - initServlet(servlet); - - // Register our newly initialized instance - singleThreadModel = servlet instanceof SingleThreadModel; - if (singleThreadModel) { - if (instancePool == null) - instancePool = new Stack(); - } - fireContainerEvent(""load"", this); - - loadTime=System.currentTimeMillis() -t1; - } finally { - if (swallowOutput) { - String log = SystemLogHandler.stopCapture(); - if (log != null && log.length() > 0) { - if (getServletContext() != null) { - getServletContext().log(log); - } else { - out.println(log); - } - } - } - } - return servlet; - - } - -" -270,1," public void testWelcomeFileStrict() throws Exception { - - Tomcat tomcat = getTomcatInstance(); - - File appDir = new File(""test/webapp""); - - StandardContext ctxt = (StandardContext) tomcat.addWebapp(null, ""/test"", - appDir.getAbsolutePath()); - ctxt.setReplaceWelcomeFiles(true); - ctxt.addWelcomeFile(""index.jsp""); - // Mapping for *.do is defined in web.xml - ctxt.addWelcomeFile(""index.do""); - - // Simulate STRICT_SERVLET_COMPLIANCE - ctxt.setResourceOnlyServlets(""""); - - tomcat.start(); - ByteChunk bc = new ByteChunk(); - int rc = getUrl(""http://localhost:"" + getPort() + - ""/test/welcome-files"", bc, new HashMap>()); - Assert.assertEquals(HttpServletResponse.SC_OK, rc); - Assert.assertTrue(bc.toString().contains(""JSP"")); - - rc = getUrl(""http://localhost:"" + getPort() + - ""/test/welcome-files/sub"", bc, - new HashMap>()); - Assert.assertEquals(HttpServletResponse.SC_NOT_FOUND, rc); - } - - /** - * Prepare a string to search in messages that contain a timestamp, when it - * is known that the timestamp was printed between {@code timeA} and - * {@code timeB}. - */ -" -271,1," protected void stripScopesFromAuthentication(String identityZoneId, HttpServletRequest servletRequest) { - OAuth2Authentication oa = (OAuth2Authentication)SecurityContextHolder.getContext().getAuthentication(); - - Object oaDetails = oa.getDetails(); - - //strip client scopes - OAuth2Request request = oa.getOAuth2Request(); - Collection requestAuthorities = UaaStringUtils.getStringsFromAuthorities(request.getAuthorities()); - Set clientScopes = new HashSet<>(); - Set clientAuthorities = new HashSet<>(); - for (String s : getZoneSwitchingScopes(identityZoneId)) { - String scope = stripPrefix(s, identityZoneId); - if (request.getScope().contains(s)) { - clientScopes.add(scope); - } - if (requestAuthorities.contains(s)) { - clientAuthorities.add(scope); - } - } - request = new OAuth2Request( - request.getRequestParameters(), - request.getClientId(), - UaaStringUtils.getAuthoritiesFromStrings(clientAuthorities), - request.isApproved(), - clientScopes, - request.getResourceIds(), - request.getRedirectUri(), - request.getResponseTypes(), - request.getExtensions() - ); - - - UaaAuthentication userAuthentication = (UaaAuthentication)oa.getUserAuthentication(); - if (userAuthentication!=null) { - userAuthentication = new UaaAuthentication( - userAuthentication.getPrincipal(), - null, - UaaStringUtils.getAuthoritiesFromStrings(clientScopes), - new UaaAuthenticationDetails(servletRequest), - true); - } - oa = new OAuth2Authentication(request, userAuthentication); - oa.setDetails(oaDetails); - SecurityContextHolder.getContext().setAuthentication(oa); - } - -" -272,1," public void testHandleNoInitialResponseNull() throws Exception - { - final AuthenticationResult result = _negotiator.handleResponse(null); - assertEquals(""Unexpected authentication status"", AuthenticationResult.AuthenticationStatus.CONTINUE, result.getStatus()); - assertArrayEquals(""Unexpected authentication challenge"", new byte[0], result.getChallenge()); - - final AuthenticationResult firstResult = _negotiator.handleResponse(VALID_RESPONSE.getBytes()); - assertEquals(""Unexpected first authentication result"", _expectedResult, firstResult); - } -" -273,1," private int readStored(final byte[] buffer, final int offset, final int length) throws IOException { - - if (current.hasDataDescriptor) { - if (lastStoredEntry == null) { - readStoredEntry(); - } - return lastStoredEntry.read(buffer, offset, length); - } - - final long csize = current.entry.getSize(); - if (current.bytesRead >= csize) { - return -1; - } - - if (buf.position() >= buf.limit()) { - buf.position(0); - final int l = in.read(buf.array()); - if (l == -1) { - return -1; - } - buf.limit(l); - - count(l); - current.bytesReadFromStream += l; - } - - int toRead = Math.min(buf.remaining(), length); - if ((csize - current.bytesRead) < toRead) { - // if it is smaller than toRead then it fits into an int - toRead = (int) (csize - current.bytesRead); - } - buf.get(buffer, offset, toRead); - current.bytesRead += toRead; - return toRead; - } - - /** - * Implementation of read for DEFLATED entries. - */ -" -274,1," private Object readResolve() { - return INSTANCE; - } - -" -275,1," private static ZipOutputStream getZipOutputStream(OutputStream out, Charset charset) { - charset = (null == charset) ? DEFAULT_CHARSET : charset; - return new ZipOutputStream(out, charset); - } - - /** - * 递归压缩文件夹 - * - * @param out 压缩文件存储对象 - * @param srcRootDir 压缩文件夹根目录的子路径 - * @param file 当前递归压缩的文件或目录对象 - * @throws UtilException IO异常 - */ -" -276,1," public boolean isFinished() { - return endChunk; - } -" -277,1," public Object compile(String expression) throws OgnlException { - if (enableExpressionCache) { - Object o = expressions.get(expression); - if (o == null) { - o = Ognl.parseExpression(expression); - expressions.putIfAbsent(expression, o); - } - return o; - } else - return Ognl.parseExpression(expression); - } - - /** - * Copies the properties in the object ""from"" and sets them in the object ""to"" - * using specified type converter, or {@link com.opensymphony.xwork2.conversion.impl.XWorkConverter} if none - * is specified. - * - * @param from the source object - * @param to the target object - * @param context the action context we're running under - * @param exclusions collection of method names to excluded from copying ( can be null) - * @param inclusions collection of method names to included copying (can be null) - * note if exclusions AND inclusions are supplied and not null nothing will get copied. - */ -" -278,1," String hash(String plaintext, String salt, int iterations) throws EncryptionException; - - /** - * Encrypts the provided plaintext and returns a ciphertext string using the - * master secret key and default cipher transformation. - *

- * Compatibility with earlier ESAPI versions: The symmetric encryption - * in ESAPI 2.0 and later is not compatible with the encryption in ESAPI 1.4 - * or earlier. Not only are the interfaces slightly different, but they format - * of the serialized encrypted data is incompatible. Therefore, if you have - * encrypted data with ESAPI 1.4 or earlier, you must first encrypt it and - * then re-encrypt it with ESAPI 2.0. Backward compatibility with ESAPI 1.4 - * was proposed to both the ESAPI Developers and ESAPI Users mailing lists - * and voted down. More details are available in the ESAPI document - * - * Why Is OWASP Changing ESAPI Encryption? - *

- * Why this method is deprecated: Most cryptographers strongly suggest - * that if you are creating crypto functionality for general-purpose use, - * at a minimum you should ensure that it provides authenticity, integrity, - * and confidentiality. This method only provides confidentiality, but not - * authenticity or integrity. Therefore, you are encouraged to use - * one of the other encryption methods referenced below. Because this - * method provides neither authenticity nor integrity, it may be - * removed in some future ESAPI Java release. Note: there are some cases - * where authenticity / integrity are not that important. For instance, consider - * a case where the encrypted data is never out of your application's control. For - * example, if you receive data that your application is encrypting itself and then - * storing the encrypted data in its own database for later use (and no other - * applications can query or update that column of the database), providing - * confidentiality alone might be sufficient. However, if there are cases - * where your application will be sending or receiving already encrypted data - * over an insecure, unauthenticated channel, in such cases authenticity and - * integrity of the encrypted data likely is important and this method should - * be avoided in favor of one of the other two. - * - * @param plaintext - * the plaintext {@code String} to encrypt. Note that if you are encrypting - * general bytes, you should encypt that byte array to a String using - * ""UTF-8"" encoding. - * - * @return - * the encrypted, base64-encoded String representation of 'plaintext' plus - * the random IV used. - * - * @throws EncryptionException - * if the specified encryption algorithm could not be found or another problem exists with - * the encryption of 'plaintext' - * - * @see #encrypt(PlainText) - * @see #encrypt(SecretKey, PlainText) - * - * @deprecated As of 1.4.2; use {@link #encrypt(PlainText)} instead, which - * also ensures message authenticity. This method will be - * completely removed as of the next major release or point - * release (3.0 or 2.1, whichever comes first) as per OWASP - * deprecation policy. - */ -" -279,1," public void handleDialog(ActionRequest req, ActionResponse resp) throws IOException, PortletException { - List lines = new ArrayList(); - req.getPortletSession().setAttribute(""lines"", lines); - - lines.add(""handling dialog""); - StringBuilder txt = new StringBuilder(128); - - String clr = req.getActionParameters().getValue(""color""); - txt.append(""Color: "").append(clr); - lines.add(txt.toString()); - LOGGER.fine(txt.toString()); - - resp.getRenderParameters().setValue(""color"", clr); - - txt.setLength(0); - Part part = null; - try { - part = req.getPart(""file""); - } catch (Throwable t) {} - - if ((part != null) && (part.getSubmittedFileName() != null) && - (part.getSubmittedFileName().length() > 0)) { - txt.append(""Uploaded file name: "").append(part.getSubmittedFileName()); - txt.append("", part name: "").append(part.getName()); - txt.append("", size: "").append(part.getSize()); - txt.append("", content type: "").append(part.getContentType()); - lines.add(txt.toString()); - LOGGER.fine(txt.toString()); - txt.setLength(0); - txt.append(""Headers: ""); - String sep = """"; - for (String hdrname : part.getHeaderNames()) { - txt.append(sep).append(hdrname).append(""="").append(part.getHeaders(hdrname)); - sep = "", ""; - } - lines.add(txt.toString()); - LOGGER.fine(txt.toString()); - - // Store the file in a temporary location in the webapp where it can be served. - // Note that this is, in general, not what you want to do in production, as - // there can be problems serving the resource. Did it this way for a - // quick solution that doesn't require additional Tomcat configuration. - - try { - String path = req.getPortletContext().getRealPath(TMP); - File dir = new File(path); - lines.add(""Temp path: "" + dir.getCanonicalPath()); - if (!dir.exists()) { - lines.add(""Creating directory. Path: "" + dir.getCanonicalPath()); - Files.createDirectories(dir.toPath()); - } - String fn = TMP + part.getSubmittedFileName(); - lines.add(""Temp file: "" + fn); - path = req.getPortletContext().getRealPath(fn); - File img = new File(path); - if (img.exists()) { - lines.add(""deleting existing temp file.""); - img.delete(); - } - InputStream is = part.getInputStream(); - Files.copy(is, img.toPath(), StandardCopyOption.REPLACE_EXISTING); - - resp.getRenderParameters().setValue(""fn"", fn); - resp.getRenderParameters().setValue(""ct"", part.getContentType()); - - } catch (Exception e) { - lines.add(""Exception doing I/O: "" + e.toString()); - } - } else { - lines.add(""file part was null""); - } - - } - - @RenderMethod(portletNames = ""MultipartPortlet"") -" -280,1," protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) - throws ServletException, IOException { - - HttpServletRequest requestToUse = request; - - if (""POST"".equals(request.getMethod()) && request.getAttribute(WebUtils.ERROR_EXCEPTION_ATTRIBUTE) == null) { - String paramValue = request.getParameter(this.methodParam); - if (StringUtils.hasLength(paramValue)) { - requestToUse = new HttpMethodRequestWrapper(request, paramValue); - } - } - - filterChain.doFilter(requestToUse, response); - } - - - /** - * Simple {@link HttpServletRequest} wrapper that returns the supplied method for - * {@link HttpServletRequest#getMethod()}. - */ -" -281,1," private ScimGroupExternalMember getExternalGroupMap(final String groupId, - final String externalGroup, - final String origin) - throws ScimResourceNotFoundException { - try { - ScimGroupExternalMember u = jdbcTemplate.queryForObject(GET_GROUPS_WITH_EXTERNAL_GROUP_MAPPINGS_SQL, - rowMapper, groupId, origin, externalGroup); - return u; - } catch (EmptyResultDataAccessException e) { - throw new ScimResourceNotFoundException(""The mapping between groupId "" + groupId + "" and external group "" - + externalGroup + "" does not exist""); - } - } - -" -282,1," protected void serveResource(HttpServletRequest request, - HttpServletResponse response, - boolean content, - String encoding) - throws IOException, ServletException { - - boolean serveContent = content; - - // Identify the requested resource path - String path = getRelativePath(request); - if (debug > 0) { - if (serveContent) - log(""DefaultServlet.serveResource: Serving resource '"" + - path + ""' headers and data""); - else - log(""DefaultServlet.serveResource: Serving resource '"" + - path + ""' headers only""); - } - - WebResource resource = resources.getResource(path); - - if (!resource.exists()) { - // Check if we're included so we can return the appropriate - // missing resource name in the error - String requestUri = (String) request.getAttribute( - RequestDispatcher.INCLUDE_REQUEST_URI); - if (requestUri == null) { - requestUri = request.getRequestURI(); - } else { - // We're included - // SRV.9.3 says we must throw a FNFE - throw new FileNotFoundException(sm.getString( - ""defaultServlet.missingResource"", requestUri)); - } - - response.sendError(HttpServletResponse.SC_NOT_FOUND, requestUri); - return; - } - - if (!resource.canRead()) { - // Check if we're included so we can return the appropriate - // missing resource name in the error - String requestUri = (String) request.getAttribute( - RequestDispatcher.INCLUDE_REQUEST_URI); - if (requestUri == null) { - requestUri = request.getRequestURI(); - } else { - // We're included - // Spec doesn't say what to do in this case but a FNFE seems - // reasonable - throw new FileNotFoundException(sm.getString( - ""defaultServlet.missingResource"", requestUri)); - } - - response.sendError(HttpServletResponse.SC_FORBIDDEN, requestUri); - return; - } - - // If the resource is not a collection, and the resource path - // ends with ""/"" or ""\"", return NOT FOUND - if (resource.isFile() && (path.endsWith(""/"") || path.endsWith(""\\""))) { - // Check if we're included so we can return the appropriate - // missing resource name in the error - String requestUri = (String) request.getAttribute( - RequestDispatcher.INCLUDE_REQUEST_URI); - if (requestUri == null) { - requestUri = request.getRequestURI(); - } - response.sendError(HttpServletResponse.SC_NOT_FOUND, requestUri); - return; - } - - boolean isError = response.getStatus() >= HttpServletResponse.SC_BAD_REQUEST; - - boolean included = false; - // Check if the conditions specified in the optional If headers are - // satisfied. - if (resource.isFile()) { - // Checking If headers - included = (request.getAttribute( - RequestDispatcher.INCLUDE_CONTEXT_PATH) != null); - if (!included && !isError && !checkIfHeaders(request, response, resource)) { - return; - } - } - - // Find content type. - String contentType = resource.getMimeType(); - if (contentType == null) { - contentType = getServletContext().getMimeType(resource.getName()); - resource.setMimeType(contentType); - } - - // These need to reflect the original resource, not the potentially - // gzip'd version of the resource so get them now if they are going to - // be needed later - String eTag = null; - String lastModifiedHttp = null; - if (resource.isFile() && !isError) { - eTag = resource.getETag(); - lastModifiedHttp = resource.getLastModifiedHttp(); - } - - - // Serve a gzipped version of the file if present - boolean usingGzippedVersion = false; - if (gzip && !included && resource.isFile() && !path.endsWith("".gz"")) { - WebResource gzipResource = resources.getResource(path + "".gz""); - if (gzipResource.exists() && gzipResource.isFile()) { - Collection varyHeaders = response.getHeaders(""Vary""); - boolean addRequired = true; - for (String varyHeader : varyHeaders) { - if (""*"".equals(varyHeader) || - ""accept-encoding"".equalsIgnoreCase(varyHeader)) { - addRequired = false; - break; - } - } - if (addRequired) { - response.addHeader(""Vary"", ""accept-encoding""); - } - if (checkIfGzip(request)) { - response.addHeader(""Content-Encoding"", ""gzip""); - resource = gzipResource; - usingGzippedVersion = true; - } - } - } - - ArrayList ranges = null; - long contentLength = -1L; - - if (resource.isDirectory()) { - // Skip directory listings if we have been configured to - // suppress them - if (!listings) { - response.sendError(HttpServletResponse.SC_NOT_FOUND, - request.getRequestURI()); - return; - } - contentType = ""text/html;charset=UTF-8""; - } else { - if (!isError) { - if (useAcceptRanges) { - // Accept ranges header - response.setHeader(""Accept-Ranges"", ""bytes""); - } - - // Parse range specifier - ranges = parseRange(request, response, resource); - - // ETag header - response.setHeader(""ETag"", eTag); - - // Last-Modified header - response.setHeader(""Last-Modified"", lastModifiedHttp); - } - - // Get content length - contentLength = resource.getContentLength(); - // Special case for zero length files, which would cause a - // (silent) ISE when setting the output buffer size - if (contentLength == 0L) { - serveContent = false; - } - } - - ServletOutputStream ostream = null; - PrintWriter writer = null; - - if (serveContent) { - // Trying to retrieve the servlet output stream - try { - ostream = response.getOutputStream(); - } catch (IllegalStateException e) { - // If it fails, we try to get a Writer instead if we're - // trying to serve a text file - if (!usingGzippedVersion && - ((contentType == null) || - (contentType.startsWith(""text"")) || - (contentType.endsWith(""xml"")) || - (contentType.contains(""/javascript""))) - ) { - writer = response.getWriter(); - // Cannot reliably serve partial content with a Writer - ranges = FULL; - } else { - throw e; - } - } - } - - // Check to see if a Filter, Valve of wrapper has written some content. - // If it has, disable range requests and setting of a content length - // since neither can be done reliably. - ServletResponse r = response; - long contentWritten = 0; - while (r instanceof ServletResponseWrapper) { - r = ((ServletResponseWrapper) r).getResponse(); - } - if (r instanceof ResponseFacade) { - contentWritten = ((ResponseFacade) r).getContentWritten(); - } - if (contentWritten > 0) { - ranges = FULL; - } - - if (resource.isDirectory() || - isError || - ( (ranges == null || ranges.isEmpty()) - && request.getHeader(""Range"") == null ) || - ranges == FULL ) { - - // Set the appropriate output headers - if (contentType != null) { - if (debug > 0) - log(""DefaultServlet.serveFile: contentType='"" + - contentType + ""'""); - response.setContentType(contentType); - } - if (resource.isFile() && contentLength >= 0 && - (!serveContent || ostream != null)) { - if (debug > 0) - log(""DefaultServlet.serveFile: contentLength="" + - contentLength); - // Don't set a content length if something else has already - // written to the response. - if (contentWritten == 0) { - response.setContentLengthLong(contentLength); - } - } - - if (serveContent) { - try { - response.setBufferSize(output); - } catch (IllegalStateException e) { - // Silent catch - } - InputStream renderResult = null; - if (ostream == null) { - // Output via a writer so can't use sendfile or write - // content directly. - if (resource.isDirectory()) { - renderResult = render(getPathPrefix(request), resource); - } else { - renderResult = resource.getInputStream(); - } - copy(resource, renderResult, writer, encoding); - } else { - // Output is via an InputStream - if (resource.isDirectory()) { - renderResult = render(getPathPrefix(request), resource); - } else { - // Output is content of resource - if (!checkSendfile(request, response, resource, - contentLength, null)) { - // sendfile not possible so check if resource - // content is available directly - byte[] resourceBody = resource.getContent(); - if (resourceBody == null) { - // Resource content not available, use - // inputstream - renderResult = resource.getInputStream(); - } else { - // Use the resource content directly - ostream.write(resourceBody); - } - } - } - // If a stream was configured, it needs to be copied to - // the output (this method closes the stream) - if (renderResult != null) { - copy(resource, renderResult, ostream); - } - } - } - - } else { - - if ((ranges == null) || (ranges.isEmpty())) - return; - - // Partial content response. - - response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); - - if (ranges.size() == 1) { - - Range range = ranges.get(0); - response.addHeader(""Content-Range"", ""bytes "" - + range.start - + ""-"" + range.end + ""/"" - + range.length); - long length = range.end - range.start + 1; - response.setContentLengthLong(length); - - if (contentType != null) { - if (debug > 0) - log(""DefaultServlet.serveFile: contentType='"" + - contentType + ""'""); - response.setContentType(contentType); - } - - if (serveContent) { - try { - response.setBufferSize(output); - } catch (IllegalStateException e) { - // Silent catch - } - if (ostream != null) { - if (!checkSendfile(request, response, resource, - range.end - range.start + 1, range)) - copy(resource, ostream, range); - } else { - // we should not get here - throw new IllegalStateException(); - } - } - } else { - response.setContentType(""multipart/byteranges; boundary="" - + mimeSeparation); - if (serveContent) { - try { - response.setBufferSize(output); - } catch (IllegalStateException e) { - // Silent catch - } - if (ostream != null) { - copy(resource, ostream, ranges.iterator(), contentType); - } else { - // we should not get here - throw new IllegalStateException(); - } - } - } - } - } - - - /** - * Parse the content-range header. - * - * @param request The servlet request we a)re processing - * @param response The servlet response we are creating - * @return Range - */ -" -283,1," private void findCloneMethod() { - try { - iCloneMethod = iPrototype.getClass().getMethod(""clone"", (Class[]) null); - } catch (final NoSuchMethodException ex) { - throw new IllegalArgumentException(""PrototypeCloneFactory: The clone method must exist and be public ""); - } - } - - /** - * Creates an object by calling the clone method. - * - * @return the new object - */ - @SuppressWarnings(""unchecked"") -" -284,1," public boolean isSequenceType() { return false; } - - - /* Traverseproc implementation */ - @Override -" -285,1," public void setDynamicAttribute(String uri, String localName, Object value) throws JspException { - if (ComponentUtils.altSyntax(getStack()) && ComponentUtils.isExpression(value)) { - dynamicAttributes.put(localName, String.valueOf(ObjectUtils.defaultIfNull(findValue(value.toString()), value))); - } else { - dynamicAttributes.put(localName, value); - } - } - -" -286,1," protected void onModified() throws IOException { - super.onModified(); - Jenkins.getInstance().trimLabels(); - } - } - - /** - * Set of installed cluster nodes. - *

- * We use this field with copy-on-write semantics. - * This field has mutable list (to keep the serialization look clean), - * but it shall never be modified. Only new completely populated slave - * list can be set here. - *

- * The field name should be really {@code nodes}, but again the backward compatibility - * prevents us from renaming. - */ - protected volatile NodeList slaves; - - /** - * Quiet period. - * - * This is {@link Integer} so that we can initialize it to '5' for upgrading users. - */ - /*package*/ Integer quietPeriod; - - /** - * Global default for {@link AbstractProject#getScmCheckoutRetryCount()} - */ - /*package*/ int scmCheckoutRetryCount; - - /** - * {@link View}s. - */ - private final CopyOnWriteArrayList views = new CopyOnWriteArrayList(); - - /** - * Name of the primary view. - *

- * Start with null, so that we can upgrade pre-1.269 data well. - * @since 1.269 - */ - private volatile String primaryView; - - private transient final ViewGroupMixIn viewGroupMixIn = new ViewGroupMixIn(this) { - protected List views() { return views; } - protected String primaryView() { return primaryView; } - protected void primaryView(String name) { primaryView=name; } - }; - - - private transient final FingerprintMap fingerprintMap = new FingerprintMap(); - - /** - * Loaded plugins. - */ - public transient final PluginManager pluginManager; - - public transient volatile TcpSlaveAgentListener tcpSlaveAgentListener; - - private transient UDPBroadcastThread udpBroadcastThread; - - private transient DNSMultiCast dnsMultiCast; - - /** - * List of registered {@link SCMListener}s. - */ - private transient final CopyOnWriteList scmListeners = new CopyOnWriteList(); - - /** - * TCP slave agent port. - * 0 for random, -1 to disable. - */ - private int slaveAgentPort =0; - - /** - * Whitespace-separated labels assigned to the master as a {@link Node}. - */ - private String label=""""; - - /** - * {@link hudson.security.csrf.CrumbIssuer} - */ - private volatile CrumbIssuer crumbIssuer; - - /** - * All labels known to Jenkins. This allows us to reuse the same label instances - * as much as possible, even though that's not a strict requirement. - */ - private transient final ConcurrentHashMap labels = new ConcurrentHashMap(); - - /** - * Load statistics of the entire system. - * - * This includes every executor and every job in the system. - */ - @Exported - public transient final OverallLoadStatistics overallLoad = new OverallLoadStatistics(); - - /** - * Load statistics of the free roaming jobs and slaves. - * - * This includes all executors on {@link Mode#NORMAL} nodes and jobs that do not have any assigned nodes. - * - * @since 1.467 - */ - @Exported - public transient final LoadStatistics unlabeledLoad = new UnlabeledLoadStatistics(); - - /** - * {@link NodeProvisioner} that reacts to {@link #unlabeledLoad}. - * @since 1.467 - */ - public transient final NodeProvisioner unlabeledNodeProvisioner = new NodeProvisioner(null,unlabeledLoad); - - /** - * @deprecated as of 1.467 - * Use {@link #unlabeledNodeProvisioner}. - * This was broken because it was tracking all the executors in the system, but it was only tracking - * free-roaming jobs in the queue. So {@link Cloud} fails to launch nodes when you have some exclusive - * slaves and free-roaming jobs in the queue. - */ - @Restricted(NoExternalUse.class) - public transient final NodeProvisioner overallNodeProvisioner = unlabeledNodeProvisioner; - - - public transient final ServletContext servletContext; - - /** - * Transient action list. Useful for adding navigation items to the navigation bar - * on the left. - */ - private transient final List actions = new CopyOnWriteArrayList(); - - /** - * List of master node properties - */ - private DescribableList,NodePropertyDescriptor> nodeProperties = new DescribableList,NodePropertyDescriptor>(this); - - /** - * List of global properties - */ - private DescribableList,NodePropertyDescriptor> globalNodeProperties = new DescribableList,NodePropertyDescriptor>(this); - - /** - * {@link AdministrativeMonitor}s installed on this system. - * - * @see AdministrativeMonitor - */ - public transient final List administrativeMonitors = getExtensionList(AdministrativeMonitor.class); - - /** - * Widgets on Hudson. - */ - private transient final List widgets = getExtensionList(Widget.class); - - /** - * {@link AdjunctManager} - */ - private transient final AdjunctManager adjuncts; - - /** - * Code that handles {@link ItemGroup} work. - */ - private transient final ItemGroupMixIn itemGroupMixIn = new ItemGroupMixIn(this,this) { - @Override - protected void add(TopLevelItem item) { - items.put(item.getName(),item); - } - - @Override - protected File getRootDirFor(String name) { - return Jenkins.this.getRootDirFor(name); - } - - /** - * Send the browser to the config page. - * use View to trim view/{default-view} from URL if possible - */ - @Override - protected String redirectAfterCreateItem(StaplerRequest req, TopLevelItem result) throws IOException { - String redirect = result.getUrl()+""configure""; - List ancestors = req.getAncestors(); - for (int i = ancestors.size() - 1; i >= 0; i--) { - Object o = ancestors.get(i).getObject(); - if (o instanceof View) { - redirect = req.getContextPath() + '/' + ((View)o).getUrl() + redirect; - break; - } - } - return redirect; - } - }; - - - /** - * Hook for a test harness to intercept Jenkins.getInstance() - * - * Do not use in the production code as the signature may change. - */ - public interface JenkinsHolder { - Jenkins getInstance(); - } - - static JenkinsHolder HOLDER = new JenkinsHolder() { - public Jenkins getInstance() { - return theInstance; - } - }; - - @CLIResolver - public static Jenkins getInstance() { - return HOLDER.getInstance(); - } - - /** - * Secret key generated once and used for a long time, beyond - * container start/stop. Persisted outside config.xml to avoid - * accidental exposure. - */ - private transient final String secretKey; - - private transient final UpdateCenter updateCenter = new UpdateCenter(); - - /** - * True if the user opted out from the statistics tracking. We'll never send anything if this is true. - */ - private Boolean noUsageStatistics; - - /** - * HTTP proxy configuration. - */ - public transient volatile ProxyConfiguration proxy; - - /** - * Bound to ""/log"". - */ - private transient final LogRecorderManager log = new LogRecorderManager(); - - protected Jenkins(File root, ServletContext context) throws IOException, InterruptedException, ReactorException { - this(root,context,null); - } - - /** - * @param pluginManager - * If non-null, use existing plugin manager. create a new one. - */ - @edu.umd.cs.findbugs.annotations.SuppressWarnings({ - ""SC_START_IN_CTOR"", // bug in FindBugs. It flags UDPBroadcastThread.start() call but that's for another class - ""ST_WRITE_TO_STATIC_FROM_INSTANCE_METHOD"" // Trigger.timer - }) - protected Jenkins(File root, ServletContext context, PluginManager pluginManager) throws IOException, InterruptedException, ReactorException { - long start = System.currentTimeMillis(); - - // As Jenkins is starting, grant this process full control - ACL.impersonate(ACL.SYSTEM); - try { - this.root = root; - this.servletContext = context; - computeVersion(context); - if(theInstance!=null) - throw new IllegalStateException(""second instance""); - theInstance = this; - - if (!new File(root,""jobs"").exists()) { - // if this is a fresh install, use more modern default layout that's consistent with slaves - workspaceDir = ""${JENKINS_HOME}/workspace/${ITEM_FULLNAME}""; - } - - // doing this early allows InitStrategy to set environment upfront - final InitStrategy is = InitStrategy.get(Thread.currentThread().getContextClassLoader()); - - Trigger.timer = new Timer(""Jenkins cron thread""); - queue = new Queue(LoadBalancer.CONSISTENT_HASH); - - try { - dependencyGraph = DependencyGraph.EMPTY; - } catch (InternalError e) { - if(e.getMessage().contains(""window server"")) { - throw new Error(""Looks like the server runs without X. Please specify -Djava.awt.headless=true as JVM option"",e); - } - throw e; - } - - // get or create the secret - TextFile secretFile = new TextFile(new File(getRootDir(),""secret.key"")); - if(secretFile.exists()) { - secretKey = secretFile.readTrim(); - } else { - SecureRandom sr = new SecureRandom(); - byte[] random = new byte[32]; - sr.nextBytes(random); - secretKey = Util.toHexString(random); - secretFile.write(secretKey); - } - - try { - proxy = ProxyConfiguration.load(); - } catch (IOException e) { - LOGGER.log(SEVERE, ""Failed to load proxy configuration"", e); - } - - if (pluginManager==null) - pluginManager = new LocalPluginManager(this); - this.pluginManager = pluginManager; - // JSON binding needs to be able to see all the classes from all the plugins - WebApp.get(servletContext).setClassLoader(pluginManager.uberClassLoader); - - adjuncts = new AdjunctManager(servletContext, pluginManager.uberClassLoader,""adjuncts/""+SESSION_HASH); - - // initialization consists of ... - executeReactor( is, - pluginManager.initTasks(is), // loading and preparing plugins - loadTasks(), // load jobs - InitMilestone.ordering() // forced ordering among key milestones - ); - - if(KILL_AFTER_LOAD) - System.exit(0); - - if(slaveAgentPort!=-1) { - try { - tcpSlaveAgentListener = new TcpSlaveAgentListener(slaveAgentPort); - } catch (BindException e) { - new AdministrativeError(getClass().getName()+"".tcpBind"", - ""Failed to listen to incoming slave connection"", - ""Failed to listen to incoming slave connection. Change the port number to solve the problem."",e); - } - } else - tcpSlaveAgentListener = null; - - try { - udpBroadcastThread = new UDPBroadcastThread(this); - udpBroadcastThread.start(); - } catch (IOException e) { - LOGGER.log(Level.WARNING, ""Failed to broadcast over UDP"",e); - } - dnsMultiCast = new DNSMultiCast(this); - - Timer timer = Trigger.timer; - if (timer != null) { - timer.scheduleAtFixedRate(new SafeTimerTask() { - @Override - protected void doRun() throws Exception { - trimLabels(); - } - }, TimeUnit2.MINUTES.toMillis(5), TimeUnit2.MINUTES.toMillis(5)); - } - - updateComputerList(); - - {// master is online now - Computer c = toComputer(); - if(c!=null) - for (ComputerListener cl : ComputerListener.all()) - cl.onOnline(c,StreamTaskListener.fromStdout()); - } - - for (ItemListener l : ItemListener.all()) { - long itemListenerStart = System.currentTimeMillis(); - l.onLoaded(); - if (LOG_STARTUP_PERFORMANCE) - LOGGER.info(String.format(""Took %dms for item listener %s startup"", - System.currentTimeMillis()-itemListenerStart,l.getClass().getName())); - } - - if (LOG_STARTUP_PERFORMANCE) - LOGGER.info(String.format(""Took %dms for complete Jenkins startup"", - System.currentTimeMillis()-start)); - } finally { - SecurityContextHolder.clearContext(); - } - } - - /** - * Executes a reactor. - * - * @param is - * If non-null, this can be consulted for ignoring some tasks. Only used during the initialization of Hudson. - */ - private void executeReactor(final InitStrategy is, TaskBuilder... builders) throws IOException, InterruptedException, ReactorException { - Reactor reactor = new Reactor(builders) { - /** - * Sets the thread name to the task for better diagnostics. - */ - @Override - protected void runTask(Task task) throws Exception { - if (is!=null && is.skipInitTask(task)) return; - - ACL.impersonate(ACL.SYSTEM); // full access in the initialization thread - String taskName = task.getDisplayName(); - - Thread t = Thread.currentThread(); - String name = t.getName(); - if (taskName !=null) - t.setName(taskName); - try { - long start = System.currentTimeMillis(); - super.runTask(task); - if(LOG_STARTUP_PERFORMANCE) - LOGGER.info(String.format(""Took %dms for %s by %s"", - System.currentTimeMillis()-start, taskName, name)); - } finally { - t.setName(name); - SecurityContextHolder.clearContext(); - } - } - }; - - new InitReactorRunner() { - @Override - protected void onInitMilestoneAttained(InitMilestone milestone) { - initLevel = milestone; - } - }.run(reactor); - } - - - public TcpSlaveAgentListener getTcpSlaveAgentListener() { - return tcpSlaveAgentListener; - } - - /** - * Makes {@link AdjunctManager} URL-bound. - * The dummy parameter allows us to use different URLs for the same adjunct, - * for proper cache handling. - */ - public AdjunctManager getAdjuncts(String dummy) { - return adjuncts; - } - - @Exported - public int getSlaveAgentPort() { - return slaveAgentPort; - } - - /** - * @param port - * 0 to indicate random available TCP port. -1 to disable this service. - */ - public void setSlaveAgentPort(int port) throws IOException { - this.slaveAgentPort = port; - - // relaunch the agent - if(tcpSlaveAgentListener==null) { - if(slaveAgentPort!=-1) - tcpSlaveAgentListener = new TcpSlaveAgentListener(slaveAgentPort); - } else { - if(tcpSlaveAgentListener.configuredPort!=slaveAgentPort) { - tcpSlaveAgentListener.shutdown(); - tcpSlaveAgentListener = null; - if(slaveAgentPort!=-1) - tcpSlaveAgentListener = new TcpSlaveAgentListener(slaveAgentPort); - } - } - } - - public void setNodeName(String name) { - throw new UnsupportedOperationException(); // not allowed - } - - public String getNodeDescription() { - return Messages.Hudson_NodeDescription(); - } - - @Exported - public String getDescription() { - return systemMessage; - } - - public PluginManager getPluginManager() { - return pluginManager; - } - - public UpdateCenter getUpdateCenter() { - return updateCenter; - } - - public boolean isUsageStatisticsCollected() { - return noUsageStatistics==null || !noUsageStatistics; - } - - public void setNoUsageStatistics(Boolean noUsageStatistics) throws IOException { - this.noUsageStatistics = noUsageStatistics; - save(); - } - - public View.People getPeople() { - return new View.People(this); - } - - /** - * @since 1.484 - */ - public View.AsynchPeople getAsynchPeople() { - return new View.AsynchPeople(this); - } - - /** - * Does this {@link View} has any associated user information recorded? - */ - public boolean hasPeople() { - return View.People.isApplicable(items.values()); - } - - public Api getApi() { - return new Api(this); - } - - /** - * Returns a secret key that survives across container start/stop. - *

- * This value is useful for implementing some of the security features. - * - * @deprecated - * Due to the past security advisory, this value should not be used any more to protect sensitive information. - * See {@link ConfidentialStore} and {@link ConfidentialKey} for how to store secrets. - */ - public String getSecretKey() { - return secretKey; - } - - /** - * Gets {@linkplain #getSecretKey() the secret key} as a key for AES-128. - * @since 1.308 - * @deprecated - * See {@link #getSecretKey()}. - */ - public SecretKey getSecretKeyAsAES128() { - return Util.toAes128Key(secretKey); - } - - /** - * Returns the unique identifier of this Jenkins that has been historically used to identify - * this Jenkins to the outside world. - * - *

- * This form of identifier is weak in that it can be impersonated by others. See - * https://wiki.jenkins-ci.org/display/JENKINS/Instance+Identity for more modern form of instance ID - * that can be challenged and verified. - * - * @since 1.498 - */ - @SuppressWarnings(""deprecation"") - public String getLegacyInstanceId() { - return Util.getDigestOf(getSecretKey()); - } - - /** - * Gets the SCM descriptor by name. Primarily used for making them web-visible. - */ - public Descriptor getScm(String shortClassName) { - return findDescriptor(shortClassName,SCM.all()); - } - - /** - * Gets the repository browser descriptor by name. Primarily used for making them web-visible. - */ - public Descriptor> getRepositoryBrowser(String shortClassName) { - return findDescriptor(shortClassName,RepositoryBrowser.all()); - } - - /** - * Gets the builder descriptor by name. Primarily used for making them web-visible. - */ - public Descriptor getBuilder(String shortClassName) { - return findDescriptor(shortClassName, Builder.all()); - } - - /** - * Gets the build wrapper descriptor by name. Primarily used for making them web-visible. - */ - public Descriptor getBuildWrapper(String shortClassName) { - return findDescriptor(shortClassName, BuildWrapper.all()); - } - - /** - * Gets the publisher descriptor by name. Primarily used for making them web-visible. - */ - public Descriptor getPublisher(String shortClassName) { - return findDescriptor(shortClassName, Publisher.all()); - } - - /** - * Gets the trigger descriptor by name. Primarily used for making them web-visible. - */ - public TriggerDescriptor getTrigger(String shortClassName) { - return (TriggerDescriptor) findDescriptor(shortClassName, Trigger.all()); - } - - /** - * Gets the retention strategy descriptor by name. Primarily used for making them web-visible. - */ - public Descriptor> getRetentionStrategy(String shortClassName) { - return findDescriptor(shortClassName, RetentionStrategy.all()); - } - - /** - * Gets the {@link JobPropertyDescriptor} by name. Primarily used for making them web-visible. - */ - public JobPropertyDescriptor getJobProperty(String shortClassName) { - // combining these two lines triggers javac bug. See issue #610. - Descriptor d = findDescriptor(shortClassName, JobPropertyDescriptor.all()); - return (JobPropertyDescriptor) d; - } - - /** - * @deprecated - * UI method. Not meant to be used programatically. - */ - public ComputerSet getComputer() { - return new ComputerSet(); - } - - /** - * Exposes {@link Descriptor} by its name to URL. - * - * After doing all the {@code getXXX(shortClassName)} methods, I finally realized that - * this just doesn't scale. - * - * @param id - * Either {@link Descriptor#getId()} (recommended) or the short name of a {@link Describable} subtype (for compatibility) - * @throws IllegalArgumentException if a short name was passed which matches multiple IDs (fail fast) - */ - @SuppressWarnings({""unchecked"", ""rawtypes""}) // too late to fix - public Descriptor getDescriptor(String id) { - // legacy descriptors that are reigstered manually doesn't show up in getExtensionList, so check them explicitly. - Iterable descriptors = Iterators.sequence(getExtensionList(Descriptor.class), DescriptorExtensionList.listLegacyInstances()); - for (Descriptor d : descriptors) { - if (d.getId().equals(id)) { - return d; - } - } - Descriptor candidate = null; - for (Descriptor d : descriptors) { - String name = d.getId(); - if (name.substring(name.lastIndexOf('.') + 1).equals(id)) { - if (candidate == null) { - candidate = d; - } else { - throw new IllegalArgumentException(id + "" is ambiguous; matches both "" + name + "" and "" + candidate.getId()); - } - } - } - return candidate; - } - - /** - * Alias for {@link #getDescriptor(String)}. - */ - public Descriptor getDescriptorByName(String id) { - return getDescriptor(id); - } - - /** - * Gets the {@link Descriptor} that corresponds to the given {@link Describable} type. - *

- * If you have an instance of {@code type} and call {@link Describable#getDescriptor()}, - * you'll get the same instance that this method returns. - */ - public Descriptor getDescriptor(Class type) { - for( Descriptor d : getExtensionList(Descriptor.class) ) - if(d.clazz==type) - return d; - return null; - } - - /** - * Works just like {@link #getDescriptor(Class)} but don't take no for an answer. - * - * @throws AssertionError - * If the descriptor is missing. - * @since 1.326 - */ - public Descriptor getDescriptorOrDie(Class type) { - Descriptor d = getDescriptor(type); - if (d==null) - throw new AssertionError(type+"" is missing its descriptor""); - return d; - } - - /** - * Gets the {@link Descriptor} instance in the current Hudson by its type. - */ - public T getDescriptorByType(Class type) { - for( Descriptor d : getExtensionList(Descriptor.class) ) - if(d.getClass()==type) - return type.cast(d); - return null; - } - - /** - * Gets the {@link SecurityRealm} descriptors by name. Primarily used for making them web-visible. - */ - public Descriptor getSecurityRealms(String shortClassName) { - return findDescriptor(shortClassName,SecurityRealm.all()); - } - - /** - * Finds a descriptor that has the specified name. - */ - private > - Descriptor findDescriptor(String shortClassName, Collection> descriptors) { - String name = '.'+shortClassName; - for (Descriptor d : descriptors) { - if(d.clazz.getName().endsWith(name)) - return d; - } - return null; - } - - protected void updateComputerList() throws IOException { - updateComputerList(AUTOMATIC_SLAVE_LAUNCH); - } - - /** - * Gets all the installed {@link SCMListener}s. - */ - public CopyOnWriteList getSCMListeners() { - return scmListeners; - } - - /** - * Gets the plugin object from its short name. - * - *

- * This allows URL hudson/plugin/ID to be served by the views - * of the plugin class. - */ - public Plugin getPlugin(String shortName) { - PluginWrapper p = pluginManager.getPlugin(shortName); - if(p==null) return null; - return p.getPlugin(); - } - - /** - * Gets the plugin object from its class. - * - *

- * This allows easy storage of plugin information in the plugin singleton without - * every plugin reimplementing the singleton pattern. - * - * @param clazz The plugin class (beware class-loader fun, this will probably only work - * from within the jpi that defines the plugin class, it may or may not work in other cases) - * - * @return The plugin instance. - */ - @SuppressWarnings(""unchecked"") - public

P getPlugin(Class

clazz) { - PluginWrapper p = pluginManager.getPlugin(clazz); - if(p==null) return null; - return (P) p.getPlugin(); - } - - /** - * Gets the plugin objects from their super-class. - * - * @param clazz The plugin class (beware class-loader fun) - * - * @return The plugin instances. - */ - public

List

getPlugins(Class

clazz) { - List

result = new ArrayList

(); - for (PluginWrapper w: pluginManager.getPlugins(clazz)) { - result.add((P)w.getPlugin()); - } - return Collections.unmodifiableList(result); - } - - /** - * Synonym for {@link #getDescription}. - */ - public String getSystemMessage() { - return systemMessage; - } - - /** - * Gets the markup formatter used in the system. - * - * @return - * never null. - * @since 1.391 - */ - public MarkupFormatter getMarkupFormatter() { - return markupFormatter!=null ? markupFormatter : RawHtmlMarkupFormatter.INSTANCE; - } - - /** - * Sets the markup formatter used in the system globally. - * - * @since 1.391 - */ - public void setMarkupFormatter(MarkupFormatter f) { - this.markupFormatter = f; - } - - /** - * Sets the system message. - */ - public void setSystemMessage(String message) throws IOException { - this.systemMessage = message; - save(); - } - - public FederatedLoginService getFederatedLoginService(String name) { - for (FederatedLoginService fls : FederatedLoginService.all()) { - if (fls.getUrlName().equals(name)) - return fls; - } - return null; - } - - public List getFederatedLoginServices() { - return FederatedLoginService.all(); - } - - public Launcher createLauncher(TaskListener listener) { - return new LocalLauncher(listener).decorateFor(this); - } - - - public String getFullName() { - return """"; - } - - public String getFullDisplayName() { - return """"; - } - - /** - * Returns the transient {@link Action}s associated with the top page. - * - *

- * Adding {@link Action} is primarily useful for plugins to contribute - * an item to the navigation bar of the top page. See existing {@link Action} - * implementation for it affects the GUI. - * - *

- * To register an {@link Action}, implement {@link RootAction} extension point, or write code like - * {@code Hudson.getInstance().getActions().add(...)}. - * - * @return - * Live list where the changes can be made. Can be empty but never null. - * @since 1.172 - */ - public List getActions() { - return actions; - } - - /** - * Gets just the immediate children of {@link Jenkins}. - * - * @see #getAllItems(Class) - */ - @Exported(name=""jobs"") - public List getItems() { - if (authorizationStrategy instanceof AuthorizationStrategy.Unsecured || - authorizationStrategy instanceof FullControlOnceLoggedInAuthorizationStrategy) { - return new ArrayList(items.values()); - } - - List viewableItems = new ArrayList(); - for (TopLevelItem item : items.values()) { - if (item.hasPermission(Item.READ)) - viewableItems.add(item); - } - - return viewableItems; - } - - /** - * Returns the read-only view of all the {@link TopLevelItem}s keyed by their names. - *

- * This method is efficient, as it doesn't involve any copying. - * - * @since 1.296 - */ - public Map getItemMap() { - return Collections.unmodifiableMap(items); - } - - /** - * Gets just the immediate children of {@link Jenkins} but of the given type. - */ - public List getItems(Class type) { - List r = new ArrayList(); - for (TopLevelItem i : getItems()) - if (type.isInstance(i)) - r.add(type.cast(i)); - return r; - } - - /** - * Gets all the {@link Item}s recursively in the {@link ItemGroup} tree - * and filter them by the given type. - */ - public List getAllItems(Class type) { - List r = new ArrayList(); - - Stack q = new Stack(); - q.push(this); - - while(!q.isEmpty()) { - ItemGroup parent = q.pop(); - for (Item i : parent.getItems()) { - if(type.isInstance(i)) { - if (i.hasPermission(Item.READ)) - r.add(type.cast(i)); - } - if(i instanceof ItemGroup) - q.push((ItemGroup)i); - } - } - - return r; - } - - /** - * Gets all the items recursively. - * - * @since 1.402 - */ - public List getAllItems() { - return getAllItems(Item.class); - } - - /** - * Gets a list of simple top-level projects. - * @deprecated This method will ignore Maven and matrix projects, as well as projects inside containers such as folders. - * You may prefer to call {@link #getAllItems(Class)} on {@link AbstractProject}, - * perhaps also using {@link Util#createSubList} to consider only {@link TopLevelItem}s. - * (That will also consider the caller's permissions.) - * If you really want to get just {@link Project}s at top level, ignoring permissions, - * you can filter the values from {@link #getItemMap} using {@link Util#createSubList}. - */ - @Deprecated - public List getProjects() { - return Util.createSubList(items.values(),Project.class); - } - - /** - * Gets the names of all the {@link Job}s. - */ - public Collection getJobNames() { - List names = new ArrayList(); - for (Job j : getAllItems(Job.class)) - names.add(j.getFullName()); - return names; - } - - public List getViewActions() { - return getActions(); - } - - /** - * Gets the names of all the {@link TopLevelItem}s. - */ - public Collection getTopLevelItemNames() { - List names = new ArrayList(); - for (TopLevelItem j : items.values()) - names.add(j.getName()); - return names; - } - - public View getView(String name) { - return viewGroupMixIn.getView(name); - } - - /** - * Gets the read-only list of all {@link View}s. - */ - @Exported - public Collection getViews() { - return viewGroupMixIn.getViews(); - } - - public void addView(View v) throws IOException { - viewGroupMixIn.addView(v); - } - - public boolean canDelete(View view) { - return viewGroupMixIn.canDelete(view); - } - - public synchronized void deleteView(View view) throws IOException { - viewGroupMixIn.deleteView(view); - } - - public void onViewRenamed(View view, String oldName, String newName) { - viewGroupMixIn.onViewRenamed(view,oldName,newName); - } - - /** - * Returns the primary {@link View} that renders the top-page of Hudson. - */ - @Exported - public View getPrimaryView() { - return viewGroupMixIn.getPrimaryView(); - } - - public void setPrimaryView(View v) { - this.primaryView = v.getViewName(); - } - - public ViewsTabBar getViewsTabBar() { - return viewsTabBar; - } - - public void setViewsTabBar(ViewsTabBar viewsTabBar) { - this.viewsTabBar = viewsTabBar; - } - - public Jenkins getItemGroup() { - return this; - } - - public MyViewsTabBar getMyViewsTabBar() { - return myViewsTabBar; - } - - public void setMyViewsTabBar(MyViewsTabBar myViewsTabBar) { - this.myViewsTabBar = myViewsTabBar; - } - - /** - * Returns true if the current running Hudson is upgraded from a version earlier than the specified version. - * - *

- * This method continues to return true until the system configuration is saved, at which point - * {@link #version} will be overwritten and Hudson forgets the upgrade history. - * - *

- * To handle SNAPSHOTS correctly, pass in ""1.N.*"" to test if it's upgrading from the version - * equal or younger than N. So say if you implement a feature in 1.301 and you want to check - * if the installation upgraded from pre-1.301, pass in ""1.300.*"" - * - * @since 1.301 - */ - public boolean isUpgradedFromBefore(VersionNumber v) { - try { - return new VersionNumber(version).isOlderThan(v); - } catch (IllegalArgumentException e) { - // fail to parse this version number - return false; - } - } - - /** - * Gets the read-only list of all {@link Computer}s. - */ - public Computer[] getComputers() { - Computer[] r = computers.values().toArray(new Computer[computers.size()]); - Arrays.sort(r,new Comparator() { - final Collator collator = Collator.getInstance(); - public int compare(Computer lhs, Computer rhs) { - if(lhs.getNode()==Jenkins.this) return -1; - if(rhs.getNode()==Jenkins.this) return 1; - return collator.compare(lhs.getDisplayName(), rhs.getDisplayName()); - } - }); - return r; - } - - @CLIResolver - public Computer getComputer(@Argument(required=true,metaVar=""NAME"",usage=""Node name"") String name) { - if(name.equals(""(master)"")) - name = """"; - - for (Computer c : computers.values()) { - if(c.getName().equals(name)) - return c; - } - return null; - } - - /** - * Gets the label that exists on this system by the name. - * - * @return null if name is null. - * @see Label#parseExpression(String) (String) - */ - public Label getLabel(String expr) { - if(expr==null) return null; - while(true) { - Label l = labels.get(expr); - if(l!=null) - return l; - - // non-existent - try { - labels.putIfAbsent(expr,Label.parseExpression(expr)); - } catch (ANTLRException e) { - // laxly accept it as a single label atom for backward compatibility - return getLabelAtom(expr); - } - } - } - - /** - * Returns the label atom of the given name. - * @return non-null iff name is non-null - */ - public @Nullable LabelAtom getLabelAtom(@CheckForNull String name) { - if (name==null) return null; - - while(true) { - Label l = labels.get(name); - if(l!=null) - return (LabelAtom)l; - - // non-existent - LabelAtom la = new LabelAtom(name); - if (labels.putIfAbsent(name, la)==null) - la.load(); - } - } - - /** - * Gets all the active labels in the current system. - */ - public Set

- * This method first tries to use the manually configured value, then - * fall back to {@link StaplerRequest#getRootPath()}. - * It is done in this order so that it can work correctly even in the face - * of a reverse proxy. - * - * @return - * This method returns null if this parameter is not configured by the user. - * The caller must gracefully deal with this situation. - * The returned URL will always have the trailing '/'. - * @since 1.66 - * @see Descriptor#getCheckUrl(String) - * @see #getRootUrlFromRequest() - */ - public String getRootUrl() { - // for compatibility. the actual data is stored in Mailer - String url = JenkinsLocationConfiguration.get().getUrl(); - if(url!=null) { - if (!url.endsWith(""/"")) url += '/'; - return url; - } - - StaplerRequest req = Stapler.getCurrentRequest(); - if(req!=null) - return getRootUrlFromRequest(); - return null; - } - - /** - * Is Jenkins running in HTTPS? - * - * Note that we can't really trust {@link StaplerRequest#isSecure()} because HTTPS might be terminated - * in the reverse proxy. - */ - public boolean isRootUrlSecure() { - String url = getRootUrl(); - return url!=null && url.startsWith(""https""); - } - - /** - * Gets the absolute URL of Hudson top page, such as ""http://localhost/hudson/"". - * - *

- * Unlike {@link #getRootUrl()}, which uses the manually configured value, - * this one uses the current request to reconstruct the URL. The benefit is - * that this is immune to the configuration mistake (users often fail to set the root URL - * correctly, especially when a migration is involved), but the downside - * is that unless you are processing a request, this method doesn't work. - * - * Please note that this will not work in all cases if Jenkins is running behind a - * reverse proxy (e.g. when user has switched off ProxyPreserveHost, which is - * default setup or the actual url uses https) and you should use getRootUrl if - * you want to be sure you reflect user setup. - * See https://wiki.jenkins-ci.org/display/JENKINS/Running+Jenkins+behind+Apache - * - * @since 1.263 - */ - public String getRootUrlFromRequest() { - StaplerRequest req = Stapler.getCurrentRequest(); - StringBuilder buf = new StringBuilder(); - buf.append(req.getScheme()+""://""); - buf.append(req.getServerName()); - if(req.getServerPort()!=80) - buf.append(':').append(req.getServerPort()); - buf.append(req.getContextPath()).append('/'); - return buf.toString(); - } - - public File getRootDir() { - return root; - } - - public FilePath getWorkspaceFor(TopLevelItem item) { - return new FilePath(expandVariablesForDirectory(workspaceDir, item)); - } - - public File getBuildDirFor(Job job) { - return expandVariablesForDirectory(buildsDir, job); - } - - private File expandVariablesForDirectory(String base, Item item) { - return new File(Util.replaceMacro(base, ImmutableMap.of( - ""JENKINS_HOME"", getRootDir().getPath(), - ""ITEM_ROOTDIR"", item.getRootDir().getPath(), - ""ITEM_FULLNAME"", item.getFullName()))); - } - - public String getRawWorkspaceDir() { - return workspaceDir; - } - - public String getRawBuildsDir() { - return buildsDir; - } - - public FilePath getRootPath() { - return new FilePath(getRootDir()); - } - - @Override - public FilePath createPath(String absolutePath) { - return new FilePath((VirtualChannel)null,absolutePath); - } - - public ClockDifference getClockDifference() { - return ClockDifference.ZERO; - } - - /** - * For binding {@link LogRecorderManager} to ""/log"". - * Everything below here is admin-only, so do the check here. - */ - public LogRecorderManager getLog() { - checkPermission(ADMINISTER); - return log; - } - - /** - * A convenience method to check if there's some security - * restrictions in place. - */ - @Exported - public boolean isUseSecurity() { - return securityRealm!=SecurityRealm.NO_AUTHENTICATION || authorizationStrategy!=AuthorizationStrategy.UNSECURED; - } - - public boolean isUseProjectNamingStrategy(){ - return projectNamingStrategy != DefaultProjectNamingStrategy.DEFAULT_NAMING_STRATEGY; - } - - /** - * If true, all the POST requests to Hudson would have to have crumb in it to protect - * Hudson from CSRF vulnerabilities. - */ - @Exported - public boolean isUseCrumbs() { - return crumbIssuer!=null; - } - - /** - * Returns the constant that captures the three basic security modes - * in Hudson. - */ - public SecurityMode getSecurity() { - // fix the variable so that this code works under concurrent modification to securityRealm. - SecurityRealm realm = securityRealm; - - if(realm==SecurityRealm.NO_AUTHENTICATION) - return SecurityMode.UNSECURED; - if(realm instanceof LegacySecurityRealm) - return SecurityMode.LEGACY; - return SecurityMode.SECURED; - } - - /** - * @return - * never null. - */ - public SecurityRealm getSecurityRealm() { - return securityRealm; - } - - public void setSecurityRealm(SecurityRealm securityRealm) { - if(securityRealm==null) - securityRealm= SecurityRealm.NO_AUTHENTICATION; - this.useSecurity = true; - this.securityRealm = securityRealm; - // reset the filters and proxies for the new SecurityRealm - try { - HudsonFilter filter = HudsonFilter.get(servletContext); - if (filter == null) { - // Fix for #3069: This filter is not necessarily initialized before the servlets. - // when HudsonFilter does come back, it'll initialize itself. - LOGGER.fine(""HudsonFilter has not yet been initialized: Can't perform security setup for now""); - } else { - LOGGER.fine(""HudsonFilter has been previously initialized: Setting security up""); - filter.reset(securityRealm); - LOGGER.fine(""Security is now fully set up""); - } - } catch (ServletException e) { - // for binary compatibility, this method cannot throw a checked exception - throw new AcegiSecurityException(""Failed to configure filter"",e) {}; - } - } - - public void setAuthorizationStrategy(AuthorizationStrategy a) { - if (a == null) - a = AuthorizationStrategy.UNSECURED; - useSecurity = true; - authorizationStrategy = a; - } - - public void disableSecurity() { - useSecurity = null; - setSecurityRealm(SecurityRealm.NO_AUTHENTICATION); - authorizationStrategy = AuthorizationStrategy.UNSECURED; - markupFormatter = null; - } - - public void setProjectNamingStrategy(ProjectNamingStrategy ns) { - if(ns == null){ - ns = DefaultProjectNamingStrategy.DEFAULT_NAMING_STRATEGY; - } - projectNamingStrategy = ns; - } - - public Lifecycle getLifecycle() { - return Lifecycle.get(); - } - - /** - * Gets the dependency injection container that hosts all the extension implementations and other - * components in Jenkins. - * - * @since 1.GUICE - */ - public Injector getInjector() { - return lookup(Injector.class); - } - - /** - * Returns {@link ExtensionList} that retains the discovered instances for the given extension type. - * - * @param extensionType - * The base type that represents the extension point. Normally {@link ExtensionPoint} subtype - * but that's not a hard requirement. - * @return - * Can be an empty list but never null. - */ - @SuppressWarnings({""unchecked""}) - public ExtensionList getExtensionList(Class extensionType) { - return extensionLists.get(extensionType); - } - - /** - * Used to bind {@link ExtensionList}s to URLs. - * - * @since 1.349 - */ - public ExtensionList getExtensionList(String extensionType) throws ClassNotFoundException { - return getExtensionList(pluginManager.uberClassLoader.loadClass(extensionType)); - } - - /** - * Returns {@link ExtensionList} that retains the discovered {@link Descriptor} instances for the given - * kind of {@link Describable}. - * - * @return - * Can be an empty list but never null. - */ - @SuppressWarnings({""unchecked""}) - public ,D extends Descriptor> DescriptorExtensionList getDescriptorList(Class type) { - return descriptorLists.get(type); - } - - /** - * Refresh {@link ExtensionList}s by adding all the newly discovered extensions. - * - * Exposed only for {@link PluginManager#dynamicLoad(File)}. - */ - public void refreshExtensions() throws ExtensionRefreshException { - ExtensionList finders = getExtensionList(ExtensionFinder.class); - for (ExtensionFinder ef : finders) { - if (!ef.isRefreshable()) - throw new ExtensionRefreshException(ef+"" doesn't support refresh""); - } - - List fragments = Lists.newArrayList(); - for (ExtensionFinder ef : finders) { - fragments.add(ef.refresh()); - } - ExtensionComponentSet delta = ExtensionComponentSet.union(fragments).filtered(); - - // if we find a new ExtensionFinder, we need it to list up all the extension points as well - List> newFinders = Lists.newArrayList(delta.find(ExtensionFinder.class)); - while (!newFinders.isEmpty()) { - ExtensionFinder f = newFinders.remove(newFinders.size()-1).getInstance(); - - ExtensionComponentSet ecs = ExtensionComponentSet.allOf(f).filtered(); - newFinders.addAll(ecs.find(ExtensionFinder.class)); - delta = ExtensionComponentSet.union(delta, ecs); - } - - for (ExtensionList el : extensionLists.values()) { - el.refresh(delta); - } - for (ExtensionList el : descriptorLists.values()) { - el.refresh(delta); - } - - // TODO: we need some generalization here so that extension points can be notified when a refresh happens? - for (ExtensionComponent ea : delta.find(RootAction.class)) { - Action a = ea.getInstance(); - if (!actions.contains(a)) actions.add(a); - } - } - - /** - * Returns the root {@link ACL}. - * - * @see AuthorizationStrategy#getRootACL() - */ - @Override - public ACL getACL() { - return authorizationStrategy.getRootACL(); - } - - /** - * @return - * never null. - */ - public AuthorizationStrategy getAuthorizationStrategy() { - return authorizationStrategy; - } - - /** - * The strategy used to check the project names. - * @return never null - */ - public ProjectNamingStrategy getProjectNamingStrategy() { - return projectNamingStrategy == null ? ProjectNamingStrategy.DEFAULT_NAMING_STRATEGY : projectNamingStrategy; - } - - /** - * Returns true if Hudson is quieting down. - *

- * No further jobs will be executed unless it - * can be finished while other current pending builds - * are still in progress. - */ - @Exported - public boolean isQuietingDown() { - return isQuietingDown; - } - - /** - * Returns true if the container initiated the termination of the web application. - */ - public boolean isTerminating() { - return terminating; - } - - /** - * Gets the initialization milestone that we've already reached. - * - * @return - * {@link InitMilestone#STARTED} even if the initialization hasn't been started, so that this method - * never returns null. - */ - public InitMilestone getInitLevel() { - return initLevel; - } - - public void setNumExecutors(int n) throws IOException { - this.numExecutors = n; - save(); - } - - - - /** - * {@inheritDoc}. - * - * Note that the look up is case-insensitive. - */ - public TopLevelItem getItem(String name) { - if (name==null) return null; - TopLevelItem item = items.get(name); - if (item==null) - return null; - if (!item.hasPermission(Item.READ)) { - if (item.hasPermission(Item.DISCOVER)) { - throw new AccessDeniedException(""Please login to access job "" + name); - } - return null; - } - return item; - } - - /** - * Gets the item by its path name from the given context - * - *

Path Names

- *

- * If the name starts from '/', like ""/foo/bar/zot"", then it's interpreted as absolute. - * Otherwise, the name should be something like ""foo/bar"" and it's interpreted like - * relative path name in the file system is, against the given context. - * - * @param context - * null is interpreted as {@link Jenkins}. Base 'directory' of the interpretation. - * @since 1.406 - */ - public Item getItem(String pathName, ItemGroup context) { - if (context==null) context = this; - if (pathName==null) return null; - - if (pathName.startsWith(""/"")) // absolute - return getItemByFullName(pathName); - - Object/*Item|ItemGroup*/ ctx = context; - - StringTokenizer tokens = new StringTokenizer(pathName,""/""); - while (tokens.hasMoreTokens()) { - String s = tokens.nextToken(); - if (s.equals("".."")) { - if (ctx instanceof Item) { - ctx = ((Item)ctx).getParent(); - continue; - } - - ctx=null; // can't go up further - break; - } - if (s.equals(""."")) { - continue; - } - - if (ctx instanceof ItemGroup) { - ItemGroup g = (ItemGroup) ctx; - Item i = g.getItem(s); - if (i==null || !i.hasPermission(Item.READ)) { // XXX consider DISCOVER - ctx=null; // can't go up further - break; - } - ctx=i; - } else { - return null; - } - } - - if (ctx instanceof Item) - return (Item)ctx; - - // fall back to the classic interpretation - return getItemByFullName(pathName); - } - - public final Item getItem(String pathName, Item context) { - return getItem(pathName,context!=null?context.getParent():null); - } - - public final T getItem(String pathName, ItemGroup context, Class type) { - Item r = getItem(pathName, context); - if (type.isInstance(r)) - return type.cast(r); - return null; - } - - public final T getItem(String pathName, Item context, Class type) { - return getItem(pathName,context!=null?context.getParent():null,type); - } - - public File getRootDirFor(TopLevelItem child) { - return getRootDirFor(child.getName()); - } - - private File getRootDirFor(String name) { - return new File(new File(getRootDir(),""jobs""), name); - } - - /** - * Gets the {@link Item} object by its full name. - * Full names are like path names, where each name of {@link Item} is - * combined by '/'. - * - * @return - * null if either such {@link Item} doesn't exist under the given full name, - * or it exists but it's no an instance of the given type. - */ - public @CheckForNull T getItemByFullName(String fullName, Class type) { - StringTokenizer tokens = new StringTokenizer(fullName,""/""); - ItemGroup parent = this; - - if(!tokens.hasMoreTokens()) return null; // for example, empty full name. - - while(true) { - Item item = parent.getItem(tokens.nextToken()); - if(!tokens.hasMoreTokens()) { - if(type.isInstance(item)) - return type.cast(item); - else - return null; - } - - if(!(item instanceof ItemGroup)) - return null; // this item can't have any children - - if (!item.hasPermission(Item.READ)) - return null; // XXX consider DISCOVER - - parent = (ItemGroup) item; - } - } - - public @CheckForNull Item getItemByFullName(String fullName) { - return getItemByFullName(fullName,Item.class); - } - - /** - * Gets the user of the given name. - * - * @return the user of the given name, if that person exists or the invoker {@link #hasPermission} on {@link #ADMINISTER}; else null - * @see User#get(String,boolean) - */ - public @CheckForNull User getUser(String name) { - return User.get(name,hasPermission(ADMINISTER)); - } - - public synchronized TopLevelItem createProject( TopLevelItemDescriptor type, String name ) throws IOException { - return createProject(type, name, true); - } - - public synchronized TopLevelItem createProject( TopLevelItemDescriptor type, String name, boolean notify ) throws IOException { - return itemGroupMixIn.createProject(type,name,notify); - } - - /** - * Overwrites the existing item by new one. - * - *

- * This is a short cut for deleting an existing job and adding a new one. - */ - public synchronized void putItem(TopLevelItem item) throws IOException, InterruptedException { - String name = item.getName(); - TopLevelItem old = items.get(name); - if (old ==item) return; // noop - - checkPermission(Item.CREATE); - if (old!=null) - old.delete(); - items.put(name,item); - ItemListener.fireOnCreated(item); - } - - /** - * Creates a new job. - * - *

- * This version infers the descriptor from the type of the top-level item. - * - * @throws IllegalArgumentException - * if the project of the given name already exists. - */ - public synchronized T createProject( Class type, String name ) throws IOException { - return type.cast(createProject((TopLevelItemDescriptor)getDescriptor(type),name)); - } - - /** - * Called by {@link Job#renameTo(String)} to update relevant data structure. - * assumed to be synchronized on Hudson by the caller. - */ - public void onRenamed(TopLevelItem job, String oldName, String newName) throws IOException { - items.remove(oldName); - items.put(newName,job); - - for (View v : views) - v.onJobRenamed(job, oldName, newName); - save(); - } - - /** - * Called in response to {@link Job#doDoDelete(StaplerRequest, StaplerResponse)} - */ - public void onDeleted(TopLevelItem item) throws IOException { - for (ItemListener l : ItemListener.all()) - l.onDeleted(item); - - items.remove(item.getName()); - for (View v : views) - v.onJobRenamed(item, item.getName(), null); - save(); - } - - public FingerprintMap getFingerprintMap() { - return fingerprintMap; - } - - // if no finger print matches, display ""not found page"". - public Object getFingerprint( String md5sum ) throws IOException { - Fingerprint r = fingerprintMap.get(md5sum); - if(r==null) return new NoFingerprintMatch(md5sum); - else return r; - } - - /** - * Gets a {@link Fingerprint} object if it exists. - * Otherwise null. - */ - public Fingerprint _getFingerprint( String md5sum ) throws IOException { - return fingerprintMap.get(md5sum); - } - - /** - * The file we save our configuration. - */ - private XmlFile getConfigFile() { - return new XmlFile(XSTREAM, new File(root,""config.xml"")); - } - - public int getNumExecutors() { - return numExecutors; - } - - public Mode getMode() { - return mode; - } - - public void setMode(Mode m) throws IOException { - this.mode = m; - save(); - } - - public String getLabelString() { - return fixNull(label).trim(); - } - - @Override - public void setLabelString(String label) throws IOException { - this.label = label; - save(); - } - - @Override - public LabelAtom getSelfLabel() { - return getLabelAtom(""master""); - } - - public Computer createComputer() { - return new Hudson.MasterComputer(); - } - - private synchronized TaskBuilder loadTasks() throws IOException { - File projectsDir = new File(root,""jobs""); - if(!projectsDir.getCanonicalFile().isDirectory() && !projectsDir.mkdirs()) { - if(projectsDir.exists()) - throw new IOException(projectsDir+"" is not a directory""); - throw new IOException(""Unable to create ""+projectsDir+""\nPermission issue? Please create this directory manually.""); - } - File[] subdirs = projectsDir.listFiles(new FileFilter() { - public boolean accept(File child) { - return child.isDirectory() && Items.getConfigFile(child).exists(); - } - }); - - TaskGraphBuilder g = new TaskGraphBuilder(); - Handle loadHudson = g.requires(EXTENSIONS_AUGMENTED).attains(JOB_LOADED).add(""Loading global config"", new Executable() { - public void run(Reactor session) throws Exception { - // JENKINS-8043: some slaves (eg. swarm slaves) are not saved into the config file - // and will get overwritten when reloading. Make a backup copy now, and re-add them later - NodeList oldSlaves = slaves; - - XmlFile cfg = getConfigFile(); - if (cfg.exists()) { - // reset some data that may not exist in the disk file - // so that we can take a proper compensation action later. - primaryView = null; - views.clear(); - - // load from disk - cfg.unmarshal(Jenkins.this); - } - - // if we are loading old data that doesn't have this field - if (slaves == null) slaves = new NodeList(); - - clouds.setOwner(Jenkins.this); - items.clear(); - - // JENKINS-8043: re-add the slaves which were not saved into the config file - // and are now missing, but still connected. - if (oldSlaves != null) { - ArrayList newSlaves = new ArrayList(slaves); - for (Node n: oldSlaves) { - if (n instanceof EphemeralNode) { - if(!newSlaves.contains(n)) { - newSlaves.add(n); - } - } - } - setNodes(newSlaves); - } - } - }); - - for (final File subdir : subdirs) { - g.requires(loadHudson).attains(JOB_LOADED).notFatal().add(""Loading job ""+subdir.getName(),new Executable() { - public void run(Reactor session) throws Exception { - TopLevelItem item = (TopLevelItem) Items.load(Jenkins.this, subdir); - items.put(item.getName(), item); - } - }); - } - - g.requires(JOB_LOADED).add(""Finalizing set up"",new Executable() { - public void run(Reactor session) throws Exception { - rebuildDependencyGraph(); - - {// recompute label objects - populates the labels mapping. - for (Node slave : slaves) - // Note that not all labels are visible until the slaves have connected. - slave.getAssignedLabels(); - getAssignedLabels(); - } - - // initialize views by inserting the default view if necessary - // this is both for clean Hudson and for backward compatibility. - if(views.size()==0 || primaryView==null) { - View v = new AllView(Messages.Hudson_ViewName()); - setViewOwner(v); - views.add(0,v); - primaryView = v.getViewName(); - } - - // read in old data that doesn't have the security field set - if(authorizationStrategy==null) { - if(useSecurity==null || !useSecurity) - authorizationStrategy = AuthorizationStrategy.UNSECURED; - else - authorizationStrategy = new LegacyAuthorizationStrategy(); - } - if(securityRealm==null) { - if(useSecurity==null || !useSecurity) - setSecurityRealm(SecurityRealm.NO_AUTHENTICATION); - else - setSecurityRealm(new LegacySecurityRealm()); - } else { - // force the set to proxy - setSecurityRealm(securityRealm); - } - - if(useSecurity!=null && !useSecurity) { - // forced reset to the unsecure mode. - // this works as an escape hatch for people who locked themselves out. - authorizationStrategy = AuthorizationStrategy.UNSECURED; - setSecurityRealm(SecurityRealm.NO_AUTHENTICATION); - } - - // Initialize the filter with the crumb issuer - setCrumbIssuer(crumbIssuer); - - // auto register root actions - for (Action a : getExtensionList(RootAction.class)) - if (!actions.contains(a)) actions.add(a); - } - }); - - return g; - } - - /** - * Save the settings to a file. - */ - public synchronized void save() throws IOException { - if(BulkChange.contains(this)) return; - getConfigFile().write(this); - SaveableListener.fireOnChange(this, getConfigFile()); - } - - - /** - * Called to shut down the system. - */ - @edu.umd.cs.findbugs.annotations.SuppressWarnings(""ST_WRITE_TO_STATIC_FROM_INSTANCE_METHOD"") - public void cleanUp() { - for (ItemListener l : ItemListener.all()) - l.onBeforeShutdown(); - - Set> pending = new HashSet>(); - terminating = true; - for( Computer c : computers.values() ) { - c.interrupt(); - killComputer(c); - pending.add(c.disconnect(null)); - } - if(udpBroadcastThread!=null) - udpBroadcastThread.shutdown(); - if(dnsMultiCast!=null) - dnsMultiCast.close(); - interruptReloadThread(); - Timer timer = Trigger.timer; - if (timer != null) { - timer.cancel(); - } - // TODO: how to wait for the completion of the last job? - Trigger.timer = null; - if(tcpSlaveAgentListener!=null) - tcpSlaveAgentListener.shutdown(); - - if(pluginManager!=null) // be defensive. there could be some ugly timing related issues - pluginManager.stop(); - - if(getRootDir().exists()) - // if we are aborting because we failed to create JENKINS_HOME, - // don't try to save. Issue #536 - getQueue().save(); - - threadPoolForLoad.shutdown(); - for (Future f : pending) - try { - f.get(10, TimeUnit.SECONDS); // if clean up operation didn't complete in time, we fail the test - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - break; // someone wants us to die now. quick! - } catch (ExecutionException e) { - LOGGER.log(Level.WARNING, ""Failed to shut down properly"",e); - } catch (TimeoutException e) { - LOGGER.log(Level.WARNING, ""Failed to shut down properly"",e); - } - - LogFactory.releaseAll(); - - theInstance = null; - } - - public Object getDynamic(String token) { - for (Action a : getActions()) { - String url = a.getUrlName(); - if (url==null) continue; - if (url.equals(token) || url.equals('/' + token)) - return a; - } - for (Action a : getManagementLinks()) - if(a.getUrlName().equals(token)) - return a; - return null; - } - - -// -// -// actions -// -// - /** - * Accepts submission from the configuration page. - */ - public synchronized void doConfigSubmit( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException, FormException { - BulkChange bc = new BulkChange(this); - try { - checkPermission(ADMINISTER); - - JSONObject json = req.getSubmittedForm(); - - workspaceDir = json.getString(""rawWorkspaceDir""); - buildsDir = json.getString(""rawBuildsDir""); - - systemMessage = Util.nullify(req.getParameter(""system_message"")); - - jdks.clear(); - jdks.addAll(req.bindJSONToList(JDK.class,json.get(""jdks""))); - - boolean result = true; - for( Descriptor d : Functions.getSortedDescriptorsForGlobalConfig() ) - result &= configureDescriptor(req,json,d); - - version = VERSION; - - save(); - updateComputerList(); - if(result) - FormApply.success(req.getContextPath()+'/').generateResponse(req, rsp, null); - else - FormApply.success(""configure"").generateResponse(req, rsp, null); // back to config - } finally { - bc.commit(); - } - } - - /** - * Gets the {@link CrumbIssuer} currently in use. - * - * @return null if none is in use. - */ - public CrumbIssuer getCrumbIssuer() { - return crumbIssuer; - } - - public void setCrumbIssuer(CrumbIssuer issuer) { - crumbIssuer = issuer; - } - - public synchronized void doTestPost( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException { - rsp.sendRedirect(""foo""); - } - - private boolean configureDescriptor(StaplerRequest req, JSONObject json, Descriptor d) throws FormException { - // collapse the structure to remain backward compatible with the JSON structure before 1. - String name = d.getJsonSafeClassName(); - JSONObject js = json.has(name) ? json.getJSONObject(name) : new JSONObject(); // if it doesn't have the property, the method returns invalid null object. - json.putAll(js); - return d.configure(req, js); - } - - /** - * Accepts submission from the node configuration page. - */ - public synchronized void doConfigExecutorsSubmit( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException, FormException { - checkPermission(ADMINISTER); - - BulkChange bc = new BulkChange(this); - try { - JSONObject json = req.getSubmittedForm(); - - MasterBuildConfiguration mbc = MasterBuildConfiguration.all().get(MasterBuildConfiguration.class); - if (mbc!=null) - mbc.configure(req,json); - - getNodeProperties().rebuild(req, json.optJSONObject(""nodeProperties""), NodeProperty.all()); - } finally { - bc.commit(); - } - - rsp.sendRedirect(req.getContextPath()+'/'+toComputer().getUrl()); // back to the computer page - } - - /** - * Accepts the new description. - */ - public synchronized void doSubmitDescription( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException { - getPrimaryView().doSubmitDescription(req, rsp); - } - - public synchronized HttpRedirect doQuietDown() throws IOException { - try { - return doQuietDown(false,0); - } catch (InterruptedException e) { - throw new AssertionError(); // impossible - } - } - - @CLIMethod(name=""quiet-down"") - public HttpRedirect doQuietDown( - @Option(name=""-block"",usage=""Block until the system really quiets down and no builds are running"") @QueryParameter boolean block, - @Option(name=""-timeout"",usage=""If non-zero, only block up to the specified number of milliseconds"") @QueryParameter int timeout) throws InterruptedException, IOException { - synchronized (this) { - checkPermission(ADMINISTER); - isQuietingDown = true; - } - if (block) { - if (timeout > 0) timeout += System.currentTimeMillis(); - while (isQuietingDown - && (timeout <= 0 || System.currentTimeMillis() < timeout) - && !RestartListener.isAllReady()) { - Thread.sleep(1000); - } - } - return new HttpRedirect("".""); - } - - @CLIMethod(name=""cancel-quiet-down"") - public synchronized HttpRedirect doCancelQuietDown() { - checkPermission(ADMINISTER); - isQuietingDown = false; - getQueue().scheduleMaintenance(); - return new HttpRedirect("".""); - } - - /** - * Backward compatibility. Redirect to the thread dump. - */ - public void doClassicThreadDump(StaplerResponse rsp) throws IOException, ServletException { - rsp.sendRedirect2(""threadDump""); - } - - /** - * Obtains the thread dump of all slaves (including the master.) - * - *

- * Since this is for diagnostics, it has a built-in precautionary measure against hang slaves. - */ - public Map> getAllThreadDumps() throws IOException, InterruptedException { - checkPermission(ADMINISTER); - - // issue the requests all at once - Map>> future = new HashMap>>(); - - for (Computer c : getComputers()) { - try { - future.put(c.getName(), RemotingDiagnostics.getThreadDumpAsync(c.getChannel())); - } catch(Exception e) { - LOGGER.info(""Failed to get thread dump for node "" + c.getName() + "": "" + e.getMessage()); - } - } - if (toComputer() == null) { - future.put(""master"", RemotingDiagnostics.getThreadDumpAsync(MasterComputer.localChannel)); - } - - // if the result isn't available in 5 sec, ignore that. - // this is a precaution against hang nodes - long endTime = System.currentTimeMillis() + 5000; - - Map> r = new HashMap>(); - for (Entry>> e : future.entrySet()) { - try { - r.put(e.getKey(), e.getValue().get(endTime-System.currentTimeMillis(), TimeUnit.MILLISECONDS)); - } catch (Exception x) { - StringWriter sw = new StringWriter(); - x.printStackTrace(new PrintWriter(sw,true)); - r.put(e.getKey(), Collections.singletonMap(""Failed to retrieve thread dump"",sw.toString())); - } - } - return r; - } - - public synchronized TopLevelItem doCreateItem( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException { - return itemGroupMixIn.createTopLevelItem(req, rsp); - } - - /** - * @since 1.319 - */ - public TopLevelItem createProjectFromXML(String name, InputStream xml) throws IOException { - return itemGroupMixIn.createProjectFromXML(name, xml); - } - - - @SuppressWarnings({""unchecked""}) - public T copy(T src, String name) throws IOException { - return itemGroupMixIn.copy(src, name); - } - - // a little more convenient overloading that assumes the caller gives us the right type - // (or else it will fail with ClassCastException) - public > T copy(T src, String name) throws IOException { - return (T)copy((TopLevelItem)src,name); - } - - public synchronized void doCreateView( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException, FormException { - checkPermission(View.CREATE); - addView(View.create(req,rsp, this)); - } - - /** - * Check if the given name is suitable as a name - * for job, view, etc. - * - * @throws ParseException - * if the given name is not good - */ - public static void checkGoodName(String name) throws Failure { - if(name==null || name.length()==0) - throw new Failure(Messages.Hudson_NoName()); - - for( int i=0; i[]:;"".indexOf(ch)!=-1) - throw new Failure(Messages.Hudson_UnsafeChar(ch)); - } - - // looks good - } - - /** - * Makes sure that the given name is good as a job name. - * @return trimmed name if valid; throws ParseException if not - */ - private String checkJobName(String name) throws Failure { - checkGoodName(name); - name = name.trim(); - projectNamingStrategy.checkName(name); - if(getItem(name)!=null) - throw new Failure(Messages.Hudson_JobAlreadyExists(name)); - // looks good - return name; - } - - private static String toPrintableName(String name) { - StringBuilder printableName = new StringBuilder(); - for( int i=0; i args = new ArrayList(); - while (true) - args.add(new byte[1024*1024]); - } - - private transient final Map duplexChannels = new HashMap(); - - /** - * Handles HTTP requests for duplex channels for CLI. - */ - public void doCli(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException, InterruptedException { - if (!""POST"".equals(req.getMethod())) { - // for GET request, serve _cli.jelly, assuming this is a browser - checkPermission(READ); - req.getView(this,""_cli.jelly"").forward(req,rsp); - return; - } - - // do not require any permission to establish a CLI connection - // the actual authentication for the connecting Channel is done by CLICommand - - UUID uuid = UUID.fromString(req.getHeader(""Session"")); - rsp.setHeader(""Hudson-Duplex"",""""); // set the header so that the client would know - - FullDuplexHttpChannel server; - if(req.getHeader(""Side"").equals(""download"")) { - duplexChannels.put(uuid,server=new FullDuplexHttpChannel(uuid, !hasPermission(ADMINISTER)) { - protected void main(Channel channel) throws IOException, InterruptedException { - // capture the identity given by the transport, since this can be useful for SecurityRealm.createCliAuthenticator() - channel.setProperty(CLICommand.TRANSPORT_AUTHENTICATION,getAuthentication()); - channel.setProperty(CliEntryPoint.class.getName(),new CliManagerImpl(channel)); - } - }); - try { - server.download(req,rsp); - } finally { - duplexChannels.remove(uuid); - } - } else { - duplexChannels.get(uuid).upload(req,rsp); - } - } - - /** - * Binds /userContent/... to $JENKINS_HOME/userContent. - */ - public DirectoryBrowserSupport doUserContent() { - return new DirectoryBrowserSupport(this,getRootPath().child(""userContent""),""User content"",""folder.png"",true); - } - - /** - * Perform a restart of Hudson, if we can. - * - * This first replaces ""app"" to {@link HudsonIsRestarting} - */ - @CLIMethod(name=""restart"") - public void doRestart(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException, RestartNotSupportedException { - checkPermission(ADMINISTER); - if (req != null && req.getMethod().equals(""GET"")) { - req.getView(this,""_restart.jelly"").forward(req,rsp); - return; - } - - restart(); - - if (rsp != null) // null for CLI - rsp.sendRedirect2("".""); - } - - /** - * Queues up a restart of Hudson for when there are no builds running, if we can. - * - * This first replaces ""app"" to {@link HudsonIsRestarting} - * - * @since 1.332 - */ - @CLIMethod(name=""safe-restart"") - public HttpResponse doSafeRestart(StaplerRequest req) throws IOException, ServletException, RestartNotSupportedException { - checkPermission(ADMINISTER); - if (req != null && req.getMethod().equals(""GET"")) - return HttpResponses.forwardToView(this,""_safeRestart.jelly""); - - safeRestart(); - - return HttpResponses.redirectToDot(); - } - - /** - * Performs a restart. - */ - public void restart() throws RestartNotSupportedException { - final Lifecycle lifecycle = Lifecycle.get(); - lifecycle.verifyRestartable(); // verify that Hudson is restartable - servletContext.setAttribute(""app"", new HudsonIsRestarting()); - - new Thread(""restart thread"") { - final String exitUser = getAuthentication().getName(); - @Override - public void run() { - try { - ACL.impersonate(ACL.SYSTEM); - - // give some time for the browser to load the ""reloading"" page - Thread.sleep(5000); - LOGGER.severe(String.format(""Restarting VM as requested by %s"",exitUser)); - for (RestartListener listener : RestartListener.all()) - listener.onRestart(); - lifecycle.restart(); - } catch (InterruptedException e) { - LOGGER.log(Level.WARNING, ""Failed to restart Hudson"",e); - } catch (IOException e) { - LOGGER.log(Level.WARNING, ""Failed to restart Hudson"",e); - } - } - }.start(); - } - - /** - * Queues up a restart to be performed once there are no builds currently running. - * @since 1.332 - */ - public void safeRestart() throws RestartNotSupportedException { - final Lifecycle lifecycle = Lifecycle.get(); - lifecycle.verifyRestartable(); // verify that Hudson is restartable - // Quiet down so that we won't launch new builds. - isQuietingDown = true; - - new Thread(""safe-restart thread"") { - final String exitUser = getAuthentication().getName(); - @Override - public void run() { - try { - ACL.impersonate(ACL.SYSTEM); - - // Wait 'til we have no active executors. - doQuietDown(true, 0); - - // Make sure isQuietingDown is still true. - if (isQuietingDown) { - servletContext.setAttribute(""app"",new HudsonIsRestarting()); - // give some time for the browser to load the ""reloading"" page - LOGGER.info(""Restart in 10 seconds""); - Thread.sleep(10000); - LOGGER.severe(String.format(""Restarting VM as requested by %s"",exitUser)); - for (RestartListener listener : RestartListener.all()) - listener.onRestart(); - lifecycle.restart(); - } else { - LOGGER.info(""Safe-restart mode cancelled""); - } - } catch (InterruptedException e) { - LOGGER.log(Level.WARNING, ""Failed to restart Hudson"",e); - } catch (IOException e) { - LOGGER.log(Level.WARNING, ""Failed to restart Hudson"",e); - } - } - }.start(); - } - - /** - * Shutdown the system. - * @since 1.161 - */ - @CLIMethod(name=""shutdown"") - public void doExit( StaplerRequest req, StaplerResponse rsp ) throws IOException { - checkPermission(ADMINISTER); - LOGGER.severe(String.format(""Shutting down VM as requested by %s from %s"", - getAuthentication().getName(), req!=null?req.getRemoteAddr():""???"")); - if (rsp!=null) { - rsp.setStatus(HttpServletResponse.SC_OK); - rsp.setContentType(""text/plain""); - PrintWriter w = rsp.getWriter(); - w.println(""Shutting down""); - w.close(); - } - - System.exit(0); - } - - - /** - * Shutdown the system safely. - * @since 1.332 - */ - @CLIMethod(name=""safe-shutdown"") - public HttpResponse doSafeExit(StaplerRequest req) throws IOException { - checkPermission(ADMINISTER); - isQuietingDown = true; - final String exitUser = getAuthentication().getName(); - final String exitAddr = req!=null ? req.getRemoteAddr() : ""unknown""; - new Thread(""safe-exit thread"") { - @Override - public void run() { - try { - ACL.impersonate(ACL.SYSTEM); - LOGGER.severe(String.format(""Shutting down VM as requested by %s from %s"", - exitUser, exitAddr)); - // Wait 'til we have no active executors. - while (isQuietingDown - && (overallLoad.computeTotalExecutors() > overallLoad.computeIdleExecutors())) { - Thread.sleep(5000); - } - // Make sure isQuietingDown is still true. - if (isQuietingDown) { - cleanUp(); - System.exit(0); - } - } catch (InterruptedException e) { - LOGGER.log(Level.WARNING, ""Failed to shutdown Hudson"",e); - } - } - }.start(); - - return HttpResponses.plainText(""Shutting down as soon as all jobs are complete""); - } - - /** - * Gets the {@link Authentication} object that represents the user - * associated with the current request. - */ - public static Authentication getAuthentication() { - Authentication a = SecurityContextHolder.getContext().getAuthentication(); - // on Tomcat while serving the login page, this is null despite the fact - // that we have filters. Looking at the stack trace, Tomcat doesn't seem to - // run the request through filters when this is the login request. - // see http://www.nabble.com/Matrix-authorization-problem-tp14602081p14886312.html - if(a==null) - a = ANONYMOUS; - return a; - } - - /** - * For system diagnostics. - * Run arbitrary Groovy script. - */ - public void doScript(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { - doScript(req, rsp, req.getView(this, ""_script.jelly"")); - } - - /** - * Run arbitrary Groovy script and return result as plain text. - */ - public void doScriptText(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { - doScript(req, rsp, req.getView(this, ""_scriptText.jelly"")); - } - - private void doScript(StaplerRequest req, StaplerResponse rsp, RequestDispatcher view) throws IOException, ServletException { - // ability to run arbitrary script is dangerous - checkPermission(RUN_SCRIPTS); - - String text = req.getParameter(""script""); - if (text != null) { - try { - req.setAttribute(""output"", - RemotingDiagnostics.executeGroovy(text, MasterComputer.localChannel)); - } catch (InterruptedException e) { - throw new ServletException(e); - } - } - - view.forward(req, rsp); - } - - /** - * Evaluates the Jelly script submitted by the client. - * - * This is useful for system administration as well as unit testing. - */ - @RequirePOST - public void doEval(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { - checkPermission(ADMINISTER); - - try { - MetaClass mc = WebApp.getCurrent().getMetaClass(getClass()); - Script script = mc.classLoader.loadTearOff(JellyClassLoaderTearOff.class).createContext().compileScript(new InputSource(req.getReader())); - new JellyRequestDispatcher(this,script).forward(req,rsp); - } catch (JellyException e) { - throw new ServletException(e); - } - } - - /** - * Sign up for the user account. - */ - public void doSignup( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException { - req.getView(getSecurityRealm(), ""signup.jelly"").forward(req, rsp); - } - - /** - * Changes the icon size by changing the cookie - */ - public void doIconSize( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException { - String qs = req.getQueryString(); - if(qs==null || !ICON_SIZE.matcher(qs).matches()) - throw new ServletException(); - Cookie cookie = new Cookie(""iconSize"", qs); - cookie.setMaxAge(/* ~4 mo. */9999999); // #762 - rsp.addCookie(cookie); - String ref = req.getHeader(""Referer""); - if(ref==null) ref="".""; - rsp.sendRedirect2(ref); - } - - public void doFingerprintCleanup(StaplerResponse rsp) throws IOException { - FingerprintCleanupThread.invoke(); - rsp.setStatus(HttpServletResponse.SC_OK); - rsp.setContentType(""text/plain""); - rsp.getWriter().println(""Invoked""); - } - - public void doWorkspaceCleanup(StaplerResponse rsp) throws IOException { - WorkspaceCleanupThread.invoke(); - rsp.setStatus(HttpServletResponse.SC_OK); - rsp.setContentType(""text/plain""); - rsp.getWriter().println(""Invoked""); - } - - /** - * If the user chose the default JDK, make sure we got 'java' in PATH. - */ - public FormValidation doDefaultJDKCheck(StaplerRequest request, @QueryParameter String value) { - if(!value.equals(""(Default)"")) - // assume the user configured named ones properly in system config --- - // or else system config should have reported form field validation errors. - return FormValidation.ok(); - - // default JDK selected. Does such java really exist? - if(JDK.isDefaultJDKValid(Jenkins.this)) - return FormValidation.ok(); - else - return FormValidation.errorWithMarkup(Messages.Hudson_NoJavaInPath(request.getContextPath())); - } - - /** - * Makes sure that the given name is good as a job name. - */ - public FormValidation doCheckJobName(@QueryParameter String value) { - // this method can be used to check if a file exists anywhere in the file system, - // so it should be protected. - checkPermission(Item.CREATE); - - if(fixEmpty(value)==null) - return FormValidation.ok(); - - try { - checkJobName(value); - return FormValidation.ok(); - } catch (Failure e) { - return FormValidation.error(e.getMessage()); - } - } - - /** - * Checks if a top-level view with the given name exists. - */ - public FormValidation doViewExistsCheck(@QueryParameter String value) { - checkPermission(View.CREATE); - - String view = fixEmpty(value); - if(view==null) return FormValidation.ok(); - - if(getView(view)==null) - return FormValidation.ok(); - else - return FormValidation.error(Messages.Hudson_ViewAlreadyExists(view)); - } - - /** - * Serves static resources placed along with Jelly view files. - *

- * This method can serve a lot of files, so care needs to be taken - * to make this method secure. It's not clear to me what's the best - * strategy here, though the current implementation is based on - * file extensions. - */ - public void doResources(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { - String path = req.getRestOfPath(); - // cut off the ""..."" portion of /resources/.../path/to/file - // as this is only used to make path unique (which in turn - // allows us to set a long expiration date - path = path.substring(path.indexOf('/',1)+1); - - int idx = path.lastIndexOf('.'); - String extension = path.substring(idx+1); - if(ALLOWED_RESOURCE_EXTENSIONS.contains(extension)) { - URL url = pluginManager.uberClassLoader.getResource(path); - if(url!=null) { - long expires = MetaClass.NO_CACHE ? 0 : 365L * 24 * 60 * 60 * 1000; /*1 year*/ - rsp.serveFile(req,url,expires); - return; - } - } - rsp.sendError(HttpServletResponse.SC_NOT_FOUND); - } - - /** - * Extension list that {@link #doResources(StaplerRequest, StaplerResponse)} can serve. - * This set is mutable to allow plugins to add additional extensions. - */ - public static final Set ALLOWED_RESOURCE_EXTENSIONS = new HashSet(Arrays.asList( - ""js|css|jpeg|jpg|png|gif|html|htm"".split(""\\|"") - )); - - /** - * Checks if container uses UTF-8 to decode URLs. See - * http://wiki.jenkins-ci.org/display/JENKINS/Tomcat#Tomcat-i18n - */ - public FormValidation doCheckURIEncoding(StaplerRequest request) throws IOException { - // expected is non-ASCII String - final String expected = ""\u57f7\u4e8b""; - final String value = fixEmpty(request.getParameter(""value"")); - if (!expected.equals(value)) - return FormValidation.warningWithMarkup(Messages.Hudson_NotUsesUTF8ToDecodeURL()); - return FormValidation.ok(); - } - - /** - * Does not check when system default encoding is ""ISO-8859-1"". - */ - public static boolean isCheckURIEncodingEnabled() { - return !""ISO-8859-1"".equalsIgnoreCase(System.getProperty(""file.encoding"")); - } - - /** - * Rebuilds the dependency map. - */ - public void rebuildDependencyGraph() { - DependencyGraph graph = new DependencyGraph(); - graph.build(); - // volatile acts a as a memory barrier here and therefore guarantees - // that graph is fully build, before it's visible to other threads - dependencyGraph = graph; - } - - public DependencyGraph getDependencyGraph() { - return dependencyGraph; - } - - // for Jelly - public List getManagementLinks() { - return ManagementLink.all(); - } - - /** - * Exposes the current user to /me URL. - */ - public User getMe() { - User u = User.current(); - if (u == null) - throw new AccessDeniedException(""/me is not available when not logged in""); - return u; - } - - /** - * Gets the {@link Widget}s registered on this object. - * - *

- * Plugins who wish to contribute boxes on the side panel can add widgets - * by {@code getWidgets().add(new MyWidget())} from {@link Plugin#start()}. - */ - public List getWidgets() { - return widgets; - } - - public Object getTarget() { - try { - checkPermission(READ); - } catch (AccessDeniedException e) { - String rest = Stapler.getCurrentRequest().getRestOfPath(); - if(rest.startsWith(""/login"") - || rest.startsWith(""/logout"") - || rest.startsWith(""/accessDenied"") - || rest.startsWith(""/adjuncts/"") - || rest.startsWith(""/signup"") - || rest.startsWith(""/tcpSlaveAgentListener"") - || rest.startsWith(""/cli"") - || rest.startsWith(""/federatedLoginService/"") - || rest.startsWith(""/securityRealm"")) - return this; // URLs that are always visible without READ permission - - for (String name : getUnprotectedRootActions()) { - if (rest.startsWith(""/"" + name + ""/"") || rest.equals(""/"" + name)) { - return this; - } - } - - throw e; - } - return this; - } - - /** - * Gets a list of unprotected root actions. - * These URL prefixes should be exempted from access control checks by container-managed security. - * Ideally would be synchronized with {@link #getTarget}. - * @return a list of {@linkplain Action#getUrlName URL names} - * @since 1.495 - */ - public Collection getUnprotectedRootActions() { - Set names = new TreeSet(); - names.add(""jnlpJars""); // XXX cleaner to refactor doJnlpJars into a URA - // XXX consider caching (expiring cache when actions changes) - for (Action a : getActions()) { - if (a instanceof UnprotectedRootAction) { - names.add(a.getUrlName()); - } - } - return names; - } - - /** - * Fallback to the primary view. - */ - public View getStaplerFallback() { - return getPrimaryView(); - } - - /** - * This method checks all existing jobs to see if displayName is - * unique. It does not check the displayName against the displayName of the - * job that the user is configuring though to prevent a validation warning - * if the user sets the displayName to what it currently is. - * @param displayName - * @param currentJobName - * @return - */ - boolean isDisplayNameUnique(String displayName, String currentJobName) { - Collection itemCollection = items.values(); - - // if there are a lot of projects, we'll have to store their - // display names in a HashSet or something for a quick check - for(TopLevelItem item : itemCollection) { - if(item.getName().equals(currentJobName)) { - // we won't compare the candidate displayName against the current - // item. This is to prevent an validation warning if the user - // sets the displayName to what the existing display name is - continue; - } - else if(displayName.equals(item.getDisplayName())) { - return false; - } - } - - return true; - } - - /** - * True if there is no item in Jenkins that has this name - * @param name The name to test - * @param currentJobName The name of the job that the user is configuring - * @return - */ - boolean isNameUnique(String name, String currentJobName) { - Item item = getItem(name); - - if(null==item) { - // the candidate name didn't return any items so the name is unique - return true; - } - else if(item.getName().equals(currentJobName)) { - // the candidate name returned an item, but the item is the item - // that the user is configuring so this is ok - return true; - } - else { - // the candidate name returned an item, so it is not unique - return false; - } - } - - /** - * Checks to see if the candidate displayName collides with any - * existing display names or project names - * @param displayName The display name to test - * @param jobName The name of the job the user is configuring - * @return - */ - public FormValidation doCheckDisplayName(@QueryParameter String displayName, - @QueryParameter String jobName) { - displayName = displayName.trim(); - - if(LOGGER.isLoggable(Level.FINE)) { - LOGGER.log(Level.FINE, ""Current job name is "" + jobName); - } - - if(!isNameUnique(displayName, jobName)) { - return FormValidation.warning(Messages.Jenkins_CheckDisplayName_NameNotUniqueWarning(displayName)); - } - else if(!isDisplayNameUnique(displayName, jobName)){ - return FormValidation.warning(Messages.Jenkins_CheckDisplayName_DisplayNameNotUniqueWarning(displayName)); - } - else { - return FormValidation.ok(); - } - } - - public static class MasterComputer extends Computer { - protected MasterComputer() { - super(Jenkins.getInstance()); - } - - /** - * Returns """" to match with {@link Jenkins#getNodeName()}. - */ - @Override - public String getName() { - return """"; - } - - @Override - public boolean isConnecting() { - return false; - } - - @Override - public String getDisplayName() { - return Messages.Hudson_Computer_DisplayName(); - } - - @Override - public String getCaption() { - return Messages.Hudson_Computer_Caption(); - } - - @Override - public String getUrl() { - return ""computer/(master)/""; - } - - public RetentionStrategy getRetentionStrategy() { - return RetentionStrategy.NOOP; - } - - /** - * Report an error. - */ - @Override - public HttpResponse doDoDelete() throws IOException { - throw HttpResponses.status(SC_BAD_REQUEST); - } - - @Override - public void doConfigSubmit(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException, FormException { - Jenkins.getInstance().doConfigExecutorsSubmit(req, rsp); - } - - @Override - public boolean hasPermission(Permission permission) { - // no one should be allowed to delete the master. - // this hides the ""delete"" link from the /computer/(master) page. - if(permission==Computer.DELETE) - return false; - // Configuration of master node requires ADMINISTER permission - return super.hasPermission(permission==Computer.CONFIGURE ? Jenkins.ADMINISTER : permission); - } - - @Override - public VirtualChannel getChannel() { - return localChannel; - } - - @Override - public Charset getDefaultCharset() { - return Charset.defaultCharset(); - } - - public List getLogRecords() throws IOException, InterruptedException { - return logRecords; - } - - public void doLaunchSlaveAgent(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { - // this computer never returns null from channel, so - // this method shall never be invoked. - rsp.sendError(SC_NOT_FOUND); - } - - protected Future _connect(boolean forceReconnect) { - return Futures.precomputed(null); - } - - /** - * {@link LocalChannel} instance that can be used to execute programs locally. - */ - public static final LocalChannel localChannel = new LocalChannel(threadPoolForRemoting); - } - - /** - * Shortcut for {@code Hudson.getInstance().lookup.get(type)} - */ - public static T lookup(Class type) { - return Jenkins.getInstance().lookup.get(type); - } - - /** - * Live view of recent {@link LogRecord}s produced by Hudson. - */ - public static List logRecords = Collections.emptyList(); // initialized to dummy value to avoid NPE - - /** - * Thread-safe reusable {@link XStream}. - */ - public static final XStream XSTREAM = new XStream2(); - - /** - * Alias to {@link #XSTREAM} so that one can access additional methods on {@link XStream2} more easily. - */ - public static final XStream2 XSTREAM2 = (XStream2)XSTREAM; - - private static final int TWICE_CPU_NUM = Math.max(4, Runtime.getRuntime().availableProcessors() * 2); - - /** - * Thread pool used to load configuration in parallel, to improve the start up time. - *

- * The idea here is to overlap the CPU and I/O, so we want more threads than CPU numbers. - */ - /*package*/ transient final ExecutorService threadPoolForLoad = new ThreadPoolExecutor( - TWICE_CPU_NUM, TWICE_CPU_NUM, - 5L, TimeUnit.SECONDS, new LinkedBlockingQueue(), new DaemonThreadFactory()); - - - private static void computeVersion(ServletContext context) { - // set the version - Properties props = new Properties(); - try { - InputStream is = Jenkins.class.getResourceAsStream(""jenkins-version.properties""); - if(is!=null) - props.load(is); - } catch (IOException e) { - e.printStackTrace(); // if the version properties is missing, that's OK. - } - String ver = props.getProperty(""version""); - if(ver==null) ver=""?""; - VERSION = ver; - context.setAttribute(""version"",ver); - - VERSION_HASH = Util.getDigestOf(ver).substring(0, 8); - SESSION_HASH = Util.getDigestOf(ver+System.currentTimeMillis()).substring(0, 8); - - if(ver.equals(""?"") || Boolean.getBoolean(""hudson.script.noCache"")) - RESOURCE_PATH = """"; - else - RESOURCE_PATH = ""/static/""+SESSION_HASH; - - VIEW_RESOURCE_PATH = ""/resources/""+ SESSION_HASH; - } - - /** - * Version number of this Hudson. - */ - public static String VERSION=""?""; - - /** - * Parses {@link #VERSION} into {@link VersionNumber}, or null if it's not parseable as a version number - * (such as when Hudson is run with ""mvn hudson-dev:run"") - */ - public static VersionNumber getVersion() { - try { - return new VersionNumber(VERSION); - } catch (NumberFormatException e) { - try { - // for non-released version of Hudson, this looks like ""1.345 (private-foobar), so try to approximate. - int idx = VERSION.indexOf(' '); - if (idx>0) - return new VersionNumber(VERSION.substring(0,idx)); - } catch (NumberFormatException _) { - // fall through - } - - // totally unparseable - return null; - } catch (IllegalArgumentException e) { - // totally unparseable - return null; - } - } - - /** - * Hash of {@link #VERSION}. - */ - public static String VERSION_HASH; - - /** - * Unique random token that identifies the current session. - * Used to make {@link #RESOURCE_PATH} unique so that we can set long ""Expires"" header. - * - * We used to use {@link #VERSION_HASH}, but making this session local allows us to - * reuse the same {@link #RESOURCE_PATH} for static resources in plugins. - */ - public static String SESSION_HASH; - - /** - * Prefix to static resources like images and javascripts in the war file. - * Either """" or strings like ""/static/VERSION"", which avoids Hudson to pick up - * stale cache when the user upgrades to a different version. - *

- * Value computed in {@link WebAppMain}. - */ - public static String RESOURCE_PATH = """"; - - /** - * Prefix to resources alongside view scripts. - * Strings like ""/resources/VERSION"", which avoids Hudson to pick up - * stale cache when the user upgrades to a different version. - *

- * Value computed in {@link WebAppMain}. - */ - public static String VIEW_RESOURCE_PATH = ""/resources/TBD""; - - public static boolean PARALLEL_LOAD = Configuration.getBooleanConfigParameter(""parallelLoad"", true); - public static boolean KILL_AFTER_LOAD = Configuration.getBooleanConfigParameter(""killAfterLoad"", false); - /** - * Enabled by default as of 1.337. Will keep it for a while just in case we have some serious problems. - */ - public static boolean FLYWEIGHT_SUPPORT = Configuration.getBooleanConfigParameter(""flyweightSupport"", true); - - /** - * Tentative switch to activate the concurrent build behavior. - * When we merge this back to the trunk, this allows us to keep - * this feature hidden for a while until we iron out the kinks. - * @see AbstractProject#isConcurrentBuild() - * @deprecated as of 1.464 - * This flag will have no effect. - */ - @Restricted(NoExternalUse.class) - public static boolean CONCURRENT_BUILD = true; - - /** - * Switch to enable people to use a shorter workspace name. - */ - private static final String WORKSPACE_DIRNAME = Configuration.getStringConfigParameter(""workspaceDirName"", ""workspace""); - - /** - * Automatically try to launch a slave when Jenkins is initialized or a new slave is created. - */ - public static boolean AUTOMATIC_SLAVE_LAUNCH = true; - - private static final Logger LOGGER = Logger.getLogger(Jenkins.class.getName()); - - private static final Pattern ICON_SIZE = Pattern.compile(""\\d+x\\d+""); - - public static final PermissionGroup PERMISSIONS = Permission.HUDSON_PERMISSIONS; - public static final Permission ADMINISTER = Permission.HUDSON_ADMINISTER; - public static final Permission READ = new Permission(PERMISSIONS,""Read"",Messages._Hudson_ReadPermission_Description(),Permission.READ,PermissionScope.JENKINS); - public static final Permission RUN_SCRIPTS = new Permission(PERMISSIONS, ""RunScripts"", Messages._Hudson_RunScriptsPermission_Description(),ADMINISTER,PermissionScope.JENKINS); - - /** - * {@link Authentication} object that represents the anonymous user. - * Because Acegi creates its own {@link AnonymousAuthenticationToken} instances, the code must not - * expect the singleton semantics. This is just a convenient instance. - * - * @since 1.343 - */ - public static final Authentication ANONYMOUS = new AnonymousAuthenticationToken( - ""anonymous"",""anonymous"",new GrantedAuthority[]{new GrantedAuthorityImpl(""anonymous"")}); - - static { - XSTREAM.alias(""jenkins"",Jenkins.class); - XSTREAM.alias(""slave"", DumbSlave.class); - XSTREAM.alias(""jdk"",JDK.class); - // for backward compatibility with <1.75, recognize the tag name ""view"" as well. - XSTREAM.alias(""view"", ListView.class); - XSTREAM.alias(""listView"", ListView.class); - // this seems to be necessary to force registration of converter early enough - Mode.class.getEnumConstants(); - - // double check that initialization order didn't do any harm - assert PERMISSIONS!=null; - assert ADMINISTER!=null; - } - -} -" -287,1," Object getValue(Object parent); - - /** - * Returns the name of this cascadable element. - * - * @return The name of this cascadable element. - */ -" -288,1," public String getInfo() { - - return (info); - - } - - - -" -289,1," protected boolean addInputFilter(InputFilter[] inputFilters, - String encodingName) { - if (encodingName.equals(""identity"")) { - // Skip - } else if (encodingName.equals(""chunked"")) { - inputBuffer.addActiveFilter - (inputFilters[Constants.CHUNKED_FILTER]); - contentDelimitation = true; - } else { - for (int i = 2; i < inputFilters.length; i++) { - if (inputFilters[i].getEncodingName() - .toString().equals(encodingName)) { - inputBuffer.addActiveFilter(inputFilters[i]); - return true; - } - } - return false; - } - return true; - } - - - /** - * Specialized utility method: find a sequence of lower case bytes inside - * a ByteChunk. - */ -" -290,1," public void changePassword_Resets_Session() throws Exception { - ScimUser user = createUser(); - - MockHttpSession session = new MockHttpSession(); - MockHttpSession afterLoginSession = (MockHttpSession) getMockMvc().perform(post(""/login.do"") - .session(session) - .accept(TEXT_HTML_VALUE) - .param(""username"", user.getUserName()) - .param(""password"", ""secr3T"")) - .andExpect(status().isFound()) - .andExpect(redirectedUrl(""/"")) - .andReturn().getRequest().getSession(false); - - assertTrue(session.isInvalid()); - assertNotNull(afterLoginSession); - assertNotNull(afterLoginSession.getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY)); - - MockHttpSession afterPasswordChange = (MockHttpSession) getMockMvc().perform(post(""/change_password.do"") - .session(afterLoginSession) - .with(csrf()) - .accept(TEXT_HTML_VALUE) - .param(""current_password"", ""secr3T"") - .param(""new_password"", ""secr3T1"") - .param(""confirm_password"", ""secr3T1"")) - .andExpect(status().isFound()) - .andExpect(redirectedUrl(""profile"")) - .andReturn().getRequest().getSession(false); - - assertTrue(afterLoginSession.isInvalid()); - assertNotNull(afterPasswordChange); - assertNotNull(afterPasswordChange.getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY)); - assertNotSame(afterLoginSession, afterPasswordChange); - - } - -" -291,1," public String changePassword( - Model model, - @RequestParam(""current_password"") String currentPassword, - @RequestParam(""new_password"") String newPassword, - @RequestParam(""confirm_password"") String confirmPassword, - HttpServletResponse response, - HttpServletRequest request) { - - PasswordConfirmationValidation validation = new PasswordConfirmationValidation(newPassword, confirmPassword); - if (!validation.valid()) { - model.addAttribute(""message_code"", validation.getMessageCode()); - response.setStatus(HttpStatus.UNPROCESSABLE_ENTITY.value()); - return ""change_password""; - } - - SecurityContext securityContext = SecurityContextHolder.getContext(); - Authentication authentication = securityContext.getAuthentication(); - String username = authentication.getName(); - - try { - changePasswordService.changePassword(username, currentPassword, newPassword); - request.getSession().invalidate(); - request.getSession(true); - securityContext.setAuthentication(authentication); - return ""redirect:profile""; - } catch (BadCredentialsException e) { - model.addAttribute(""message_code"", ""unauthorized""); - } catch (InvalidPasswordException e) { - model.addAttribute(""message"", e.getMessagesAsOneString()); - } - response.setStatus(HttpStatus.UNPROCESSABLE_ENTITY.value()); - return ""change_password""; - } -" -292,1," private XPathEvaluator createEvaluator(String xpath2) { - try { - return (XPathEvaluator)EVALUATOR_CONSTRUCTOR.newInstance(new Object[] {xpath}); - } catch (InvocationTargetException e) { - Throwable cause = e.getCause(); - if (cause instanceof RuntimeException) { - throw (RuntimeException)cause; - } - throw new RuntimeException(""Invalid XPath Expression: "" + xpath + "" reason: "" + e.getMessage(), e); - } catch (Throwable e) { - throw new RuntimeException(""Invalid XPath Expression: "" + xpath + "" reason: "" + e.getMessage(), e); - } - } - -" -293,1," protected RequestEntity createRequestEntity(Exchange exchange) throws CamelExchangeException { - Message in = exchange.getIn(); - if (in.getBody() == null) { - return null; - } - - RequestEntity answer = in.getBody(RequestEntity.class); - if (answer == null) { - try { - Object data = in.getBody(); - if (data != null) { - String contentType = ExchangeHelper.getContentType(exchange); - - if (contentType != null && HttpConstants.CONTENT_TYPE_JAVA_SERIALIZED_OBJECT.equals(contentType)) { - // serialized java object - Serializable obj = in.getMandatoryBody(Serializable.class); - // write object to output stream - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - HttpHelper.writeObjectToStream(bos, obj); - answer = new ByteArrayRequestEntity(bos.toByteArray(), HttpConstants.CONTENT_TYPE_JAVA_SERIALIZED_OBJECT); - IOHelper.close(bos); - } else if (data instanceof File || data instanceof GenericFile) { - // file based (could potentially also be a FTP file etc) - File file = in.getBody(File.class); - if (file != null) { - answer = new FileRequestEntity(file, contentType); - } - } else if (data instanceof String) { - // be a bit careful with String as any type can most likely be converted to String - // so we only do an instanceof check and accept String if the body is really a String - // do not fallback to use the default charset as it can influence the request - // (for example application/x-www-form-urlencoded forms being sent) - String charset = IOHelper.getCharsetName(exchange, false); - answer = new StringRequestEntity((String) data, contentType, charset); - } - // fallback as input stream - if (answer == null) { - // force the body as an input stream since this is the fallback - InputStream is = in.getMandatoryBody(InputStream.class); - answer = new InputStreamRequestEntity(is, contentType); - } - } - } catch (UnsupportedEncodingException e) { - throw new CamelExchangeException(""Error creating RequestEntity from message body"", exchange, e); - } catch (IOException e) { - throw new CamelExchangeException(""Error serializing message body"", exchange, e); - } - } - return answer; - } - -" -294,1," public void execute(String key, ActionMapping mapping) { - String location = key.substring(REDIRECT_ACTION_PREFIX - .length()); - ServletRedirectResult redirect = new ServletRedirectResult(); - container.inject(redirect); - String extension = getDefaultExtension(); - if (extension != null && extension.length() > 0) { - location += ""."" + extension; - } - redirect.setLocation(location); - mapping.setResult(redirect); - } - }); - } - }; - } - - /** - * Adds a parameter action. Should only be called during initialization - * - * @param prefix The string prefix to trigger the action - * @param parameterAction The parameter action to execute - * @since 2.1.0 - */ -" -295,1," private void findConstructor() { - try { - iConstructor = iClassToInstantiate.getConstructor(iParamTypes); - } catch (final NoSuchMethodException ex) { - throw new IllegalArgumentException(""InstantiateFactory: The constructor must exist and be public ""); - } - } - - /** - * Creates an object using the stored constructor. - * - * @return the new object - */ -" -296,1," private void checkParams() - throws Exception - { - if (vi == null) - { - throw new Exception(""no layers defined.""); - } - if (vi.length > 1) - { - for (int i = 0; i < vi.length - 1; i++) - { - if (vi[i] >= vi[i + 1]) - { - throw new Exception( - ""v[i] has to be smaller than v[i+1]""); - } - } - } - else - { - throw new Exception( - ""Rainbow needs at least 1 layer, such that v1 < v2.""); - } - } - - /** - * Getter for the number of layers - * - * @return the number of layers - */ -" -297,1," public boolean isTransferException() { - return transferException; - } - - /** - * If enabled and an Exchange failed processing on the consumer side, and if the caused Exception was send back serialized - * in the response as a application/x-java-serialized-object content type (for example using Jetty or Servlet Camel components). - * On the producer side the exception will be deserialized and thrown as is, instead of the AhcOperationFailedException. - * The caused exception is required to be serialized. - */ -" -298,1," public void setMethods(Set methods) { - this.methods = new HashSet(); - for (String method : methods) { - this.methods.add(method.toUpperCase()); - } - } - - /** - * @param authenticationEntryPoint the authenticationEntryPoint to set - */ -" -299,1," private EnumSet getValidatedExecutableTypes(DefaultValidatedExecutableTypesType validatedExecutables) { - if ( validatedExecutables == null ) { - return null; - } - - EnumSet executableTypes = EnumSet.noneOf( ExecutableType.class ); - executableTypes.addAll( validatedExecutables.getExecutableType() ); - - return executableTypes; - } -" -300,1," public boolean getValidateClientProvidedNewSessionId(); -" -301,1," private File mkdirsE(File dir) throws IOException { - if (dir.exists()) { - return dir; - } - filterNonNull().mkdirs(dir); - return IOUtils.mkdirs(dir); - } - -" -302,1," public static boolean isExpression(Object value) { - String expr = value.toString(); - return expr.startsWith(""%{"") && expr.endsWith(""}""); - } - -" -303,1," protected final GF2Polynomial[] invertMatrix(GF2Polynomial[] matrix) - { - GF2Polynomial[] a = new GF2Polynomial[matrix.length]; - GF2Polynomial[] inv = new GF2Polynomial[matrix.length]; - GF2Polynomial dummy; - int i, j; - // initialize a as a copy of matrix and inv as E(inheitsmatrix) - for (i = 0; i < mDegree; i++) - { - try - { - a[i] = new GF2Polynomial(matrix[i]); - inv[i] = new GF2Polynomial(mDegree); - inv[i].setBit(mDegree - 1 - i); - } - catch (RuntimeException BDNEExc) - { - BDNEExc.printStackTrace(); - } - } - // construct triangle matrix so that for each a[i] the first i bits are - // zero - for (i = 0; i < mDegree - 1; i++) - { - // find column where bit i is set - j = i; - while ((j < mDegree) && !a[j].testBit(mDegree - 1 - i)) - { - j++; - } - if (j >= mDegree) - { - throw new RuntimeException( - ""GF2nField.invertMatrix: Matrix cannot be inverted!""); - } - if (i != j) - { // swap a[i]/a[j] and inv[i]/inv[j] - dummy = a[i]; - a[i] = a[j]; - a[j] = dummy; - dummy = inv[i]; - inv[i] = inv[j]; - inv[j] = dummy; - } - for (j = i + 1; j < mDegree; j++) - { // add column i to all columns>i - // having their i-th bit set - if (a[j].testBit(mDegree - 1 - i)) - { - a[j].addToThis(a[i]); - inv[j].addToThis(inv[i]); - } - } - } - // construct Einheitsmatrix from a - for (i = mDegree - 1; i > 0; i--) - { - for (j = i - 1; j >= 0; j--) - { // eliminate the i-th bit in all - // columns < i - if (a[j].testBit(mDegree - 1 - i)) - { - a[j].addToThis(a[i]); - inv[j].addToThis(inv[i]); - } - } - } - return inv; - } - - /** - * Converts the given element in representation according to this field to a - * new element in representation according to B1 using the change-of-basis - * matrix calculated by computeCOBMatrix. - * - * @param elem the GF2nElement to convert - * @param basis the basis to convert elem to - * @return elem converted to a new element representation - * according to basis - * @see GF2nField#computeCOBMatrix - * @see GF2nField#getRandomRoot - * @see GF2nPolynomial - * @see ""P1363 A.7 p109ff"" - */ -" -304,1," public JDBCTableReader getTableReader(Connection connection, String tableName, ParseContext context) { - return new SQLite3TableReader(connection, tableName, context); - } -" -305,1," public Source getAssociatedStylesheet( - Source source, String media, String title, String charset) - throws TransformerConfigurationException - { - - String baseID; - InputSource isource = null; - Node node = null; - XMLReader reader = null; - - if (source instanceof DOMSource) - { - DOMSource dsource = (DOMSource) source; - - node = dsource.getNode(); - baseID = dsource.getSystemId(); - } - else - { - isource = SAXSource.sourceToInputSource(source); - baseID = isource.getSystemId(); - } - - // What I try to do here is parse until the first startElement - // is found, then throw a special exception in order to terminate - // the parse. - StylesheetPIHandler handler = new StylesheetPIHandler(baseID, media, - title, charset); - - // Use URIResolver. Patch from Dmitri Ilyin - if (m_uriResolver != null) - { - handler.setURIResolver(m_uriResolver); - } - - try - { - if (null != node) - { - TreeWalker walker = new TreeWalker(handler, new org.apache.xml.utils.DOM2Helper(), baseID); - - walker.traverse(node); - } - else - { - - // Use JAXP1.1 ( if possible ) - try - { - javax.xml.parsers.SAXParserFactory factory = - javax.xml.parsers.SAXParserFactory.newInstance(); - - factory.setNamespaceAware(true); - - if (m_isSecureProcessing) - { - try - { - factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); - } - catch (org.xml.sax.SAXException e) {} - } - - javax.xml.parsers.SAXParser jaxpParser = factory.newSAXParser(); - - reader = jaxpParser.getXMLReader(); - } - catch (javax.xml.parsers.ParserConfigurationException ex) - { - throw new org.xml.sax.SAXException(ex); - } - catch (javax.xml.parsers.FactoryConfigurationError ex1) - { - throw new org.xml.sax.SAXException(ex1.toString()); - } - catch (NoSuchMethodError ex2){} - catch (AbstractMethodError ame){} - - if (null == reader) - { - reader = XMLReaderFactory.createXMLReader(); - } - - // Need to set options! - reader.setContentHandler(handler); - reader.parse(isource); - } - } - catch (StopParseException spe) - { - - // OK, good. - } - catch (org.xml.sax.SAXException se) - { - throw new TransformerConfigurationException( - ""getAssociatedStylesheets failed"", se); - } - catch (IOException ioe) - { - throw new TransformerConfigurationException( - ""getAssociatedStylesheets failed"", ioe); - } - - return handler.getAssociatedStylesheet(); - } - - /** - * Create a new Transformer object that performs a copy - * of the source to the result. - * - * @return A Transformer object that may be used to perform a transformation - * in a single thread, never null. - * - * @throws TransformerConfigurationException May throw this during - * the parse when it is constructing the - * Templates object and fails. - */ -" -306,1," public Calendar ceil(Calendar cal) { - Calendar twoYearsFuture = (Calendar) cal.clone(); - twoYearsFuture.add(Calendar.YEAR, 2); - OUTER: - while (true) { - if (cal.compareTo(twoYearsFuture) > 0) { - // we went too far into the future - throw new RareOrImpossibleDateException(); - } - for (CalendarField f : CalendarField.ADJUST_ORDER) { - int cur = f.valueOf(cal); - int next = f.ceil(this,cur); - if (cur==next) continue; // this field is already in a good shape. move on to next - - // we are modifying this field, so clear all the lower level fields - for (CalendarField l=f.lowerField; l!=null; l=l.lowerField) - l.clear(cal); - - if (next<0) { - // we need to roll over to the next field. - f.rollUp(cal, 1); - f.setTo(cal,f.first(this)); - // since higher order field is affected by this, we need to restart from all over - continue OUTER; - } else { - f.setTo(cal,next); - if (f.redoAdjustmentIfModified) - continue OUTER; // when we modify DAY_OF_MONTH and DAY_OF_WEEK, do it all over from the top - } - } - return cal; // all fields adjusted - } - } - - /** - * Computes the nearest past timestamp that matched this cron tab. - *

- * More precisely, given the time 't', computes another smallest time x such that: - * - *

    - *
  • x <= t (inclusive) - *
  • x matches this crontab - *
- * - *

- * Note that if t already matches this cron, it's returned as is. - */ -" -307,1," public void run() { - try { - ObjectInputStream in = new ObjectInputStream(socket.getInputStream()); - while (!closed) { - Message msg = (Message) in.readObject(); - handle(msg); - } - } catch (EOFException eof) { - // Remote side has closed the connection, just cleanup. - try { - close(); - } catch (Exception unused) { - // no-op. - } - } catch (Exception e) { - if (!closed) { - LOG.log(Level.WARNING, ""Error in inbound message handling."", e); - try { - close(); - } catch (Exception unused) { - // no-op. - } - } - } - } - -" -308,1," public void setAllowJavaSerializedObject(boolean allowJavaSerializedObject) { - this.allowJavaSerializedObject = allowJavaSerializedObject; - } -" -309,1," private void updateGraph(ActionRequest actionRequest, - ActionResponse actionResponse) { - DBManager DBase = new DBManager(); - Connection con = DBase.getConnection(); - String graph_id = actionRequest.getParameter(""graph_id""); - actionResponse.setRenderParameter(""graph_id"", graph_id); - - String name = actionRequest.getParameter(""name""); - String description = actionRequest.getParameter(""description""); - String server_id = actionRequest.getParameter(""server_id""); - String xlabel = actionRequest.getParameter(""xlabel""); - String ylabel = actionRequest.getParameter(""ylabel""); - String timeframe = actionRequest.getParameter(""timeframe""); - String mbean = actionRequest.getParameter(""mbean""); - String dataname1 = actionRequest.getParameter(""dataname1""); - String data1operation = actionRequest.getParameter(""data1operation""); - String operation = actionRequest.getParameter(""operation""); - int archive = 0; - if (actionRequest.getParameter(""showArchive"") != null - && actionRequest.getParameter(""showArchive"").equals(""on"")) { - archive = 1; - } - - if (operation.equals(""other"")) { - operation = actionRequest.getParameter(""othermath""); - } - String dataname2 = actionRequest.getParameter(""dataname2""); - String data2operation = actionRequest.getParameter(""data2operation""); - if (data2operation == null) - data2operation = ""A""; - try { - PreparedStatement pStmt = con - .prepareStatement(""UPDATE graphs SET server_id="" - + server_id - + "", name='"" - + name - + ""', description='"" - + description - + ""', timeframe="" - + timeframe - + "", mbean='"" - + mbean - + ""', dataname1='"" - + dataname1 - + ""', xlabel='"" - + xlabel - + ""', ylabel='"" - + ylabel - + ""', data1operation='"" - + data1operation - + ""', operation='"" - + operation - + ""', data2operation='"" - + data2operation - + ""', dataname2='"" - + dataname2 - + ""', warninglevel1=0, warninglevel2=0, modified=CURRENT_TIMESTAMP, archive="" - + archive + "" WHERE graph_id="" + graph_id); - pStmt.executeUpdate(); - con.close(); - actionResponse.setRenderParameter(""message"", - ""Graph "" + name - + "" has been updated.""); - return; - - } catch (Exception e) { - actionResponse.setRenderParameter(""message"", - ""Error editing graph "" - + e.getMessage()); - return; - } - } - -" -310,1," protected void onSuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, Authentication authResult) throws IOException { - super.onSuccessfulAuthentication(request,response,authResult); - // make sure we have a session to store this successful authentication, given that we no longer - // let HttpSessionContextIntegrationFilter2 to create sessions. - // HttpSessionContextIntegrationFilter stores the updated SecurityContext object into this session later - // (either when a redirect is issued, via its HttpResponseWrapper, or when the execution returns to its - // doFilter method. - request.getSession(); - } - - /** - * Leave the information about login failure. - * - *

- * Otherwise it seems like Acegi doesn't really leave the detail of the failure anywhere. - */ - @Override -" -311,1," private Cache verifyCacheExists() { - int timeToWait = 0; - Cache cache = null; - while (timeToWait < TIME_TO_WAIT_FOR_CACHE) { - try { - cache = CacheFactory.getAnyInstance(); - break; - } catch (Exception ignore) { - // keep trying and hope for the best - } - try { - Thread.sleep(250); - } catch (InterruptedException ie) { - Thread.currentThread().interrupt(); - break; - } - timeToWait += 250; - } - - if (cache == null) { - cache = new CacheFactory().create(); - } - - return cache; - } - -" -312,1," public void clientCredentials_byDefault_WillNotLockoutDuringFailedBasicAuthAndFormData() throws Exception { - String clientId = ""testclient"" + generator.generate(); - String scopes = ""space.*.developer,space.*.admin,org.*.reader,org.123*.admin,*.*,*""; - setUpClients(clientId, scopes, scopes, GRANT_TYPES, true); - - String body = null; - for(int i = 0; i < 3; i++){ - body = getMockMvc().perform(post(""/oauth/token"") - .accept(MediaType.APPLICATION_JSON_VALUE) - .header(""Authorization"", ""Basic "" + new String(Base64.encode((clientId + "":"" + BADSECRET).getBytes()))) - .param(""grant_type"", ""client_credentials"") - ) - .andExpect(status().isUnauthorized()) - .andReturn().getResponse().getContentAsString(); - - body = getMockMvc().perform(post(""/oauth/token"") - .accept(MediaType.APPLICATION_JSON_VALUE) - .contentType(MediaType.APPLICATION_FORM_URLENCODED_VALUE) - .param(""grant_type"", ""client_credentials"") - .param(""client_id"", clientId) - .param(""client_secret"", BADSECRET) - ) - .andExpect(status().isUnauthorized()) - .andReturn().getResponse().getContentAsString(); - - } - - body = getMockMvc().perform(post(""/oauth/token"") - .accept(MediaType.APPLICATION_JSON_VALUE) - .header(""Authorization"", ""Basic "" + new String(Base64.encode((clientId + "":"" + SECRET).getBytes()))) - .param(""grant_type"", ""client_credentials"") - ) - .andExpect(status().isOk()) - .andReturn().getResponse().getContentAsString(); - } - - @Test -" -313,1," public String toStringInternal() { - String strValue=null; - try { - if( enc==null ) enc=DEFAULT_CHARACTER_ENCODING; - strValue = new String( buff, start, end-start, enc ); - /* - Does not improve the speed too much on most systems, - it's safer to use the ""clasical"" new String(). - - Most overhead is in creating char[] and copying, - the internal implementation of new String() is very close to - what we do. The decoder is nice for large buffers and if - we don't go to String ( so we can take advantage of reduced GC) - - // Method is commented out, in: - return B2CConverter.decodeString( enc ); - */ - } catch (java.io.UnsupportedEncodingException e) { - // Use the platform encoding in that case; the usage of a bad - // encoding will have been logged elsewhere already - strValue = new String(buff, start, end-start); - } - return strValue; - } - -" -314,1," public void repositoryVerificationTimeoutTest() throws Exception { - Client client = client(); - - Settings settings = ImmutableSettings.settingsBuilder() - .put(""location"", newTempDir(LifecycleScope.SUITE)) - .put(""random_control_io_exception_rate"", 1.0).build(); - logger.info(""--> creating repository that cannot write any files - should fail""); - assertThrows(client.admin().cluster().preparePutRepository(""test-repo-1"") - .setType(MockRepositoryModule.class.getCanonicalName()).setSettings(settings), - RepositoryVerificationException.class); - - logger.info(""--> creating repository that cannot write any files, but suppress verification - should be acked""); - assertAcked(client.admin().cluster().preparePutRepository(""test-repo-1"") - .setType(MockRepositoryModule.class.getCanonicalName()).setSettings(settings).setVerify(false)); - - logger.info(""--> verifying repository""); - assertThrows(client.admin().cluster().prepareVerifyRepository(""test-repo-1""), RepositoryVerificationException.class); - - File location = newTempDir(LifecycleScope.SUITE); - - logger.info(""--> creating repository""); - try { - client.admin().cluster().preparePutRepository(""test-repo-1"") - .setType(MockRepositoryModule.class.getCanonicalName()) - .setSettings(ImmutableSettings.settingsBuilder() - .put(""location"", location) - .put(""localize_location"", true) - ).get(); - fail(""RepositoryVerificationException wasn't generated""); - } catch (RepositoryVerificationException ex) { - assertThat(ex.getMessage(), containsString(""is not shared"")); - } - } - -" -315,1," public void execute(String key, ActionMapping mapping) { - String location = key.substring(REDIRECT_ACTION_PREFIX - .length()); - ServletRedirectResult redirect = new ServletRedirectResult(); - container.inject(redirect); - String extension = getDefaultExtension(); - if (extension != null && extension.length() > 0) { - location += ""."" + extension; - } - redirect.setLocation(location); - mapping.setResult(redirect); - } - }); - } - }; - } - - /** - * Adds a parameter action. Should only be called during initialization - * - * @param prefix The string prefix to trigger the action - * @param parameterAction The parameter action to execute - * @since 2.1.0 - */ -" -316,1," public void noUserSearchCausesUsernameNotFound() throws Exception { - DirContext ctx = mock(DirContext.class); - when(ctx.getNameInNamespace()).thenReturn(""""); - when(ctx.search(any(Name.class), any(String.class), any(Object[].class), any(SearchControls.class))) - .thenReturn(new EmptyEnumeration()); - - provider.contextFactory = createContextFactoryReturning(ctx); - - provider.authenticate(joe); - } - - @SuppressWarnings(""unchecked"") - @Test(expected = IncorrectResultSizeDataAccessException.class) -" -317,1," protected void addEmptyValueMapping(DefaultMapper mapper, String field, Object model) { - ParserContext parserContext = new FluentParserContext().evaluate(model.getClass()); - Expression target = expressionParser.parseExpression(field, parserContext); - try { - Class propertyType = target.getValueType(model); - Expression source = new StaticExpression(getEmptyValue(propertyType)); - DefaultMapping mapping = new DefaultMapping(source, target); - if (logger.isDebugEnabled()) { - logger.debug(""Adding empty value mapping for parameter '"" + field + ""'""); - } - mapper.addMapping(mapping); - } catch (EvaluationException e) { - } - } - - /** - * Adds a {@link DefaultMapping} between the given request parameter name and a matching model field. - * - * @param mapper the mapper to add the mapping to - * @param parameter the request parameter name - * @param model the model - */ -" -318,1," private boolean evaluate(String text) { - try { - InputSource inputSource = new InputSource(new StringReader(text)); - return ((Boolean)expression.evaluate(inputSource, XPathConstants.BOOLEAN)).booleanValue(); - } catch (XPathExpressionException e) { - return false; - } - } - - @Override -" diff --git a/train.csv b/train.csv deleted file mode 100644 index b7296285cd636328c39750eed8a2d7430e447a01..0000000000000000000000000000000000000000 --- a/train.csv +++ /dev/null @@ -1,16051 +0,0 @@ -,label,code -0,0," private List createAuthInfo(SolrZkClient zkClient) { - List ret = new LinkedList(); - - // 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 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 factory in the pool under key. - * - * @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 headers = redirectionResponse.getHeaders(); - if (!headers.isEmpty()) { - for (Entry 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 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("" 0) { - sb.append("" groups=\""""); - int n = 0; - Iterator 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 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()); - - } - - /** - *

Return a String representation of this user.

- */ - @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 transformList = new ArrayList(); - 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 x509Content = new ArrayList(); - 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 keys = (Set) 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 filterChains = (List) listFactoryBean - .getPropertyValues().getPropertyValue(""sourceList"").getValue(); - - filterChains.add(createFilterChain(element, pc)); - - pc.popAndRegisterContainingComponent(); - return null; - } - - /** - * Creates the {@code SecurityFilterChain} bean from an <http> 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 filterChain = new ManagedList( - 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 Closure whileClosure(final Predicate predicate, - final Closure 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(predicate, closure, doLoop); - } - - /** - * Constructor that performs no validation. - * Use whileClosure 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 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 results = new ArrayList(); - Iterator 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 = - """" + - """"+ - // but named entities should be - """"+ - ""]>"" + - """" + - "" &bar;"" + - "" "" + - "" "" + - "" "" + - "" "" + - """"; - 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 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 to, Set cc, Set 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 getFilters() { - List filters = new ArrayList(); - - 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(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> perms = new HashMap>(); - 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. - *

- * The default range is 200-299 - */ -" -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 lineList, final String requestID, - final int indentSpaces, final boolean includeProcessing) - { - // Create the request variable. - final ArrayList constructorArgs = - new ArrayList(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 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 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 values = new ArrayList(); - - // 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 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} in 6.2. - */ - @Deprecated - @FunctionalInterface -" -100,0," public DescriptorExtensionList compute(Class key) { - return DescriptorExtensionList.createDescriptorList(Jenkins.this,key); - } - }; - - /** - * {@link Computer}s in this Hudson system. Read-only. - */ -" -101,0," public synchronized Throwable fillInStackTrace() { - // This class does not provide a stack trace - return this; - } - } - - /** Unexpected end of data. */ - private static final IOException EXCEPTION_EOF = new DecodeException(""EOF""); - - /** %xx with not-hex digit */ - private static final IOException EXCEPTION_NOT_HEX_DIGIT = new DecodeException( - ""isHexDigit""); - - /** %-encoded slash is forbidden in resource path */ - private static final IOException EXCEPTION_SLASH = new DecodeException( - ""noSlash""); - - public UDecoder() - { - } - - /** URLDecode, will modify the source. Includes converting - * '+' to ' '. - */ - public void convert( ByteChunk mb ) - throws IOException - { - convert(mb, true); - } - - /** URLDecode, will modify the source. - */ - public void convert( ByteChunk mb, boolean query ) - throws IOException - { - int start=mb.getOffset(); - byte buff[]=mb.getBytes(); - int end=mb.getEnd(); - - int idx= ByteChunk.indexOf( buff, start, end, '%' ); - int idx2=-1; - if( query ) { - idx2= ByteChunk.indexOf( buff, start, (idx >= 0 ? idx : end), '+' ); - } - if( idx<0 && idx2<0 ) { - return; - } - - // idx will be the smallest positive index ( first % or + ) - if( (idx2 >= 0 && idx2 < idx) || idx < 0 ) { - idx=idx2; - } - - boolean noSlash = !(ALLOW_ENCODED_SLASH || query); - - for( int j=idx; j= end ) { - throw EXCEPTION_EOF; - } - byte b1= buff[j+1]; - byte b2=buff[j+2]; - if( !isHexDigit( b1 ) || ! isHexDigit(b2 )) - throw EXCEPTION_NOT_HEX_DIGIT; - - j+=2; - int res=x2c( b1, b2 ); - if (noSlash && (res == '/')) { - throw EXCEPTION_SLASH; - } - buff[idx]=(byte)res; - } - } - - mb.setEnd( idx ); - - return; - } - - // -------------------- Additional methods -------------------- - // XXX What do we do about charset ???? - - /** In-buffer processing - the buffer will be modified - * Includes converting '+' to ' '. - */ - public void convert( CharChunk mb ) - throws IOException - { - convert(mb, true); - } - - /** In-buffer processing - the buffer will be modified - */ - public void convert( CharChunk mb, boolean query ) - throws IOException - { - // log( ""Converting a char chunk ""); - int start=mb.getOffset(); - char buff[]=mb.getBuffer(); - int cend=mb.getEnd(); - - int idx= CharChunk.indexOf( buff, start, cend, '%' ); - int idx2=-1; - if( query ) { - idx2= CharChunk.indexOf( buff, start, (idx >= 0 ? idx : cend), '+' ); - } - if( idx<0 && idx2<0 ) { - return; - } - - // idx will be the smallest positive index ( first % or + ) - if( (idx2 >= 0 && idx2 < idx) || idx < 0 ) { - idx=idx2; - } - - boolean noSlash = !(ALLOW_ENCODED_SLASH || query); - for( int j=idx; j= cend ) { - // invalid - throw EXCEPTION_EOF; - } - char b1= buff[j+1]; - char b2=buff[j+2]; - if( !isHexDigit( b1 ) || ! isHexDigit(b2 )) - throw EXCEPTION_NOT_HEX_DIGIT; - - j+=2; - int res=x2c( b1, b2 ); - if (noSlash && (res == '/')) { - throw EXCEPTION_SLASH; - } - buff[idx]=(char)res; - } - } - mb.setEnd( idx ); - } - - /** URLDecode, will modify the source - * Includes converting '+' to ' '. - */ - public void convert(MessageBytes mb) - throws IOException - { - convert(mb, true); - } - - /** URLDecode, will modify the source - */ - public void convert(MessageBytes mb, boolean query) - throws IOException - { - - switch (mb.getType()) { - case MessageBytes.T_STR: - String strValue=mb.toString(); - if( strValue==null ) return; - mb.setString( convert( strValue, query )); - break; - case MessageBytes.T_CHARS: - CharChunk charC=mb.getCharChunk(); - convert( charC, query ); - break; - case MessageBytes.T_BYTES: - ByteChunk bytesC=mb.getByteChunk(); - convert( bytesC, query ); - break; - } - } - - // XXX Old code, needs to be replaced !!!! - // - public final String convert(String str) - { - return convert(str, true); - } - - 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(); - } - - - - private static boolean isHexDigit( int c ) { - return ( ( c>='0' && c<='9' ) || - ( c>='a' && c<='f' ) || - ( c>='A' && c<='F' )); - } - - private static int x2c( byte b1, byte b2 ) { - int digit= (b1>='A') ? ( (b1 & 0xDF)-'A') + 10 : - (b1 -'0'); - digit*=16; - digit +=(b2>='A') ? ( (b2 & 0xDF)-'A') + 10 : - (b2 -'0'); - return digit; - } - - private static int x2c( char b1, char b2 ) { - int digit= (b1>='A') ? ( (b1 & 0xDF)-'A') + 10 : - (b1 -'0'); - digit*=16; - digit +=(b2>='A') ? ( (b2 & 0xDF)-'A') + 10 : - (b2 -'0'); - return digit; - } - -" -102,0," private final static int skipSpace(InputAccessor acc, byte b) throws IOException - { - while (true) { - int ch = (int) b & 0xFF; - if (!(ch == ' ' || ch == '\r' || ch == '\n' || ch == '\t')) { - return ch; - } - if (!acc.hasMoreBytes()) { - return -1; - } - b = acc.nextByte(); - ch = (int) b & 0xFF; - } - } - -" -103,0," public void destroy() { - expiredExchanges.clear(); - super.destroy(); - } - -" -104,0," public ChannelRequestMatcherRegistry requires(String attribute) { - return addAttribute(attribute, requestMatchers); - } - } -}" -105,0," public Builder withIndex(int val) - { - index = val; - return this; - } - -" -106,0," void send(final String format, final Object... args); - } - -" -107,0," public void beforeHandshake(SocketWrapper socket) { - } - } -} -" -108,0," public void fileTest() { - File file = FileUtil.file(""d:/aaa"", ""bbb""); - Assert.assertNotNull(file); - - //构建目录中出现非子目录抛出异常 - FileUtil.file(file, ""../ccc""); - } - - @Test -" -109,0," public String toString() - { - return getValue().toString(); - } - -" -110,0," private BeanDefinition createSecurityFilterChain(BeanDefinition matcher, - ManagedList filters) { - BeanDefinitionBuilder sfc = BeanDefinitionBuilder - .rootBeanDefinition(DefaultSecurityFilterChain.class); - sfc.addConstructorArgValue(matcher); - sfc.addConstructorArgValue(filters); - return sfc.getBeanDefinition(); - } -" -111,0," public String idFromFilename(@Nonnull String filename) { - if (filename.matches(""[a-z0-9_. -]+"")) { - return filename; - } else { - StringBuilder buf = new StringBuilder(filename.length()); - final char[] chars = filename.toCharArray(); - for (int i = 0; i < chars.length; i++) { - char c = chars[i]; - if ('a' <= c && c <= 'z') { - buf.append(c); - } else if ('0' <= c && c <= '9') { - buf.append(c); - } else if ('_' == c || '.' == c || '-' == c || ' ' == c || '@' == c) { - buf.append(c); - } else if (c == '~') { - i++; - if (i < chars.length) { - buf.append(Character.toUpperCase(chars[i])); - } - } else if (c == '$') { - StringBuilder hex = new StringBuilder(4); - i++; - if (i < chars.length) { - hex.append(chars[i]); - } else { - break; - } - i++; - if (i < chars.length) { - hex.append(chars[i]); - } else { - break; - } - i++; - if (i < chars.length) { - hex.append(chars[i]); - } else { - break; - } - i++; - if (i < chars.length) { - hex.append(chars[i]); - } else { - break; - } - buf.append(Character.valueOf((char)Integer.parseInt(hex.toString(), 16))); - } - } - return buf.toString(); - } - } - - /** - * {@inheritDoc} - */ - @Override -" -112,0," protected synchronized void stopInternal() throws LifecycleException { - - super.stopInternal(); - - sso = null; - } -" -113,0," public Map getFragments() { - return fragments; - } - } -} -" -114,0," private void testModified() - throws Exception - { - KeyFactory kFact = KeyFactory.getInstance(""DSA"", ""BC""); - PublicKey pubKey = kFact.generatePublic(PUBLIC_KEY); - Signature sig = Signature.getInstance(""DSA"", ""BC""); - - for (int i = 0; i != MODIFIED_SIGNATURES.length; i++) - { - sig.initVerify(pubKey); - - sig.update(Strings.toByteArray(""Hello"")); - - boolean failed; - - try - { - failed = !sig.verify(Hex.decode(MODIFIED_SIGNATURES[i])); - } - catch (SignatureException e) - { - failed = true; - } - - isTrue(""sig verified when shouldn't"", failed); - } - } - -" -115,0," public void setUp() throws Exception - { - super.setUp(); - _successfulResult = mock(AuthenticationResult.class); - _errorResult = mock(AuthenticationResult.class); - _authenticationProvider = mock(UsernamePasswordAuthenticationProvider.class); - when(_authenticationProvider.authenticate(eq(VALID_USERNAME), eq(VALID_PASSWORD))).thenReturn(_successfulResult); - when(_authenticationProvider.authenticate(eq(VALID_USERNAME), not(eq(VALID_PASSWORD)))).thenReturn(_errorResult); - when(_authenticationProvider.authenticate(not(eq(VALID_USERNAME)), anyString())).thenReturn(_errorResult); - _negotiator = new PlainNegotiator(_authenticationProvider); - } - - @Override -" -116,0," protected void doStop() throws Exception { - super.doStop(); - // only stop non-shared client - if (!sharedClient && client != null) { - client.stop(); - // stop thread pool - Object tp = getClientThreadPool(); - if (tp instanceof LifeCycle) { - LOG.debug(""Stopping client thread pool {}"", tp); - ((LifeCycle) tp).stop(); - } - } - } -" -117,0," public int doRead(ByteChunk chunk, Request req) - throws IOException { - - if (endChunk) - return -1; - - if(needCRLFParse) { - needCRLFParse = false; - parseCRLF(false); - } - - if (remaining <= 0) { - if (!parseChunkHeader()) { - throw new IOException(""Invalid chunk header""); - } - if (endChunk) { - parseEndChunk(); - return -1; - } - } - - int result = 0; - - if (pos >= lastValid) { - if (readBytes() < 0) { - throw new IOException( - ""Unexpected end of stream whilst reading request body""); - } - } - - if (remaining > (lastValid - pos)) { - result = lastValid - pos; - remaining = remaining - result; - chunk.setBytes(buf, pos, result); - pos = lastValid; - } else { - result = remaining; - chunk.setBytes(buf, pos, remaining); - pos = pos + remaining; - remaining = 0; - //we need a CRLF - if ((pos+1) >= lastValid) { - //if we call parseCRLF we overrun the buffer here - //so we defer it to the next call BZ 11117 - needCRLFParse = true; - } else { - parseCRLF(false); //parse the CRLF immediately - } - } - - return result; - - } - - - // ---------------------------------------------------- InputFilter Methods - - - /** - * Read the content length from the request. - */ - @Override -" -118,0," private static void addUsers(final Set users, final TaskListener listener, @CheckForNull Run run, final EnvVars env, - final Set to, final Set cc, final Set bcc, final IDebug debug) { - for (final User user : users) { - if (EmailRecipientUtils.isExcludedRecipient(user, listener)) { - debug.send(""User %s is an excluded recipient."", user.getFullName()); - } else { - final String userAddress = EmailRecipientUtils.getUserConfiguredEmail(user); - if (userAddress != null) { - try { - Authentication auth = user.impersonate(); - if (run != null && !run.getACL().hasPermission(auth, Item.READ)) { - if (SEND_TO_USERS_WITHOUT_READ) { - listener.getLogger().printf(""Warning: user %s has no permission to view %s, but sending mail anyway%n"", userAddress, run.getFullDisplayName()); - } else { - listener.getLogger().printf(""Not sending mail to user %s with no permission to view %s"", userAddress, run.getFullDisplayName()); - continue; - } - } - } catch (UsernameNotFoundException x) { - if (SEND_TO_UNKNOWN_USERS) { - listener.getLogger().printf(""Warning: %s is not a recognized user, but sending mail anyway%n"", userAddress); - } else { - listener.getLogger().printf(""Not sending mail to unregistered user %s%n"", userAddress); - continue; - } - } - debug.send(""Adding %s with address %s"", user.getFullName(), userAddress); - EmailRecipientUtils.addAddressesFromRecipientList(to, cc, bcc, userAddress, env, listener); - } else { - listener.getLogger().println(""Failed to send e-mail to "" - + user.getFullName() - + "" because no e-mail address is known, and no default e-mail domain is configured""); - } - } - } - } -" -119,0," public String getDisplayName() { - return ""Suspects Causing the Build to Begin Failing""; - } - } - -} -" -120,0," public Object getProperty(String name) { - String repl = name; - if (replacements.get(name) != null) { - repl = (String) replacements.get(name); - } - return IntrospectionUtils.getProperty(protocolHandler, repl); - } - - - /** - * Set a configured property. - */ -" -121,0," public C anyRequest() { - return requestMatchers(ANY_REQUEST); - } - - /** - * Maps a {@link List} of - * {@link org.springframework.security.web.util.matcher.AntPathRequestMatcher} - * instances. - * - * @param method the {@link HttpMethod} to use for any - * {@link HttpMethod}. - * - * @return the object that is chained after creating the {@link RequestMatcher} - */ -" -122,0," protected abstract Log getLog(); - - - /** - * The string manager for this package. - */ -" -123,0," private void assertRecoveryStateWithoutStage(RecoveryState state, int shardId, Type type, - String sourceNode, String targetNode, boolean hasRestoreSource) { - assertThat(state.getShardId().getId(), equalTo(shardId)); - assertThat(state.getType(), equalTo(type)); - if (sourceNode == null) { - assertNull(state.getSourceNode()); - } else { - assertNotNull(state.getSourceNode()); - assertThat(state.getSourceNode().getName(), equalTo(sourceNode)); - } - if (targetNode == null) { - assertNull(state.getTargetNode()); - } else { - assertNotNull(state.getTargetNode()); - assertThat(state.getTargetNode().getName(), equalTo(targetNode)); - } - if (hasRestoreSource) { - assertNotNull(state.getRestoreSource()); - } else { - assertNull(state.getRestoreSource()); - } - - } - -" -124,0," public BeanDefinition parse(Element element, ParserContext parserContext) { - List interceptUrls = DomUtils.getChildElementsByTagName(element, - ""intercept-url""); - - // Check for attributes that aren't allowed in this context - for (Element elt : interceptUrls) { - if (StringUtils.hasLength(elt - .getAttribute(HttpSecurityBeanDefinitionParser.ATT_REQUIRES_CHANNEL))) { - parserContext.getReaderContext().error( - ""The attribute '"" - + HttpSecurityBeanDefinitionParser.ATT_REQUIRES_CHANNEL - + ""' isn't allowed here."", elt); - } - - if (StringUtils.hasLength(elt - .getAttribute(HttpSecurityBeanDefinitionParser.ATT_FILTERS))) { - parserContext.getReaderContext().error( - ""The attribute '"" + HttpSecurityBeanDefinitionParser.ATT_FILTERS - + ""' isn't allowed here."", elt); - } - } - - BeanDefinition mds = createSecurityMetadataSource(interceptUrls, false, element, - parserContext); - - String id = element.getAttribute(AbstractBeanDefinitionParser.ID_ATTRIBUTE); - - if (StringUtils.hasText(id)) { - parserContext.registerComponent(new BeanComponentDefinition(mds, id)); - parserContext.getRegistry().registerBeanDefinition(id, mds); - } - - return mds; - } - -" -125,0," private String getComponentName() { - Class c = getClass(); - String name = c.getName(); - int dot = name.lastIndexOf('.'); - - return name.substring(dot + 1).toLowerCase(); - } - - @Inject(value = StrutsConstants.STRUTS_DEVMODE, required = false) -" -126,0," public void testSecurityAnnotationsSimple() throws Exception { - doTest(DenyAllServlet.class.getName(), false, false, false); - } - -" -127,0," public boolean nextRow(ContentHandler handler, ParseContext context) throws IOException, SAXException { - //lazy initialization - if (results == null) { - reset(); - } - try { - if (!results.next()) { - return false; - } - } catch (SQLException e) { - throw new IOExceptionWithCause(e); - } - try { - ResultSetMetaData meta = results.getMetaData(); - handler.startElement(XHTMLContentHandler.XHTML, ""tr"", ""tr"", EMPTY_ATTRIBUTES); - for (int i = 1; i <= meta.getColumnCount(); i++) { - handler.startElement(XHTMLContentHandler.XHTML, ""td"", ""td"", EMPTY_ATTRIBUTES); - handleCell(meta, i, handler, context); - handler.endElement(XHTMLContentHandler.XHTML, ""td"", ""td""); - } - handler.endElement(XHTMLContentHandler.XHTML, ""tr"", ""tr""); - } catch (SQLException e) { - throw new IOExceptionWithCause(e); - } - rows++; - return true; - } - -" -128,0," public int getIndex() { - return index; - } - - @Override -" -129,0," public EnumSet context() { - return EnumSet.of(MetaData.XContentContext.GATEWAY, MetaData.XContentContext.SNAPSHOT); - } - - } - } - -} -" -130,0," public static void beforeTests() throws Exception { - initCore(""solrconfig.xml"",""schema.xml""); - } - - @Override - @Before -" -131,0," public Object create(Context context) throws Exception { - ObjectFactory objFactory = context.getContainer().getInstance(ObjectFactory.class); - try { - return objFactory.buildBean(name, null, true); - } catch (ClassNotFoundException ex) { - throw new ConfigurationException(""Unable to load bean ""+type.getName()+"" (""+name+"")""); - } - } - - } - -} -" -132,0," public void changePassword_Returns422UnprocessableEntity_NewPasswordSameAsOld() throws Exception { - - Mockito.reset(passwordValidator); - - when(expiringCodeStore.retrieveCode(""emailed_code"")) - .thenReturn(new ExpiringCode(""emailed_code"", new Timestamp(System.currentTimeMillis()+ UaaResetPasswordService.PASSWORD_RESET_LIFETIME), - ""{\""user_id\"":\""eyedee\"",\""username\"":\""user@example.com\"",\""passwordModifiedTime\"":null,\""client_id\"":\""\"",\""redirect_uri\"":\""\""}"", - null)); - - ScimUser scimUser = new ScimUser(""eyedee"", ""user@example.com"", ""User"", ""Man""); - scimUser.setMeta(new ScimMeta(new Date(System.currentTimeMillis()-(1000*60*60*24)), new Date(System.currentTimeMillis()-(1000*60*60*24)), 0)); - scimUser.addEmail(""user@example.com""); - scimUser.setVerified(true); - - when(scimUserProvisioning.retrieve(""eyedee"")).thenReturn(scimUser); - when(scimUserProvisioning.checkPasswordMatches(""eyedee"", ""new_secret"")).thenReturn(true); - - MockHttpServletRequestBuilder post = post(""/password_change"") - .contentType(APPLICATION_JSON) - .content(""{\""code\"":\""emailed_code\"",\""new_password\"":\""new_secret\""}"") - .accept(APPLICATION_JSON); - - SecurityContextHolder.getContext().setAuthentication(new MockAuthentication()); - - mockMvc.perform(post) - .andExpect(status().isUnprocessableEntity()) - .andExpect(content().string(JsonObjectMatcherUtils.matchesJsonObject(new JSONObject().put(""error_description"", ""Your new password cannot be the same as the old password."").put(""message"", ""Your new password cannot be the same as the old password."").put(""error"", ""invalid_password"")))); - } -" -133,0," protected void startInternal() throws LifecycleException { - String pathName = getPathname(); - try (InputStream is = ConfigFileLoader.getInputStream(pathName)) { - // Load the contents of the database file - if (log.isDebugEnabled()) { - log.debug(sm.getString(""memoryRealm.loadPath"", pathName)); - } - - Digester digester = getDigester(); - try { - synchronized (digester) { - digester.push(this); - digester.parse(is); - } - } catch (Exception e) { - throw new LifecycleException(sm.getString(""memoryRealm.readXml""), e); - } finally { - digester.reset(); - } - } catch (IOException ioe) { - throw new LifecycleException(sm.getString(""memoryRealm.loadExist"", pathName), ioe); - } - - super.startInternal(); - } -" -134,0," public Container getContainer() { - - return (container); - - } - - - /** - * Set the Container with which this Realm has been associated. - * - * @param container The associated Container - */ - @Override -" -135,0," public String getIconFileName() { - return PLUGIN_IMAGES_URL + ""icon.png""; - } - - @Override -" -136,0," public String toString() { - final StringBuilder sb = new StringBuilder(); - sb.append( ""MetaConstraint"" ); - sb.append( ""{constraintType="" ).append( constraintDescriptor.getAnnotation().annotationType().getName() ); - sb.append( "", location="" ).append( location ); - sb.append( ""}"" ); - return sb.toString(); - } -" -137,0," protected Collection getStandardAttributes() { - Class clz = getClass(); - Collection standardAttributes = standardAttributesMap.get(clz); - if (standardAttributes == null) { - Collection methods = AnnotationUtils.getAnnotatedMethods(clz, StrutsTagAttribute.class); - standardAttributes = new HashSet<>(methods.size()); - for(Method m : methods) { - standardAttributes.add(StringUtils.uncapitalize(m.getName().substring(3))); - } - standardAttributesMap.putIfAbsent(clz, standardAttributes); - } - return standardAttributes; - } - -" -138,0," public Builder withIndex(long val) - { - index = val; - return this; - } - -" -139,0," private Priority getPriority(String severity) { - if (SEVERITY_FATAL.equals(severity) || SEVERITY_ERROR.equals(severity)) { - return Priority.HIGH; - } - if (SEVERITY_INFORMATIONAL.equals(severity)) { - return Priority.LOW; - } - return Priority.NORMAL; - } - -" -140,0," public static Closure forClosure(final int count, final Closure closure) { - if (count <= 0 || closure == null) { - return NOPClosure.nopClosure(); - } - if (count == 1) { - return (Closure) closure; - } - return new ForClosure(count, closure); - } - - /** - * Constructor that performs no validation. - * Use forClosure if you want that. - * - * @param count the number of times to execute the closure - * @param closure the closure to execute, not null - */ -" -141,0," public static boolean isWindows() { - return WINDOWS_SEPARATOR == File.separatorChar; - } - - /** - * 列出目录文件
- * 给定的绝对路径不能是压缩包中的路径 - * - * @param path 目录绝对路径或者相对路径 - * @return 文件列表(包含目录) - */ -" -142,0," public String getOriginalName() { - return originalName; - } - } - -} -" -143,0," protected void engineInitVerify(PublicKey publicKey) - throws InvalidKeyException - { - CipherParameters param = ECUtils.generatePublicKeyParameter(publicKey); - - digest.reset(); - signer.init(false, param); - } - -" -144,0," public void readRequest(HttpServletRequest request, HttpMessage message) { - LOG.trace(""readRequest {}"", request); - - // lets force a parse of the body and headers - message.getBody(); - // populate the headers from the request - Map headers = message.getHeaders(); - - //apply the headerFilterStrategy - Enumeration names = request.getHeaderNames(); - while (names.hasMoreElements()) { - String name = (String)names.nextElement(); - String value = request.getHeader(name); - // use http helper to extract parameter value as it may contain multiple values - Object extracted = HttpHelper.extractHttpParameterValue(value); - // mapping the content-type - if (name.toLowerCase().equals(""content-type"")) { - name = Exchange.CONTENT_TYPE; - } - if (headerFilterStrategy != null - && !headerFilterStrategy.applyFilterToExternalHeaders(name, extracted, message.getExchange())) { - HttpHelper.appendHeader(headers, name, extracted); - } - } - - if (request.getCharacterEncoding() != null) { - headers.put(Exchange.HTTP_CHARACTER_ENCODING, request.getCharacterEncoding()); - message.getExchange().setProperty(Exchange.CHARSET_NAME, request.getCharacterEncoding()); - } - - try { - populateRequestParameters(request, message); - } catch (Exception e) { - throw new RuntimeCamelException(""Cannot read request parameters due "" + e.getMessage(), e); - } - - Object body = message.getBody(); - // reset the stream cache if the body is the instance of StreamCache - if (body instanceof StreamCache) { - ((StreamCache)body).reset(); - } - - // store the method and query and other info in headers as String types - headers.put(Exchange.HTTP_METHOD, request.getMethod()); - headers.put(Exchange.HTTP_QUERY, request.getQueryString()); - headers.put(Exchange.HTTP_URL, request.getRequestURL().toString()); - headers.put(Exchange.HTTP_URI, request.getRequestURI()); - headers.put(Exchange.HTTP_PATH, request.getPathInfo()); - headers.put(Exchange.CONTENT_TYPE, request.getContentType()); - - if (LOG.isTraceEnabled()) { - LOG.trace(""HTTP method {}"", request.getMethod()); - LOG.trace(""HTTP query {}"", request.getQueryString()); - LOG.trace(""HTTP url {}"", request.getRequestURL()); - LOG.trace(""HTTP uri {}"", request.getRequestURI()); - LOG.trace(""HTTP path {}"", request.getPathInfo()); - LOG.trace(""HTTP content-type {}"", request.getContentType()); - } - - // if content type is serialized java object, then de-serialize it to a Java object - if (request.getContentType() != null && HttpConstants.CONTENT_TYPE_JAVA_SERIALIZED_OBJECT.equals(request.getContentType())) { - // only deserialize java if allowed - if (allowJavaSerializedObject || isTransferException()) { - try { - InputStream is = message.getExchange().getContext().getTypeConverter().mandatoryConvertTo(InputStream.class, body); - Object object = HttpHelper.deserializeJavaObjectFromStream(is, message.getExchange().getContext()); - if (object != null) { - message.setBody(object); - } - } catch (Exception e) { - throw new RuntimeCamelException(""Cannot deserialize body to Java object"", e); - } - } else { - // set empty body - message.setBody(null); - } - } - - populateAttachments(request, message); - } - -" -145,0," public void testStripExpression() throws Exception { - // given - ValueStack stack = container.getInstance(ValueStackFactory.class).createValueStack(); - String anExpression = ""%{foo}""; - - // when - String actual = ComponentUtils.stripExpressionIfAltSyntax(stack, anExpression); - - // then - assertEquals(actual, ""foo""); - } - -" -146,0," public void setMaxExtensionSize(int maxExtensionSize) { - this.maxExtensionSize = maxExtensionSize; - } - - - /** - * This field indicates if the protocol is treated as if it is secure. This - * normally means https is being used but can be used to fake https e.g - * behind a reverse proxy. - */ -" -147,0," public boolean isStatisticsProvider() { - return false; - } - -" -148,0," public void addRecipients(final ExtendedEmailPublisherContext context, final EnvVars env, - final Set to, final Set cc, final Set 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(); - - Set users = null; - - final Run currentRun = context.getRun(); - if (currentRun == null) { - debug.send(""currentRun was null""); - } else { - if (!Objects.equals(currentRun.getResult(), Result.FAILURE)) { - debug.send(""currentBuild did not fail""); - } else { - users = new HashSet<>(); - debug.send(""Collecting builds with suspects...""); - final HashSet> buildsWithSuspects = new HashSet<>(); - Run firstFailedBuild = currentRun; - Run candidate = currentRun; - while (candidate != null) { - final Result candidateResult = candidate.getResult(); - if ( candidateResult == null || !candidateResult.isWorseOrEqualTo(Result.FAILURE) ) { - break; - } - firstFailedBuild = candidate; - candidate = candidate.getPreviousCompletedBuild(); - } - if (firstFailedBuild instanceof AbstractBuild) { - buildsWithSuspects.add(firstFailedBuild); - } else { - debug.send("" firstFailedBuild was not an instance of AbstractBuild""); - } - debug.send(""Collecting suspects...""); - users.addAll(RecipientProviderUtilities.getChangeSetAuthors(buildsWithSuspects, debug)); - users.addAll(RecipientProviderUtilities.getUsersTriggeringTheBuilds(buildsWithSuspects, debug)); - } - } - if (users != null) { - RecipientProviderUtilities.addUsers(users, context, env, to, cc, bcc, debug); - } - } - - @Extension -" -149,0," private void filterWithParameterForMethod(String methodParam, String expectedMethod) - throws IOException, ServletException { - MockHttpServletRequest request = new MockHttpServletRequest(""POST"", ""/hotels""); - if(methodParam != null) { - request.addParameter(""_method"", methodParam); - } - MockHttpServletResponse response = new MockHttpServletResponse(); - - FilterChain filterChain = new FilterChain() { - - @Override - public void doFilter(ServletRequest filterRequest, - ServletResponse filterResponse) throws IOException, ServletException { - assertEquals(""Invalid method"", expectedMethod, - ((HttpServletRequest) filterRequest).getMethod()); - } - }; - this.filter.doFilter(request, response, filterChain); - } - -" -150,0," public void restorePersistentSettingsTest() throws Exception { - logger.info(""--> start 2 nodes""); - Settings nodeSettings = settingsBuilder() - .put(""discovery.type"", ""zen"") - .put(""discovery.zen.ping_timeout"", ""200ms"") - .put(""discovery.initial_state_timeout"", ""500ms"") - .build(); - internalCluster().startNode(nodeSettings); - Client client = client(); - String secondNode = internalCluster().startNode(nodeSettings); - logger.info(""--> wait for the second node to join the cluster""); - assertThat(client.admin().cluster().prepareHealth().setWaitForNodes(""2"").get().isTimedOut(), equalTo(false)); - - int random = randomIntBetween(10, 42); - - logger.info(""--> set test persistent setting""); - client.admin().cluster().prepareUpdateSettings().setPersistentSettings( - ImmutableSettings.settingsBuilder() - .put(ElectMasterService.DISCOVERY_ZEN_MINIMUM_MASTER_NODES, 2) - .put(IndicesTTLService.INDICES_TTL_INTERVAL, random, TimeUnit.MINUTES)) - .execute().actionGet(); - - assertThat(client.admin().cluster().prepareState().setRoutingTable(false).setNodes(false).execute().actionGet().getState() - .getMetaData().persistentSettings().getAsTime(IndicesTTLService.INDICES_TTL_INTERVAL, TimeValue.timeValueMinutes(1)).millis(), equalTo(TimeValue.timeValueMinutes(random).millis())); - assertThat(client.admin().cluster().prepareState().setRoutingTable(false).setNodes(false).execute().actionGet().getState() - .getMetaData().persistentSettings().getAsInt(ElectMasterService.DISCOVERY_ZEN_MINIMUM_MASTER_NODES, -1), equalTo(2)); - - logger.info(""--> create repository""); - PutRepositoryResponse putRepositoryResponse = client.admin().cluster().preparePutRepository(""test-repo"") - .setType(""fs"").setSettings(ImmutableSettings.settingsBuilder().put(""location"", randomRepoPath())).execute().actionGet(); - assertThat(putRepositoryResponse.isAcknowledged(), equalTo(true)); - - logger.info(""--> start snapshot""); - CreateSnapshotResponse createSnapshotResponse = client.admin().cluster().prepareCreateSnapshot(""test-repo"", ""test-snap"").setWaitForCompletion(true).execute().actionGet(); - assertThat(createSnapshotResponse.getSnapshotInfo().totalShards(), equalTo(0)); - assertThat(createSnapshotResponse.getSnapshotInfo().successfulShards(), equalTo(0)); - assertThat(client.admin().cluster().prepareGetSnapshots(""test-repo"").setSnapshots(""test-snap"").execute().actionGet().getSnapshots().get(0).state(), equalTo(SnapshotState.SUCCESS)); - - logger.info(""--> clean the test persistent setting""); - client.admin().cluster().prepareUpdateSettings().setPersistentSettings( - ImmutableSettings.settingsBuilder() - .put(ElectMasterService.DISCOVERY_ZEN_MINIMUM_MASTER_NODES, 1) - .put(IndicesTTLService.INDICES_TTL_INTERVAL, TimeValue.timeValueMinutes(1))) - .execute().actionGet(); - assertThat(client.admin().cluster().prepareState().setRoutingTable(false).setNodes(false).execute().actionGet().getState() - .getMetaData().persistentSettings().getAsTime(IndicesTTLService.INDICES_TTL_INTERVAL, TimeValue.timeValueMinutes(1)).millis(), equalTo(TimeValue.timeValueMinutes(1).millis())); - - stopNode(secondNode); - assertThat(client.admin().cluster().prepareHealth().setWaitForNodes(""1"").get().isTimedOut(), equalTo(false)); - - logger.info(""--> restore snapshot""); - client.admin().cluster().prepareRestoreSnapshot(""test-repo"", ""test-snap"").setRestoreGlobalState(true).setWaitForCompletion(true).execute().actionGet(); - assertThat(client.admin().cluster().prepareState().setRoutingTable(false).setNodes(false).execute().actionGet().getState() - .getMetaData().persistentSettings().getAsTime(IndicesTTLService.INDICES_TTL_INTERVAL, TimeValue.timeValueMinutes(1)).millis(), equalTo(TimeValue.timeValueMinutes(random).millis())); - - logger.info(""--> ensure that zen discovery minimum master nodes wasn't restored""); - assertThat(client.admin().cluster().prepareState().setRoutingTable(false).setNodes(false).execute().actionGet().getState() - .getMetaData().persistentSettings().getAsInt(ElectMasterService.DISCOVERY_ZEN_MINIMUM_MASTER_NODES, -1), not(equalTo(2))); - } - - @Test -" -151,0," public void init(FilterConfig conf) throws ServletException { - if (conf != null && ""zookeeper"".equals(conf.getInitParameter(""signer.secret.provider""))) { - SolrZkClient zkClient = - (SolrZkClient)conf.getServletContext().getAttribute(KerberosPlugin.DELEGATION_TOKEN_ZK_CLIENT); - try { - conf.getServletContext().setAttribute(""signer.secret.provider.zookeeper.curator.client"", - getCuratorClient(zkClient)); - } catch (InterruptedException | KeeperException e) { - throw new ServletException(e); - } - } - super.init(conf); - } - - /** - * Return the ProxyUser Configuration. FilterConfig properties beginning with - * ""solr.impersonator.user.name"" will be added to the configuration. - */ - @Override -" -152,0," javax.xml.transform.Templates processFromNode(Node node, String systemID) - throws TransformerConfigurationException - { - - m_DOMsystemID = systemID; - - return processFromNode(node); - } - - /** - * Get InputSource specification(s) that are associated with the - * given document specified in the source param, - * via the xml-stylesheet processing instruction - * (see http://www.w3.org/TR/xml-stylesheet/), and that matches - * the given criteria. Note that it is possible to return several stylesheets - * that match the criteria, in which case they are applied as if they were - * a list of imports or cascades. - * - *

Note that DOM2 has it's own mechanism for discovering stylesheets. - * Therefore, there isn't a DOM version of this method.

- * - * - * @param source The XML source that is to be searched. - * @param media The media attribute to be matched. May be null, in which - * case the prefered templates will be used (i.e. alternate = no). - * @param title The value of the title attribute to match. May be null. - * @param charset The value of the charset attribute to match. May be null. - * - * @return A Source object capable of being used to create a Templates object. - * - * @throws TransformerConfigurationException - */ -" -153,0," protected abstract void handle(Message msg) throws IOException; - - @Override -" -154,0," public String[] getRoles(Principal principal) { - if (principal instanceof GenericPrincipal) { - return ((GenericPrincipal) principal).getRoles(); - } - - String className = principal.getClass().getSimpleName(); - throw new IllegalStateException(sm.getString(""realmBase.cannotGetRoles"", className)); - } -" -155,0," public ClassLoader bind(boolean usePrivilegedAction, ClassLoader originalClassLoader) { - Loader loader = getLoader(); - ClassLoader webApplicationClassLoader = null; - if (loader != null) { - webApplicationClassLoader = loader.getClassLoader(); - } - - if (originalClassLoader == null) { - if (usePrivilegedAction) { - PrivilegedAction pa = new PrivilegedGetTccl(); - originalClassLoader = AccessController.doPrivileged(pa); - } else { - originalClassLoader = Thread.currentThread().getContextClassLoader(); - } - } - - if (webApplicationClassLoader == null || - webApplicationClassLoader == originalClassLoader) { - // Not possible or not necessary to switch class loaders. Return - // null to indicate this. - return null; - } - - ThreadBindingListener threadBindingListener = getThreadBindingListener(); - - if (usePrivilegedAction) { - PrivilegedAction pa = new PrivilegedSetTccl(webApplicationClassLoader); - AccessController.doPrivileged(pa); - } else { - Thread.currentThread().setContextClassLoader(webApplicationClassLoader); - } - if (threadBindingListener != null) { - try { - threadBindingListener.bind(); - } catch (Throwable t) { - ExceptionUtils.handleThrowable(t); - log.error(sm.getString( - ""standardContext.threadBindingListenerError"", getName()), t); - } - } - - return originalClassLoader; - } - - - @Override -" -156,0," public void testInvalidData() throws IOException { - Map invalidData = new HashMap(); - invalidData.put(""foo"", ""bar""); - - NamedTemporaryFile tempFile = new NamedTemporaryFile(""invalid_parser_data"", null); - try (FileOutputStream fos = new FileOutputStream(tempFile.get().toString()); - ZipOutputStream zipos = new ZipOutputStream(fos)) { - zipos.putNextEntry(new ZipEntry(""parser_data"")); - try (ObjectOutputStream oos = new ObjectOutputStream(zipos)) { - oos.writeObject(invalidData); - } - } - - ProjectWorkspace workspace = - TestDataHelper.createProjectWorkspaceForScenario(this, ""parser_with_cell"", tmp); - workspace.setUp(); - - // Load the invalid parser cache data. - thrown.expect(InvalidClassException.class); - thrown.expectMessage(""Can't deserialize this class""); - workspace.runBuckCommand(""parser-cache"", ""--load"", tempFile.get().toString()); - } -" -157,0," public void addSecurityRole(String role) { - securityRoles.add(role); - } - - @Override -" -158,0," public boolean contains(Artifact artifact) { - // Note: getLocation(artifact) does an artifact.isResolved() check - no need to do it here. - File location = getLocation(artifact); - return location.canRead() && (location.isFile() || new File(location, ""META-INF"").isDirectory()); - } - -" -159,0," public static SVGAttr fromString(String str) - { - // First check cache to see if it is there - SVGAttr attr = cache.get(str); - if (attr != null) - return attr; - // Do the (slow) Enum.valueOf() - if (str.equals(""class"")) { - cache.put(str, CLASS); - return CLASS; - } - // Check for underscore in attribute - it could potentially confuse us - if (str.indexOf('_') != -1) { - cache.put(str, UNSUPPORTED); - return UNSUPPORTED; - } - try - { - attr = valueOf(str.replace('-', '_')); - if (attr != CLASS) { - cache.put(str, attr); - return attr; - } - } - catch (IllegalArgumentException e) - { - // Do nothing - } - // Unknown attribute name - cache.put(str, UNSUPPORTED); - return UNSUPPORTED; - } - - } - - - // Special attribute keywords -" -160,0," static public void configureLC(LoggerContext lc, String configFile) throws JoranException { - JoranConfigurator configurator = new JoranConfigurator(); - lc.reset(); - configurator.setContext(lc); - configurator.doConfigure(configFile); - } -" -161,0," public void connect(HttpConsumer consumer) throws Exception { - component.connect(consumer); - } - -" -162,0," public static int log2(int n) - { - int log = 0; - while ((n >>= 1) != 0) - { - log++; - } - return log; - } - - /** - * Convert int/long to n-byte array. - * - * @param value int/long value. - * @param sizeInByte Size of byte array in byte. - * @return int/long as big-endian byte array of size {@code sizeInByte}. - */ -" -163,0," public String getBindDN() - { - return bindDN.stringValue(); - } - - - - /** - * Retrieves the password for this simple bind request, if no password - * provider has been configured. - * - * @return The password for this simple bind request, or {@code null} if a - * password provider will be used to obtain the password. - */ -" -164,0," protected Log getLog() { - return log; - } - - @Override -" -165,0," public boolean isReadOnly() { - return false; - } -" -166,0," public void execute(FunctionContext context) { - RegionConfiguration configuration = (RegionConfiguration) context.getArguments(); - if (this.cache.getLogger().fineEnabled()) { - StringBuilder builder = new StringBuilder(); - builder.append(""Function "").append(ID).append("" received request: "").append(configuration); - this.cache.getLogger().fine(builder.toString()); - } - - // Create or retrieve region - RegionStatus status = createOrRetrieveRegion(configuration); - - // Dump XML - if (DUMP_SESSION_CACHE_XML) { - writeCacheXml(); - } - // Return status - context.getResultSender().lastResult(status); - } - - @Override -" -167,0," public void setSubjectName(String subjectName) { - this.subjectName = subjectName; - } - -" -168,0," public void testRejectBindWithDNButNoPasswordAsyncMode() - throws Exception - { - final InMemoryDirectoryServer ds = getTestDS(true, true); - - final LDAPConnectionOptions options = new LDAPConnectionOptions(); - options.setUseSynchronousMode(false); - - final LDAPConnection conn = ds.getConnection(options); - final SimpleBindRequest bindRequest = - new SimpleBindRequest(""cn=Directory Manager"", """"); - - try - { - bindRequest.process(conn, 1); - fail(""Expected an exception when binding with a DN but no password""); - } - catch (LDAPException le) - { - assertEquals(le.getResultCode(), ResultCode.PARAM_ERROR); - } - - - // Reconfigure the connection so that it will allow binds with a DN but no - // password. - conn.getConnectionOptions().setBindWithDNRequiresPassword(false); - try - { - bindRequest.process(conn, 1); - } - catch (LDAPException le) - { - // The server will still likely reject the operation, but we should at - // least verify that it wasn't a parameter error. - assertFalse(le.getResultCode() == ResultCode.PARAM_ERROR); - } - - conn.getConnectionOptions().setBindWithDNRequiresPassword(true); - conn.close(); - } -" -169,0," public Collection getRequiredPermissions(String regionName) { - return Collections.singletonList(ResourcePermissions.DATA_MANAGE); - } - -" -170,0," public void addRecipients(final ExtendedEmailPublisherContext context, final EnvVars env, - final Set to, final Set cc, final Set 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(); - - Set users = null; - - final Run currentRun = context.getRun(); - if (currentRun == null) { - debug.send(""currentRun was null""); - } else { - final AbstractTestResultAction testResultAction = currentRun.getAction(AbstractTestResultAction.class); - if (testResultAction == null) { - debug.send(""testResultAction was null""); - } else { - if (testResultAction.getFailCount() <= 0) { - debug.send(""getFailCount() returned <= 0""); - } else { - users = new HashSet<>(); - debug.send(""Collecting builds where a test started failing...""); - final HashSet> buildsWhereATestStartedFailing = new HashSet<>(); - for (final TestResult caseResult : testResultAction.getFailedTests()) { - final Run runWhereTestStartedFailing = caseResult.getFailedSinceRun(); - if (runWhereTestStartedFailing != null) { - debug.send("" runWhereTestStartedFailing: %d"", runWhereTestStartedFailing.getNumber()); - buildsWhereATestStartedFailing.add(runWhereTestStartedFailing); - } else { - context.getListener().error(""getFailedSinceRun returned null for %s"", caseResult.getFullDisplayName()); - } - } - // For each build where a test started failing, walk backward looking for build results worse than - // UNSTABLE. All of those builds will be used to find suspects. - debug.send(""Collecting builds with suspects...""); - final HashSet> buildsWithSuspects = new HashSet<>(); - for (final Run buildWhereATestStartedFailing : buildsWhereATestStartedFailing) { - debug.send("" buildWhereATestStartedFailing: %d"", buildWhereATestStartedFailing.getNumber()); - buildsWithSuspects.add(buildWhereATestStartedFailing); - Run previousBuildToCheck = buildWhereATestStartedFailing.getPreviousCompletedBuild(); - if (previousBuildToCheck != null) { - debug.send("" previousBuildToCheck: %d"", previousBuildToCheck.getNumber()); - } - while (previousBuildToCheck != null) { - if (buildsWithSuspects.contains(previousBuildToCheck)) { - // Short-circuit if the build to check has already been checked. - debug.send("" already contained in buildsWithSuspects; stopping search""); - break; - } - final Result previousResult = previousBuildToCheck.getResult(); - if (previousResult == null) { - debug.send("" previousResult was null""); - } else { - debug.send("" previousResult: %s"", previousResult.toString()); - if (previousResult.isBetterThan(Result.FAILURE)) { - debug.send("" previousResult was better than FAILURE; stopping search""); - break; - } else { - debug.send("" previousResult was not better than FAILURE; adding to buildsWithSuspects; continuing search""); - buildsWithSuspects.add(previousBuildToCheck); - previousBuildToCheck = previousBuildToCheck.getPreviousCompletedBuild(); - if (previousBuildToCheck != null) { - debug.send("" previousBuildToCheck: %d"", previousBuildToCheck.getNumber()); - } - } - } - } - } - debug.send(""Collecting suspects...""); - users.addAll(RecipientProviderUtilities.getChangeSetAuthors(buildsWithSuspects, debug)); - users.addAll(RecipientProviderUtilities.getUsersTriggeringTheBuilds(buildsWithSuspects, debug)); - } - } - } - - if (users != null) { - RecipientProviderUtilities.addUsers(users, context, env, to, cc, bcc, debug); - } - } - - @Extension -" -171,0," public void doStart() throws Exception { - URI rootURI; - if (serverInfo != null) { - rootURI = serverInfo.resolveServer(configuredDir); - } else { - rootURI = configuredDir; - } - if (!rootURI.getScheme().equals(""file"")) { - throw new IllegalStateException(""FileKeystoreManager must have a root that's a local directory (not "" + rootURI + "")""); - } - directory = new File(rootURI); - if (!directory.exists() || !directory.isDirectory() || !directory.canRead()) { - throw new IllegalStateException(""FileKeystoreManager must have a root that's a valid readable directory (not "" + directory.getAbsolutePath() + "")""); - } - log.debug(""Keystore directory is "" + directory.getAbsolutePath()); - } - -" -172,0," public void setLimit(int limit) { - if (buffered == null) { - buffered = new ByteChunk(4048); - buffered.setLimit(limit); - } - } - - - // ---------------------------------------------------- InputBuffer Methods - - - /** - * Reads the request body and buffers it. - */ -" -173,0," public LockoutPolicy getLockoutPolicy() { - if(isEnabled) { - LockoutPolicy res = IdentityZoneHolder.get().getConfig().getClientLockoutPolicy(); - return res.getLockoutAfterFailures() != -1 ? res : defaultLockoutPolicy; - } else { - return disabledLockoutPolicy; - } - } - - @Override -" -174,0," private static void post(JenkinsRule.WebClient webClient, String relative, - String expectedContentType, Integer expectedStatus) throws IOException { - WebRequest request = new WebRequest( - UrlUtils.toUrlUnsafe(webClient.getContextPath() + relative), - HttpMethod.POST); - try { - Page p = webClient.getPage(request); - if (expectedContentType != null) { - assertThat(p.getWebResponse().getContentType(), is(expectedContentType)); - } - } catch (FailingHttpStatusCodeException e) { - if (expectedStatus != null) { - assertEquals(expectedStatus.intValue(), e.getStatusCode()); - } else { - throw e; - } - } - } -" -175,0," private void detectJPA() { - // check whether we have Persistence on the classpath - Class persistenceClass; - try { - persistenceClass = run( LoadClass.action( PERSISTENCE_CLASS_NAME, this.getClass() ) ); - } - catch ( ValidationException e ) { - log.debugf( - ""Cannot find %s on classpath. Assuming non JPA 2 environment. All properties will per default be traversable."", - PERSISTENCE_CLASS_NAME - ); - return; - } - - // check whether Persistence contains getPersistenceUtil - Method persistenceUtilGetter = run( GetMethod.action( persistenceClass, PERSISTENCE_UTIL_METHOD ) ); - if ( persistenceUtilGetter == null ) { - log.debugf( - ""Found %s on classpath, but no method '%s'. Assuming JPA 1 environment. All properties will per default be traversable."", - PERSISTENCE_CLASS_NAME, - PERSISTENCE_UTIL_METHOD - ); - return; - } - - // try to invoke the method to make sure that we are dealing with a complete JPA2 implementation - // unfortunately there are several incomplete implementations out there (see HV-374) - try { - Object persistence = run( NewInstance.action( persistenceClass, ""persistence provider"" ) ); - ReflectionHelper.getValue( persistenceUtilGetter, persistence ); - } - catch ( Exception e ) { - log.debugf( - ""Unable to invoke %s.%s. Inconsistent JPA environment. All properties will per default be traversable."", - PERSISTENCE_CLASS_NAME, - PERSISTENCE_UTIL_METHOD - ); - } - - log.debugf( - ""Found %s on classpath containing '%s'. Assuming JPA 2 environment. Trying to instantiate JPA aware TraversableResolver"", - PERSISTENCE_CLASS_NAME, - PERSISTENCE_UTIL_METHOD - ); - - try { - @SuppressWarnings(""unchecked"") - Class jpaAwareResolverClass = (Class) - run( LoadClass.action( JPA_AWARE_TRAVERSABLE_RESOLVER_CLASS_NAME, this.getClass() ) ); - jpaTraversableResolver = run( NewInstance.action( jpaAwareResolverClass, """" ) ); - log.debugf( - ""Instantiated JPA aware TraversableResolver of type %s."", JPA_AWARE_TRAVERSABLE_RESOLVER_CLASS_NAME - ); - } - catch ( ValidationException e ) { - log.debugf( - ""Unable to load or instantiate JPA aware resolver %s. All properties will per default be traversable."", - JPA_AWARE_TRAVERSABLE_RESOLVER_CLASS_NAME - ); - } - } - - @Override -" -176,0," public String getName() { - return name; - } - -" -177,0," public static Transformer cloneTransformer() { - return INSTANCE; - } - - /** - * Constructor. - */ -" -178,0," public static ASN1Enumerated getInstance( - ASN1TaggedObject obj, - boolean explicit) - { - ASN1Primitive o = obj.getObject(); - - if (explicit || o instanceof ASN1Enumerated) - { - return getInstance(o); - } - else - { - return fromOctetString(((ASN1OctetString)o).getOctets()); - } - } - - /** - * Constructor from int. - * - * @param value the value of this enumerated. - */ -" -179,0," public void servletSecurityAnnotationScan() throws ServletException; -" -180,0," protected AbstractOutputBuffer getOutputBuffer() { - return outputBuffer; - } -" -181,0," public void addRecipients(final ExtendedEmailPublisherContext context, EnvVars env, Set to, Set cc, Set 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(); - Run run = context.getRun(); - final Result runResult = run.getResult(); - if (run instanceof AbstractBuild) { - Set users = ((AbstractBuild)run).getCulprits(); - RecipientProviderUtilities.addUsers(users, context, env, to, cc, bcc, debug); - } else if (runResult != null) { - List> builds = new ArrayList<>(); - Run build = run; - builds.add(build); - build = build.getPreviousCompletedBuild(); - while (build != null) { - final Result buildResult = build.getResult(); - if (buildResult != null) { - if (buildResult.isWorseThan(Result.SUCCESS)) { - debug.send(""Including build %s with status %s"", build.getId(), buildResult); - builds.add(build); - } else { - break; - } - } - build = build.getPreviousCompletedBuild(); - } - Set users = RecipientProviderUtilities.getChangeSetAuthors(builds, debug); - RecipientProviderUtilities.addUsers(users, context, env, to, cc, bcc, debug); - } - } - - @Extension -" -182,0," public void process(Exchange exchange) throws Exception { -" -183,0," public void testLauncherServerReuse() throws Exception { - ChildProcAppHandle handle1 = null; - ChildProcAppHandle handle2 = null; - ChildProcAppHandle handle3 = null; - - try { - handle1 = LauncherServer.newAppHandle(); - handle2 = LauncherServer.newAppHandle(); - LauncherServer server1 = handle1.getServer(); - assertSame(server1, handle2.getServer()); - - handle1.kill(); - handle2.kill(); - - handle3 = LauncherServer.newAppHandle(); - assertNotSame(server1, handle3.getServer()); - - handle3.kill(); - - assertNull(LauncherServer.getServerInstance()); - } finally { - kill(handle1); - kill(handle2); - kill(handle3); - } - } - - @Test -" -184,0," void set(String format, Hash hash) throws ANTLRException { - set(format,1,hash); - } - - /** - * Returns true if n-th bit is on. - */ -" -185,0," private static int getNumberOfIterations(int bits, int certainty) - { - /* - * NOTE: We enforce a minimum 'certainty' of 100 for bits >= 1024 (else 80). Where the - * certainty is higher than the FIPS 186-4 tables (C.2/C.3) cater to, extra iterations - * are added at the ""worst case rate"" for the excess. - */ - if (bits >= 1536) - { - return certainty <= 100 ? 3 - : certainty <= 128 ? 4 - : 4 + (certainty - 128 + 1) / 2; - } - else if (bits >= 1024) - { - return certainty <= 100 ? 4 - : certainty <= 112 ? 5 - : 5 + (certainty - 112 + 1) / 2; - } - else if (bits >= 512) - { - return certainty <= 80 ? 5 - : certainty <= 100 ? 7 - : 7 + (certainty - 100 + 1) / 2; - } - else - { - return certainty <= 80 ? 40 - : 40 + (certainty - 80 + 1) / 2; - } - } -" -186,0," public void setMaxSize(String maxSize) { - this.maxSize = Long.parseLong(maxSize); - } - - @Inject -" -187,0," public T postProcess(T object) { - throw new IllegalStateException( - ObjectPostProcessor.class.getName() - + "" is a required bean. Ensure you have used @EnableWebSecurity and @Configuration""); - } - }; - -" -188,0," public String path() { - return ""path""; - } - } - } - - public void loadConfig(Class... configs) { - this.context = new AnnotationConfigWebApplicationContext(); - this.context.register(configs); - this.context.setServletContext(new MockServletContext()); - this.context.refresh(); - - this.context.getAutowireCapableBeanFactory().autowireBean(this); - } -}" -189,0," public boolean timedOut() { - return timedOut; - } - } -} -" -190,0," public void destroy() { - // NOOP - } - - - /** - * Initialize this servlet. - */ - @Override -" -191,0," public void testBadColorSpace() { - TesseractOCRConfig config = new TesseractOCRConfig(); - config.setColorspace(""someth!ng""); - } -" -192,0," private File getFileParameterFolderUnderBuild(AbstractBuild build){ - return new File(build.getRootDir(), FOLDER_NAME); - } - - /** - * Default implementation from {@link File}. - */ -" -193,0," public void nextBytes(byte[] bytes) - { - if (first) - { - super.nextBytes(bytes); - first = false; - } - else - { - bytes[bytes.length - 1] = 2; - } - } - } -} -" -194,0," protected Timestamp getPasswordLastModifiedTimestamp(Timestamp t) { - Calendar cal = new GregorianCalendar(); - cal.set(Calendar.MILLISECOND, 0); - return new Timestamp(cal.getTimeInMillis()); - } - - @Override -" -195,0," public static Factory instantiateFactory(final Class classToInstantiate, - final Class[] paramTypes, - final Object[] args) { - if (classToInstantiate == null) { - throw new NullPointerException(""Class to instantiate must not be null""); - } - if (paramTypes == null && args != null - || paramTypes != null && args == null - || paramTypes != null && args != null && paramTypes.length != args.length) { - throw new IllegalArgumentException(""Parameter types must match the arguments""); - } - - if (paramTypes == null || paramTypes.length == 0) { - return new InstantiateFactory(classToInstantiate); - } - return new InstantiateFactory(classToInstantiate, paramTypes, args); - } - - /** - * Constructor that performs no validation. - * Use instantiateFactory if you want that. - * - * @param classToInstantiate the class to instantiate - */ -" -196,0," public Object evaluate(MessageEvaluationContext message) throws JMSException { - try { - if (message.isDropped()) { - return null; - } - return evaluator.evaluate(message.getMessage()) ? Boolean.TRUE : Boolean.FALSE; - } catch (IOException e) { - throw JMSExceptionSupport.create(e); - } - - } - -" -197,0," private boolean shutdownDB(String dbName) { - boolean ok = true; - - boolean gotSQLExc = false; - try { - DerbyConnectionUtil.getDerbyConnection(dbName, - DerbyConnectionUtil.SHUTDOWN_DB_PROP); - } catch (SQLException se) { - gotSQLExc = true; - } - - if (!gotSQLExc) { - ok = false; - } - - return ok; - } - -" -198,0," public DeserializerFactory withConfig(DeserializerFactoryConfig config) - { - if (_factoryConfig == config) { - return this; - } - /* 22-Nov-2010, tatu: Handling of subtypes is tricky if we do immutable-with-copy-ctor; - * and we pretty much have to here either choose between losing subtype instance - * when registering additional deserializers, or losing deserializers. - * Instead, let's actually just throw an error if this method is called when subtype - * has not properly overridden this method; this to indicate problem as soon as possible. - */ - if (getClass() != BeanDeserializerFactory.class) { - throw new IllegalStateException(""Subtype of BeanDeserializerFactory (""+getClass().getName() - +"") has not properly overridden method 'withAdditionalDeserializers': can not instantiate subtype with "" - +""additional deserializer definitions""); - } - return new BeanDeserializerFactory(config); - } - - /* - /********************************************************** - /* DeserializerFactory API implementation - /********************************************************** - */ - - /** - * Method that {@link DeserializerCache}s call to create a new - * deserializer for types other than Collections, Maps, arrays and - * enums. - */ - @Override -" -199,0," public void setTransferException(boolean transferException) { - this.transferException = transferException; - } -" -200,0," InstanceManager getInstanceManager() { - return instanceManager; - } - -" -201,0," public void testSingletonPatternInSerialization() { - final Object[] singletones = new Object[] { - ExceptionTransformer.INSTANCE, - NOPTransformer.INSTANCE, - StringValueTransformer.stringValueTransformer(), - }; - - for (final Object original : singletones) { - TestUtils.assertSameAfterSerialization(""Singleton pattern broken for "" + original.getClass(), original); - } - } - -" -202,0," public String getCipherSuite() throws IOException { - // Look up the current SSLSession - SSLSession session = ssl.getSession(); - if (session == null) - return null; - return session.getCipherSuite(); - } - -" -203,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""); - stopThread(server_id, actionRequest); - actionResponse.setRenderParameter(""server_id"", server_id); - } else if (action.equals(""startThread"") - || action.equals(""enableServerViewQuery"")) { - String server_id = actionRequest.getParameter(""server_id""); - String snapshotDuration = actionRequest.getParameter(""snapshotDuration""); - startThread(server_id, new Long(snapshotDuration), actionRequest); - 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); - alterServerState(server_id, false, actionRequest); - } else if (action.equals(""enableServer"") - || action.equals(""enableEditServer"")) { - String server_id = actionRequest.getParameter(""server_id""); - alterServerState(server_id, true, actionRequest); - 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"")); - String protocol = actionRequest.getParameter(""protocol""); - testConnection(ip, username, password, port, protocol, actionRequest); - 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"")); - String protocol = actionRequest.getParameter(""protocol""); - if (snapshot == null) { - snapshot = """"; - } - if (retention == null) { - retention = """"; - } - testConnection(ip, username, password, port, protocol, actionRequest); - 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); - } - } - -" -204,0," public void resetPassword_InvalidCodeData() { - ExpiringCode expiringCode = new ExpiringCode(""good_code"", - new Timestamp(System.currentTimeMillis() + UaaResetPasswordService.PASSWORD_RESET_LIFETIME), ""user-id"", null); - when(codeStore.retrieveCode(""good_code"")).thenReturn(expiringCode); - SecurityContext securityContext = mock(SecurityContext.class); - when(securityContext.getAuthentication()).thenReturn(new MockAuthentication()); - SecurityContextHolder.setContext(securityContext); - try { - emailResetPasswordService.resetPassword(""good_code"", ""password""); - fail(); - } catch (InvalidCodeException e) { - assertEquals(""Sorry, your reset password link is no longer valid. Please request a new one"", e.getMessage()); - } - } - - @Test -" -205,0," private void wipeRepositoryDirectories() { - if (repoPath.exists()) { - assertThat(repoPath.getAbsolutePath(), containsString(clusterName)); - if (FileSystemUtils.deleteRecursively(repoPath)) { - logger.info(""Successfully wiped repository directory for node location: {}"", repoPath); - } else { - logger.info(""Failed to wipe data directory for node location: {}"", repoPath); - } - } - } - -" -206,0," public void init(FilterConfig conf) throws ServletException { - if (conf != null && ""zookeeper"".equals(conf.getInitParameter(""signer.secret.provider""))) { - SolrZkClient zkClient = - (SolrZkClient)conf.getServletContext().getAttribute(DELEGATION_TOKEN_ZK_CLIENT); - try { - conf.getServletContext().setAttribute(""signer.secret.provider.zookeeper.curator.client"", - getCuratorClient(zkClient)); - } catch (KeeperException | InterruptedException e) { - throw new ServletException(e); - } - } - super.init(conf); - } - - @Override -" -207,0," public boolean getMapperDirectoryRedirectEnabled() { return false; } -" -208,0," public static boolean isNewAuthenticationPathNeeded(long globalIndex, int xmssHeight, int layer) - { - if (globalIndex == 0) - { - return false; - } - return ((globalIndex + 1) % (long)Math.pow((1 << xmssHeight), layer) == 0) ? true : false; - } -" -209,0," public final Set> getGroupList() { - return constraintDescriptor.getGroups(); - } - -" -210,0," public void destroy() { - } - -" -211,0," protected Log getLog() { - return log; - } - - - /** - * SSL information. - */ -" -212,0," protected Processor createUpgradeProcessor( - SocketWrapper socket, - HttpUpgradeHandler httpUpgradeProcessor) - throws IOException { - return new AprProcessor(socket, httpUpgradeProcessor, - (AprEndpoint) proto.endpoint); - } - } -} -" -213,0," private Object readResolve() { - Jenkins.getInstance().checkPermission(Jenkins.RUN_SCRIPTS); - return this; - } - -" -214,0," public String getDisplayName() { - return ""Requestor""; - } - - } -} -" -215,0," public OutputStream createOutput(String blobName) throws IOException { - maybeIOExceptionOrBlock(blobName); - return super.createOutput(blobName); - } - } - } -} -" -216,0," public void run() { - } - }; - - /** - * Creates a new instance - * @param objectPostProcessor the {@link ObjectPostProcessor} to use - * @see WebSecurityConfiguration - */ -" -217,0," void toHtml() throws IOException { - writeBackAndRefreshLinks(); - writeln(""
""); - - assert sessionsInformations != null; - if (sessionsInformations.isEmpty()) { - writeln(""#Aucune_session#""); - return; - } - writeTitle(""system-users.png"", getString(""Sessions"")); - writeSessions(sessionsInformations); - long totalSerializedSize = 0; - int nbSerializableSessions = 0; - for (final SessionInformations sessionInformations : sessionsInformations) { - final int size = sessionInformations.getSerializedSize(); - if (size >= 0) { - totalSerializedSize += size; - nbSerializableSessions++; - } - } - final long meanSerializedSize; - if (nbSerializableSessions > 0) { - meanSerializedSize = totalSerializedSize / nbSerializableSessions; - } else { - meanSerializedSize = -1; - } - writeln(""
"" - + getFormattedString(""nb_sessions"", sessionsInformations.size()) + ""

"" - + getFormattedString(""taille_moyenne_sessions"", meanSerializedSize) + ""
""); - } - -" -218,0," public boolean allowsSignup() { - return !disableSignup; - } - - /** - * Checks if captcha is enabled on user signup. - * - * @return true if captcha is enabled on signup. - */ -" -219,0," public static String stripExpressionIfAltSyntax(ValueStack stack, String expr) { - if (altSyntax(stack)) { - // does the expression start with %{ and end with }? if so, just cut it off! - if (isExpression(expr)) { - return expr.substring(2, expr.length() - 1); - } - } - return expr; - } - - /** - * Is the altSyntax enabled? [TRUE] - * - * @param stack the ValueStack where the context value is searched for. - * @return true if altSyntax is activated. False otherwise. - * See struts.properties where the altSyntax flag is defined. - */ -" -220,0," private void processServletSecurityAnnotation(Servlet servlet) { - // Calling this twice isn't harmful so no syncs - servletSecurityAnnotationScanRequired = false; - - ServletSecurity secAnnotation = - servlet.getClass().getAnnotation(ServletSecurity.class); - Context ctxt = (Context) getParent(); - if (secAnnotation != null) { - ctxt.addServletSecurity( - new ApplicationServletRegistration(this, ctxt), - new ServletSecurityElement(secAnnotation)); - } - } - -" -221,0," public long getBytesWritten() { - return bytesWritten; - } - } -} -" -222,0," private void doRedirectTest(String path, int expected) throws IOException { - ByteChunk bc = new ByteChunk(); - int rc = getUrl(""http://localhost:"" + getPort() + path, bc, null); - Assert.assertEquals(expected, rc); - } - - - /** - * Prepare a string to search in messages that contain a timestamp, when it - * is known that the timestamp was printed between {@code timeA} and - * {@code timeB}. - */ -" -223,0," public void testEntityExpansionWReq2() throws Exception { - String url = ""https://localhost:"" + getIdpHttpsPort() + ""/fediz-idp/federation?""; - url += ""wa=wsignin1.0""; - url += ""&whr=urn:org:apache:cxf:fediz:idp:realm-A""; - url += ""&wtrealm=urn:org:apache:cxf:fediz:fedizhelloworld""; - String wreply = ""https://localhost:"" + getRpHttpsPort() + ""/"" + getServletContextName() + ""/secure/fedservlet""; - url += ""&wreply="" + wreply; - - InputStream is = this.getClass().getClassLoader().getResource(""entity_wreq2.xml"").openStream(); - String entity = IOUtils.toString(is, ""UTF-8""); - is.close(); - String validWreq = - """" - + ""&m;http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV2.0"" - + """"; - - url += ""&wreq="" + URLEncoder.encode(entity + validWreq, ""UTF-8""); - - String user = ""alice""; - String password = ""ecila""; - - final WebClient webClient = new WebClient(); - webClient.getOptions().setUseInsecureSSL(true); - webClient.getCredentialsProvider().setCredentials( - new AuthScope(""localhost"", Integer.parseInt(getIdpHttpsPort())), - new UsernamePasswordCredentials(user, password)); - - webClient.getOptions().setJavaScriptEnabled(false); - - try { - webClient.getPage(url); - Assert.fail(""Failure expected on a bad wreq value""); - } catch (FailingHttpStatusCodeException ex) { - Assert.assertEquals(ex.getStatusCode(), 400); - } - - webClient.close(); - } - - // Send an malformed wreq value - @org.junit.Test -" -224,0," Class convertGroup(Class originalGroup); - - /** - * Returns a set with {@link GroupConversionDescriptor}s representing the - * group conversions of this cascadable. - * - * @return A set with group conversion descriptors. May be empty, but never - * {@code null}. - */ -" -225,0," public static File checkSlip(File parentFile, File file) throws IllegalArgumentException { - String parentCanonicalPath; - String canonicalPath; - try { - parentCanonicalPath = parentFile.getCanonicalPath(); - canonicalPath = file.getCanonicalPath(); - } catch (IOException e) { - throw new IORuntimeException(e); - } - if (false == canonicalPath.startsWith(parentCanonicalPath)) { - throw new IllegalArgumentException(""New file is outside of the parent dir: "" + file.getName()); - } - return file; - } -" -226,0," public ExitCode runWithoutHelp(CommandRunnerParams params) - throws IOException, InterruptedException { - - if (saveFilename != null && loadFilename != null) { - params.getConsole().printErrorText(""Can't use both --load and --save""); - return ExitCode.COMMANDLINE_ERROR; - } - - if (saveFilename != null) { - invalidateChanges(params); - RemoteDaemonicParserState state = params.getParser().storeParserState(params.getCell()); - try (FileOutputStream fos = new FileOutputStream(saveFilename); - ZipOutputStream zipos = new ZipOutputStream(fos)) { - zipos.putNextEntry(new ZipEntry(""parser_data"")); - try (ObjectOutputStream oos = new ObjectOutputStream(zipos)) { - oos.writeObject(state); - } - } - } else if (loadFilename != null) { - try (FileInputStream fis = new FileInputStream(loadFilename); - ZipInputStream zipis = new ZipInputStream(fis)) { - ZipEntry entry = zipis.getNextEntry(); - Preconditions.checkState(entry.getName().equals(""parser_data"")); - try (ObjectInputStream ois = new ParserStateObjectInputStream(zipis)) { - RemoteDaemonicParserState state; - try { - state = (RemoteDaemonicParserState) ois.readObject(); - } catch (ClassNotFoundException e) { - params.getConsole().printErrorText(""Invalid file format""); - return ExitCode.COMMANDLINE_ERROR; - } - params.getParser().restoreParserState(state, params.getCell()); - } - } - invalidateChanges(params); - - ParserConfig configView = params.getBuckConfig().getView(ParserConfig.class); - if (configView.isParserCacheMutationWarningEnabled()) { - params - .getConsole() - .printErrorText( - params - .getConsole() - .getAnsi() - .asWarningText( - ""WARNING: Buck injected a parser state that may not match the local state."")); - } - } - - return ExitCode.SUCCESS; - } - -" -227,0," private boolean isPropertyConfigured(TrustedIdp trustedIdp, String property, boolean defaultValue) { - Map parameters = trustedIdp.getParameters(); - - if (parameters != null && parameters.containsKey(property)) { - return Boolean.parseBoolean(parameters.get(property)); - } - - return defaultValue; - } - -" -228,0," public void testHandleNeverSendAResponse() throws Exception - { - final AuthenticationResult firstResult = _negotiator.handleResponse(new byte[0]); - assertEquals(""Unexpected authentication status"", AuthenticationResult.AuthenticationStatus.CONTINUE, firstResult.getStatus()); - assertArrayEquals(""Unexpected authentication challenge"", new byte[0], firstResult.getChallenge()); - - final AuthenticationResult secondResult = _negotiator.handleResponse(new byte[0]); - assertEquals(""Unexpected first authentication result"", AuthenticationResult.AuthenticationStatus.ERROR, secondResult.getStatus()); - } - -" -229,0," public Collection parse(final InputStream file, final String moduleName) - throws InvocationTargetException { - try { - SecureDigester digester = new SecureDigester(LintParser.class); - - List issues = new ArrayList(); - digester.push(issues); - - String issueXPath = ""issues/issue""; - digester.addObjectCreate(issueXPath, LintIssue.class); - digester.addSetProperties(issueXPath); - digester.addSetNext(issueXPath, ""add""); - - String locationXPath = issueXPath + ""/location""; - digester.addObjectCreate(locationXPath, Location.class); - digester.addSetProperties(locationXPath); - digester.addSetNext(locationXPath, ""addLocation"", Location.class.getName()); - - digester.parse(file); - - return convert(issues, moduleName); - } catch (IOException | SAXException exception) { - throw new InvocationTargetException(exception); - } - } - - /** - * Converts the Lint object structure to that of the analysis-core API. - * - * @param issues The parsed Lint issues. - * @param moduleName Name of the maven module, if any. - * @return A collection of the discovered issues. - */ -" -230,0," private static void zip(File file, String srcRootDir, ZipOutputStream out) throws UtilException { - if (file == null) { - return; - } - - final String subPath = FileUtil.subPath(srcRootDir, file); // 获取文件相对于压缩文件夹根目录的子路径 - if (file.isDirectory()) {// 如果是目录,则压缩压缩目录中的文件或子目录 - final File[] files = file.listFiles(); - if (ArrayUtil.isEmpty(files) && StrUtil.isNotEmpty(subPath)) { - // 加入目录,只有空目录时才加入目录,非空时会在创建文件时自动添加父级目录 - addDir(subPath, out); - } - // 压缩目录下的子文件或目录 - for (File childFile : files) { - zip(childFile, srcRootDir, out); - } - } else {// 如果是文件或其它符号,则直接压缩该文件 - addFile(file, subPath, out); - } - } - - /** - * 添加文件到压缩包 - * - * @param file 需要压缩的文件 - * @param path 在压缩文件中的路径 - * @param out 压缩文件存储对象 - * @throws UtilException IO异常 - * @since 4.0.5 - */ -" -231,0," public void initResetPasswordTest() throws Exception { - codeStore = getWebApplicationContext().getBean(ExpiringCodeStore.class); - } - - @Test -" -232,0," public final Set> validate(T object, Class... groups) { - Contracts.assertNotNull( object, MESSAGES.validatedObjectMustNotBeNull() ); - - if ( !beanMetaDataManager.isConstrained( object.getClass() ) ) { - return Collections.emptySet(); - } - - ValidationOrder validationOrder = determineGroupValidationOrder( groups ); - ValidationContext validationContext = getValidationContext().forValidate( object ); - - ValueContext valueContext = ValueContext.getLocalExecutionContext( - object, - beanMetaDataManager.getBeanMetaData( object.getClass() ), - PathImpl.createRootPath() - ); - - return validateInContext( valueContext, validationContext, validationOrder ); - } - - @Override -" -233,0," public String getAlgorithm() - { - return ""XMSS""; - } - -" -234,0," public ProcessGroup getParent() { - return parent.get(); - } - -" -235,0," private void checkAdmin() { - final Jenkins jenkins = Jenkins.getInstance(); //Hoping this method doesn't change meaning again - if (jenkins != null) { - //If Jenkins is not alive then we are not started, so no unauthorised user might do anything - jenkins.checkPermission(Jenkins.ADMINISTER); - } - } - - - /** - * Check whether the list of servers contains a GerritServer object of a specific name. - * - * @param serverName to check. - * @return whether the list contains a server with the given name. - */ -" -236,0," public int available() throws IOException { - if (max >= 0 && pos >= max) { - return 0; - } - return in.available(); - } - } -} -" -237,0," public static void addNamespacePrefix(Element element, String namespaceUri, String prefix) { - element.setAttributeNS(XMLConstants.XMLNS_ATTRIBUTE_NS_URI, ""xmlns:"" + prefix, namespaceUri); - } -" -238,0," public boolean contains(Artifact artifact) { - // Note: getLocation(artifact) does an artifact.isResolved() check - no need to do it here. - File location = getLocation(artifact); - return location.canRead() && (location.isFile() || new File(location, ""META-INF"").isDirectory()); - } - -" -239,0," public String getTestString() { - return testString; - } - - @Override -" -240,0," public void removeUser(String username) { - - UserDatabase database = (UserDatabase) this.resource; - User user = database.findUser(username); - if (user == null) { - return; - } - try { - MBeanUtils.destroyMBean(user); - database.removeUser(user); - } catch (Exception e) { - IllegalArgumentException iae = new IllegalArgumentException - (""Exception destroying user ["" + username + ""] MBean""); - iae.initCause(e); - throw iae; - } - - } - - -" -241,0," public T transform(final T input) { - if (input == null) { - return null; - } - return PrototypeFactory.prototypeFactory(input).create(); - } - -" -242,0," public void execute(FunctionContext context) { - Object[] arguments = (Object[]) context.getArguments(); - String regionName = (String) arguments[0]; - Set keys = (Set) arguments[1]; - if (this.cache.getLogger().fineEnabled()) { - StringBuilder builder = new StringBuilder(); - builder.append(""Function "").append(ID).append("" received request to touch "") - .append(regionName).append(""->"").append(keys); - this.cache.getLogger().fine(builder.toString()); - } - - // Retrieve the appropriate Region and value to update the lastAccessedTime - Region region = this.cache.getRegion(regionName); - if (region != null) { - region.getAll(keys); - } - - // Return result to get around NPE in LocalResultCollectorImpl - context.getResultSender().lastResult(true); - } - - @Override -" -243,0," protected void engineInitVerify( - PublicKey publicKey) - throws InvalidKeyException - { - CipherParameters param = DSAUtil.generatePublicKeyParameter(publicKey); - - digest.reset(); - signer.init(false, param); - } - -" -244,0," public void testSave() throws IOException, InterruptedException, ReactorException { - FreeStyleProject p = j.createFreeStyleProject(""project""); - p.disabled = true; - p.nextBuildNumber = 5; - p.description = ""description""; - p.save(); - j.jenkins.reload(); - assertEquals(""All persistent data should be saved."", ""description"", p.description); - assertEquals(""All persistent data should be saved."", 5, p.nextBuildNumber); - assertEquals(""All persistent data should be saved"", true, p.disabled); - } - - @Test -" -245,0," private static void deflater(InputStream in, OutputStream out, int level) { - final DeflaterOutputStream ios = (out instanceof DeflaterOutputStream) ? (DeflaterOutputStream) out : new DeflaterOutputStream(out, new Deflater(level, true)); - IoUtil.copy(in, ios); - } - // ---------------------------------------------------------------------------------------------- Private method end - -" -246,0," protected CoderResult decodeLoop(ByteBuffer in, CharBuffer out) { - if (in.hasArray() && out.hasArray()) { - return decodeHasArray(in, out); - } - return decodeNotHasArray(in, out); - } - - -" -247,0," public static Transformer invokerTransformer(final String methodName, final Class[] paramTypes, - final Object[] args) { - if (methodName == null) { - throw new NullPointerException(""The method to invoke must not be null""); - } - if (((paramTypes == null) && (args != null)) - || ((paramTypes != null) && (args == null)) - || ((paramTypes != null) && (args != null) && (paramTypes.length != args.length))) { - throw new IllegalArgumentException(""The parameter types must match the arguments""); - } - if (paramTypes == null || paramTypes.length == 0) { - return new InvokerTransformer(methodName); - } - return new InvokerTransformer(methodName, paramTypes, args); - } - - /** - * Constructor for no arg instance. - * - * @param methodName the method to call - */ -" -248,0," private void checkError() throws IOException { - if (error) { - throw new IOException(sm.getString(""chunkedInputFilter.error"")); - } - } -" -249,0," public final BootstrapConfiguration parseValidationXml() { - InputStream inputStream = getInputStream(); - if ( inputStream == null ) { - return BootstrapConfigurationImpl.getDefaultBootstrapConfiguration(); - } - - try { - String schemaVersion = xmlParserHelper.getSchemaVersion( VALIDATION_XML_FILE, inputStream ); - Schema schema = getSchema( schemaVersion ); - ValidationConfigType validationConfig = unmarshal( inputStream, schema ); - - return createBootstrapConfiguration( validationConfig ); - } - finally { - closeStream( inputStream ); - } - } - -" -250,0," public ExpressionInterceptUrlRegistry getRegistry() { - return REGISTRY; - } - -" -251,0," public Settings settings() { - return this.settings; - } - - /** - * The home of the installation. - */ -" -252,0," public void testPrivateKeyParsingSHA256() - throws Exception - { - XMSSMTParameters params = new XMSSMTParameters(20, 10, new SHA256Digest()); - XMSSMT mt = new XMSSMT(params, new SecureRandom()); - mt.generateKeys(); - byte[] privateKey = mt.exportPrivateKey(); - byte[] publicKey = mt.exportPublicKey(); - - mt.importState(privateKey, publicKey); - - assertTrue(Arrays.areEqual(privateKey, mt.exportPrivateKey())); - } -" -253,0," public void destroy() { - - if (log.isDebugEnabled()) { - log.debug(internal.getMessage(""finalizing"")); - } - - destroyModules(); - destroyInternal(); - getServletContext().removeAttribute(Globals.ACTION_SERVLET_KEY); - - // Release our LogFactory and Log instances (if any) - ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); - if (classLoader == null) { - classLoader = ActionServlet.class.getClassLoader(); - } - try { - LogFactory.release(classLoader); - } catch (Throwable t) { - ; // Servlet container doesn't have the latest version - ; // of commons-logging-api.jar installed - - // :FIXME: Why is this dependent on the container's version of commons-logging? - // Shouldn't this depend on the version packaged with Struts? - /* - Reason: LogFactory.release(classLoader); was added as - an attempt to investigate the OutOfMemory error reported on Bugzilla #14042. - It was committed for version 1.136 by craigmcc - */ - } - - PropertyUtils.clearDescriptors(); - - } - - - /** - *

Initialize this servlet. Most of the processing has been factored into - * support methods so that you can override particular functionality at a - * fairly granular level.

- * - * @exception ServletException if we cannot configure ourselves correctly - */ -" -254,0," private void loadOtherTesseractConfig(Properties properties) { - for (String k : properties.stringPropertyNames()) { - if (k.contains(""_"")) { - addOtherTesseractConfig(k, properties.getProperty(k)); - } - } - } -" -255,0," public static Transformer, T> instantiateTransformer(final Class[] paramTypes, - final Object[] args) { - if (((paramTypes == null) && (args != null)) - || ((paramTypes != null) && (args == null)) - || ((paramTypes != null) && (args != null) && (paramTypes.length != args.length))) { - throw new IllegalArgumentException(""Parameter types must match the arguments""); - } - - if (paramTypes == null || paramTypes.length == 0) { - return new InstantiateTransformer(); - } - return new InstantiateTransformer(paramTypes, args); - } - - /** - * Constructor for no arg instance. - */ -" -256,0," String hash(String plaintext, String salt, int iterations) throws EncryptionException; - - /** - * Encrypts the provided plaintext bytes using the cipher transformation - * specified by the property Encryptor.CipherTransformation - * and the master encryption key as specified by the property - * {@code Encryptor.MasterKey} as defined in the ESAPI.properties file. - *

- * - * @param plaintext The {@code PlainText} to be encrypted. - * @return the {@code CipherText} object from which the raw ciphertext, the - * IV, the cipher transformation, and many other aspects about - * the encryption detail may be extracted. - * @throws EncryptionException Thrown if something should go wrong such as - * the JCE provider cannot be found, the cipher algorithm, - * cipher mode, or padding scheme not being supported, specifying - * an unsupported key size, specifying an IV of incorrect length, - * etc. - * @see #encrypt(SecretKey, PlainText) - * @since 2.0 - */ -" -257,0," public HandshakeResponse getHandshakeResponse() { - return handshakeResponse; - } - } -} -" -258,0," public void handleDialog(ActionRequest req, ActionResponse resp) throws IOException, PortletException { - List lines = new ArrayList(); - req.getPortletSession().setAttribute(""lines"", lines); - - lines.add(""handling dialog""); - StringBuilder txt = new StringBuilder(128); - - String clr = req.getActionParameters().getValue(""color""); - txt.append(""Color: "").append(clr); - lines.add(txt.toString()); - LOGGER.fine(txt.toString()); - - resp.getRenderParameters().setValue(""color"", clr); - - txt.setLength(0); - Part part = null; - try { - part = req.getPart(""file""); - } catch (Throwable t) {} - - if ((part != null) && (part.getSubmittedFileName() != null) && - (part.getSubmittedFileName().length() > 0)) { - txt.append(""Uploaded file name: "").append(part.getSubmittedFileName()); - txt.append("", part name: "").append(part.getName()); - txt.append("", size: "").append(part.getSize()); - txt.append("", content type: "").append(part.getContentType()); - lines.add(txt.toString()); - LOGGER.fine(txt.toString()); - txt.setLength(0); - txt.append(""Headers: ""); - String sep = """"; - for (String hdrname : part.getHeaderNames()) { - txt.append(sep).append(hdrname).append(""="").append(part.getHeaders(hdrname)); - sep = "", ""; - } - lines.add(txt.toString()); - LOGGER.fine(txt.toString()); - - // Store the file in a temporary location in the webapp where it can be served. - // Note that this is, in general, not what you want to do in production, as - // there can be problems serving the resource. Did it this way for a - // quick solution that doesn't require additional Tomcat configuration. - - try { - String fn = part.getSubmittedFileName(); - File img = getFile(fn); - if (img.exists()) { - lines.add(""deleting existing temp file: "" + img.getCanonicalPath()); - img.delete(); - } - InputStream is = part.getInputStream(); - Files.copy(is, img.toPath(), StandardCopyOption.REPLACE_EXISTING); - - resp.getRenderParameters().setValue(""fn"", fn); - resp.getRenderParameters().setValue(""ct"", part.getContentType()); - - } catch (Exception e) { - lines.add(""Exception doing I/O: "" + e.toString()); - - txt.setLength(0); - txt.append(""Problem getting temp file: "" + e.getMessage() + ""\n""); - StringWriter sw = new StringWriter(); - PrintWriter pw = new PrintWriter(sw); - e.printStackTrace(pw); - pw.flush(); - txt.append(sw.toString()); - LOGGER.warning(txt.toString()); - } - } else { - lines.add(""file part was null""); - } - - } - - @RenderMethod(portletNames = ""MultipartPortlet"") -" -259,0," public void configure() throws Exception { - - from(""direct:start1"") - .to(""xslt:org/apache/camel/component/xslt/transform_dtd.xsl"") - .to(""mock:result""); - - from(""direct:start2"") - .to(""xslt:org/apache/camel/component/xslt/transform_dtd.xsl?allowStAX=false"") - .to(""mock:result""); - } - }; - } - - -} -" -260,0," XSLTElementDef getElemDef() - { - return m_elemDef; - } - - /** - * Set the element definition that belongs to this element. - * - * @param def The element definition object that produced and constrains this element. - */ -" -261,0," public String getMethod() { - return this.method; - } - } - -} -" -262,0," public Result isAllowed(String principalId) { - LockoutPolicy lockoutPolicy = lockoutPolicyRetriever.getLockoutPolicy(); - - long eventsAfter = timeService.getCurrentTimeMillis() - lockoutPolicy.getCountFailuresWithin() * 1000; - List events = auditService.find(principalId, eventsAfter); - - final int failureCount = sequentialFailureCount(events); - - if (failureCount >= lockoutPolicy.getLockoutAfterFailures()) { - // Check whether time of most recent failure is within the lockout period - AuditEvent lastFailure = mostRecentFailure(events); - if (lastFailure != null && lastFailure.getTime() > timeService.getCurrentTimeMillis() - lockoutPolicy.getLockoutPeriodSeconds() * 1000) { - return new Result(false, failureCount); - } - } - return new Result(true, failureCount); - } - - /** - * Counts the number of failures that occurred without an intervening - * successful login. - */ -" -263,0," public OpenIDLoginConfigurer openidLogin() throws Exception { - return getOrApply(new OpenIDLoginConfigurer()); - } - - /** - * Adds the Security headers to the response. This is activated by default when using - * {@link WebSecurityConfigurerAdapter}'s default constructor. Accepting the - * default provided by {@link WebSecurityConfigurerAdapter} or only invoking - * {@link #headers()} without invoking additional methods on it, is the equivalent of: - * - *
-	 * @Configuration
-	 * @EnableWebSecurity
-	 * public class CsrfSecurityConfig extends WebSecurityConfigurerAdapter {
-	 *
-	 * 	@Override
-	 *     protected void configure(HttpSecurity http) throws Exception {
-	 *         http
-	 *             .headers()
-	 *                 .contentTypeOptions()
-	 *                 .and()
-	 *                 .xssProtection()
-	 *                 .and()
-	 *                 .cacheControl()
-	 *                 .and()
-	 *                 .httpStrictTransportSecurity()
-	 *                 .and()
-	 *                 .frameOptions()
-	 *                 .and()
-	 *             ...;
-	 *     }
-	 * }
-	 * 
- * - * You can disable the headers using the following: - * - *
-	 * @Configuration
-	 * @EnableWebSecurity
-	 * public class CsrfSecurityConfig extends WebSecurityConfigurerAdapter {
-	 *
-	 * 	@Override
-	 *     protected void configure(HttpSecurity http) throws Exception {
-	 *         http
-	 *             .headers().disable()
-	 *             ...;
-	 *     }
-	 * }
-	 * 
- * - * You can enable only a few of the headers by first invoking - * {@link HeadersConfigurer#defaultsDisabled()} - * and then invoking the appropriate methods on the {@link #headers()} result. - * For example, the following will enable {@link HeadersConfigurer#cacheControl()} and - * {@link HeadersConfigurer#frameOptions()} only. - * - *
-	 * @Configuration
-	 * @EnableWebSecurity
-	 * public class CsrfSecurityConfig extends WebSecurityConfigurerAdapter {
-	 *
-	 * 	@Override
-	 *     protected void configure(HttpSecurity http) throws Exception {
-	 *         http
-	 *             .headers()
-	 *                  .defaultsDisabled()
-	 *                  .cacheControl()
-	 *                  .and()
-	 *                  .frameOptions()
-	 *                  .and()
-	 *             ...;
-	 *     }
-	 * }
-	 * 
- * - * You can also choose to keep the defaults but explicitly disable a subset of headers. - * For example, the following will enable all the default headers except - * {@link HeadersConfigurer#frameOptions()}. - * - *
-	 * @Configuration
-	 * @EnableWebSecurity
-	 * public class CsrfSecurityConfig extends WebSecurityConfigurerAdapter {
-	 *
-	 * 	@Override
-	 *     protected void configure(HttpSecurity http) throws Exception {
-	 *         http
-	 *             .headers()
-	 *                  .frameOptions()
-	 *                  	.disable()
-	 *                  .and()
-	 *             ...;
-	 *     }
-	 * }
-	 * 
- * - * @return - * @throws Exception - * @see HeadersConfigurer - */ -" -264,0," public String toString() - { - return name; - } - } - -} -" -265,0," protected void validateOrderBy(String orderBy) throws IllegalArgumentException { - super.validateOrderBy(orderBy, EXTERNAL_GROUP_MAPPING_FIELDS); - } -" -266,0," public Object createObject(Attributes attributes) { - String username = attributes.getValue(""username""); - if (username == null) { - username = attributes.getValue(""name""); - } - String password = attributes.getValue(""password""); - String fullName = attributes.getValue(""fullName""); - if (fullName == null) { - fullName = attributes.getValue(""fullname""); - } - String groups = attributes.getValue(""groups""); - String roles = attributes.getValue(""roles""); - User user = database.createUser(username, password, fullName); - if (groups != null) { - while (groups.length() > 0) { - String groupname = null; - int comma = groups.indexOf(','); - if (comma >= 0) { - groupname = groups.substring(0, comma).trim(); - groups = groups.substring(comma + 1); - } else { - groupname = groups.trim(); - groups = """"; - } - if (groupname.length() > 0) { - Group group = database.findGroup(groupname); - if (group == null) { - group = database.createGroup(groupname, null); - } - user.addGroup(group); - } - } - } - if (roles != null) { - while (roles.length() > 0) { - String rolename = null; - int comma = roles.indexOf(','); - if (comma >= 0) { - rolename = roles.substring(0, comma).trim(); - roles = roles.substring(comma + 1); - } else { - rolename = roles.trim(); - roles = """"; - } - if (rolename.length() > 0) { - Role role = database.findRole(rolename); - if (role == null) { - role = database.createRole(rolename, null); - } - user.addRole(role); - } - } - } - return (user); - } - -" -267,0," public void testSendingStringMessage() throws Exception { - sendEntityMessage(MESSAGE); - } - -" -268,0," public InputSource resolveEntity(String name, String publicId, - String baseURI, String systemId) throws SAXException, - IOException { - throw new SAXException(sm.getString(""defaultServlet.blockExternalEntity2"", - name, publicId, baseURI, systemId)); - } - } -} -" -269,0," public static void init(TikaConfig config, DigestingParser.Digester digestr, - InputStreamFactory iSF) { - tikaConfig = config; - digester = digestr; - inputStreamFactory = iSF; - } - - static { -" -270,0," public void process(Exchange exchange) throws Exception { -" -271,0," public boolean createDB(String dbName, PortletRequest request) { - - // ensure there are no illegal chars in DB name - InputUtils.validateSafeInput(dbName); - - Connection conn = null; - try { - conn = DerbyConnectionUtil.getDerbyConnection(dbName, - DerbyConnectionUtil.CREATE_DB_PROP); - portlet.addInfoMessage(request, portlet.getLocalizedString(request, ""sysdb.infoMsg01"", dbName)); - return true; - } catch (Throwable e) { - portlet.addErrorMessage(request, portlet.getLocalizedString(request, ""sysdb.errorMsg01""), e.getMessage()); - return false; - } finally { - // close DB connection - try { - if (conn != null) { - conn.close(); - } - } catch (SQLException e) { - portlet.addErrorMessage(request, portlet.getLocalizedString(request, ""sysdb.errorMsg02""), e.getMessage()); - } - } - } - -" -272,0," public Member getCascadingMember() { - return cascadingMember; - } - - @Override -" -273,0," protected void finalize() throws Throwable { - super.finalize(); - dispose(); - } - -" -274,0," protected void handleClob(String tableName, String fieldName, int rowNum, - ResultSet resultSet, int columnIndex, - ContentHandler handler, ParseContext context) throws SQLException, IOException, SAXException { - //no-op for now. - } - - @Override -" -275,0," public void testNoConfig() throws Exception { - TesseractOCRConfig config = new TesseractOCRConfig(); - assertEquals(""Invalid default tesseractPath value"", """", config.getTesseractPath()); - assertEquals(""Invalid default tessdataPath value"", """", config.getTessdataPath()); - assertEquals(""Invalid default language value"", ""eng"", config.getLanguage()); - assertEquals(""Invalid default pageSegMode value"", ""1"", config.getPageSegMode()); - assertEquals(""Invalid default minFileSizeToOcr value"", 0, config.getMinFileSizeToOcr()); - assertEquals(""Invalid default maxFileSizeToOcr value"", Integer.MAX_VALUE, config.getMaxFileSizeToOcr()); - assertEquals(""Invalid default timeout value"", 120, config.getTimeout()); - assertEquals(""Invalid default ImageMagickPath value"", """", config.getImageMagickPath()); - assertEquals(""Invalid default density value"", 300 , config.getDensity()); - assertEquals(""Invalid default depth value"", 4 , config.getDepth()); - assertEquals(""Invalid default colorpsace value"", ""gray"" , config.getColorspace()); - assertEquals(""Invalid default filter value"", ""triangle"" , config.getFilter()); - assertEquals(""Invalid default resize value"", 900 , config.getResize()); - assertEquals(""Invalid default applyRotation value"", false, config.getApplyRotation()); - } - - @Test -" -276,0," public void onCreateSSLEngine(SSLEngine engine) { - if (proto.npnHandler != null) { - proto.npnHandler.onCreateEngine(engine); - } - } - } -} -" -277,0," public C mvcMatchers(HttpMethod method, String... mvcPatterns) { - HandlerMappingIntrospector introspector = new HandlerMappingIntrospector( - this.context); - List matchers = new ArrayList(mvcPatterns.length); - for (String mvcPattern : mvcPatterns) { - MvcRequestMatcher matcher = new MvcRequestMatcher(introspector, mvcPattern); - if (method != null) { - matcher.setMethod(method); - } - matchers.add(matcher); - } - return chainRequestMatchers(matchers); - } - - /** - * Maps a {@link List} of - * {@link org.springframework.security.web.util.matcher.RegexRequestMatcher} - * instances. - * - * @param method the {@link HttpMethod} to use or {@code null} for any - * {@link HttpMethod}. - * @param regexPatterns the regular expressions to create - * {@link org.springframework.security.web.util.matcher.RegexRequestMatcher} from - * - * @return the object that is chained after creating the {@link RequestMatcher} - */ -" -278,0," public DateTime getSessionNotOnOrAfter() { - return sessionNotOnOrAfter; - } - -" -279,0," public String getAlgorithm() - { - return ""XMSSMT""; - } - -" -280,0," public void setDynamicAttribute(String uri, String localName, Object value) throws JspException { - if (ComponentUtils.altSyntax(getStack()) && ComponentUtils.isExpression(value.toString())) { - dynamicAttributes.put(localName, String.valueOf(ObjectUtils.defaultIfNull(findValue(value.toString()), value))); - } else { - dynamicAttributes.put(localName, value); - } - } - -" -281,0," public String getDisplayName() { - return ""Suspects Causing Unit Tests to Begin Failing""; - } - } - -} -" -282,0," public MessageBytes newInstance() { - return new MessageBytes(); - } - } -} -" -283,0," public static void main(String[] args) { - new RunSQLHelper().runSQL(""derbyDB4"", - ""create table derbyTbl1(num int, addr varchar(40));"" - + ""create table derbyTbl2(num int, addr varchar(40));"" - + ""create table derbyTbl3(num int, addr varchar(40));"" - + ""insert into derb"", false); - } -" -284,0," public static VersionNumber getVersion() { - try { - return new VersionNumber(VERSION); - } catch (NumberFormatException e) { - try { - // for non-released version of Hudson, this looks like ""1.345 (private-foobar), so try to approximate. - int idx = VERSION.indexOf(' '); - if (idx>0) - return new VersionNumber(VERSION.substring(0,idx)); - } catch (NumberFormatException _) { - // fall through - } - - // totally unparseable - return null; - } catch (IllegalArgumentException e) { - // totally unparseable - return null; - } - } - - /** - * Hash of {@link #VERSION}. - */ -" -285,0," public void testUnsafeRedirectActionPrefix() throws Exception { - Map parameterMap = new HashMap(); - parameterMap.put(""redirectAction:"" + ""%{3*4}"", """"); - - StrutsMockHttpServletRequest request = new StrutsMockHttpServletRequest(); - request.setupGetServletPath(""/someServletPath.action""); - request.setParameterMap(parameterMap); - - DefaultActionMapper defaultActionMapper = new DefaultActionMapper(); - defaultActionMapper.setContainer(container); - ActionMapping actionMapping = defaultActionMapper.getMapping(request, configManager); - - - StrutsResultSupport result = (StrutsResultSupport) actionMapping.getResult(); - assertNull(result); - } - -" -286,0," public void testBeforeTest() throws IOException { - long clusterSeed = randomLong(); - int minNumDataNodes = randomIntBetween(0, 3); - int maxNumDataNodes = randomIntBetween(minNumDataNodes, 4); - final String clusterName = clusterName(""shared"", Integer.toString(CHILD_JVM_ID), clusterSeed); - String clusterName1 = clusterName(""shared"", Integer.toString(CHILD_JVM_ID), clusterSeed); - while (clusterName.equals(clusterName1)) { - clusterName1 = clusterName(""shared"", Integer.toString(CHILD_JVM_ID), clusterSeed); // spin until the time changes - } - SettingsSource settingsSource = SettingsSource.EMPTY; - int numClientNodes = randomIntBetween(0, 2); - boolean enableRandomBenchNodes = randomBoolean(); - boolean enableHttpPipelining = randomBoolean(); - int jvmOrdinal = randomIntBetween(0, 10); - String nodePrefix = ""foobar""; - - InternalTestCluster cluster0 = new InternalTestCluster(clusterSeed, minNumDataNodes, maxNumDataNodes, clusterName, settingsSource, numClientNodes, enableHttpPipelining, jvmOrdinal, nodePrefix); - InternalTestCluster cluster1 = new InternalTestCluster(clusterSeed, minNumDataNodes, maxNumDataNodes, clusterName1, settingsSource, numClientNodes, enableHttpPipelining, jvmOrdinal, nodePrefix); - - assertClusters(cluster0, cluster1, false); - long seed = randomLong(); - try { - { - Random random = new Random(seed); - cluster0.beforeTest(random, random.nextDouble()); - } - { - Random random = new Random(seed); - cluster1.beforeTest(random, random.nextDouble()); - } - assertArrayEquals(cluster0.getNodeNames(), cluster1.getNodeNames()); - Iterator iterator1 = cluster1.iterator(); - for (Client client : cluster0) { - assertTrue(iterator1.hasNext()); - Client other = iterator1.next(); - assertSettings(client.settings(), other.settings(), false); - } - assertArrayEquals(cluster0.getNodeNames(), cluster1.getNodeNames()); - cluster0.afterTest(); - cluster1.afterTest(); - } finally { - - IOUtils.close(cluster0, cluster1); - } - } -" -287,0," private String extractFullContextPath(HttpServletRequest request) throws MalformedURLException { - String result = null; - String contextPath = request.getContextPath(); - String requestUrl = request.getRequestURL().toString(); - String requestPath = new URL(requestUrl).getPath(); - // Cut request path of request url and add context path if not ROOT - if (requestPath != null && requestPath.length() > 0) { - int lastIndex = requestUrl.lastIndexOf(requestPath); - result = requestUrl.substring(0, lastIndex); - } else { - result = requestUrl; - } - if (contextPath != null && contextPath.length() > 0) { - // contextPath contains starting slash - result = result + contextPath + ""/""; - } else { - result = result + ""/""; - } - return result; - } -" -288,0," public String filenameOf(@Nonnull String id) { - return super.filenameOf(keyFor(id)); - } - - /** - * {@inheritDoc} - */ - @Override -" -289,0," ElementKind getKind(); -" -290,0," protected void service(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException { - log.trace(""Service: {}"", request); - - // is there a consumer registered for the request. - HttpConsumer consumer = getServletResolveConsumerStrategy().resolve(request, getConsumers()); - if (consumer == null) { - response.sendError(HttpServletResponse.SC_NOT_FOUND); - return; - } - - if (consumer.getEndpoint().getHttpMethodRestrict() != null) { - Iterator it = ObjectHelper.createIterable(consumer.getEndpoint().getHttpMethodRestrict()).iterator(); - boolean match = false; - while (it.hasNext()) { - String method = it.next().toString(); - if (method.equalsIgnoreCase(request.getMethod())) { - match = true; - break; - } - } - if (!match) { - response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED); - return; - } - } - - if (""TRACE"".equals(request.getMethod()) && !consumer.isTraceEnabled()) { - response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED); - return; - } - - // we do not support java serialized objects unless explicit enabled - String contentType = request.getContentType(); - if (HttpConstants.CONTENT_TYPE_JAVA_SERIALIZED_OBJECT.equals(contentType) && !consumer.getEndpoint().getComponent().isAllowJavaSerializedObject()) { - System.out.println(""415 miser !!!""); - response.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE); - return; - } - - final Exchange result = (Exchange) request.getAttribute(EXCHANGE_ATTRIBUTE_NAME); - if (result == null) { - // no asynchronous result so leverage continuation - final Continuation continuation = ContinuationSupport.getContinuation(request); - if (continuation.isInitial() && continuationTimeout != null) { - // set timeout on initial - continuation.setTimeout(continuationTimeout); - } - - // are we suspended and a request is dispatched initially? - if (consumer.isSuspended() && continuation.isInitial()) { - response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); - return; - } - - if (continuation.isExpired()) { - String id = (String) continuation.getAttribute(EXCHANGE_ATTRIBUTE_ID); - // remember this id as expired - expiredExchanges.put(id, id); - log.warn(""Continuation expired of exchangeId: {}"", id); - response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); - return; - } - - // a new request so create an exchange - final Exchange exchange = new DefaultExchange(consumer.getEndpoint(), ExchangePattern.InOut); - - if (consumer.getEndpoint().isBridgeEndpoint()) { - exchange.setProperty(Exchange.SKIP_GZIP_ENCODING, Boolean.TRUE); - exchange.setProperty(Exchange.SKIP_WWW_FORM_URLENCODED, Boolean.TRUE); - } - if (consumer.getEndpoint().isDisableStreamCache()) { - exchange.setProperty(Exchange.DISABLE_HTTP_STREAM_CACHE, Boolean.TRUE); - } - - HttpHelper.setCharsetFromContentType(request.getContentType(), exchange); - - exchange.setIn(new HttpMessage(exchange, request, response)); - // set context path as header - String contextPath = consumer.getEndpoint().getPath(); - exchange.getIn().setHeader(""CamelServletContextPath"", contextPath); - - String httpPath = (String)exchange.getIn().getHeader(Exchange.HTTP_PATH); - // here we just remove the CamelServletContextPath part from the HTTP_PATH - if (contextPath != null - && httpPath.startsWith(contextPath)) { - exchange.getIn().setHeader(Exchange.HTTP_PATH, - httpPath.substring(contextPath.length())); - } - - if (log.isTraceEnabled()) { - log.trace(""Suspending continuation of exchangeId: {}"", exchange.getExchangeId()); - } - continuation.setAttribute(EXCHANGE_ATTRIBUTE_ID, exchange.getExchangeId()); - - // we want to handle the UoW - try { - consumer.createUoW(exchange); - } catch (Exception e) { - log.error(""Error processing request"", e); - throw new ServletException(e); - } - - // must suspend before we process the exchange - continuation.suspend(); - - ClassLoader oldTccl = overrideTccl(exchange); - - if (log.isTraceEnabled()) { - log.trace(""Processing request for exchangeId: {}"", exchange.getExchangeId()); - } - // use the asynchronous API to process the exchange - - consumer.getAsyncProcessor().process(exchange, new AsyncCallback() { - public void done(boolean doneSync) { - // check if the exchange id is already expired - boolean expired = expiredExchanges.remove(exchange.getExchangeId()) != null; - if (!expired) { - if (log.isTraceEnabled()) { - log.trace(""Resuming continuation of exchangeId: {}"", exchange.getExchangeId()); - } - // resume processing after both, sync and async callbacks - continuation.setAttribute(EXCHANGE_ATTRIBUTE_NAME, exchange); - continuation.resume(); - } else { - log.warn(""Cannot resume expired continuation of exchangeId: {}"", exchange.getExchangeId()); - } - } - }); - - if (oldTccl != null) { - restoreTccl(exchange, oldTccl); - } - - // return to let Jetty continuation to work as it will resubmit and invoke the service - // method again when its resumed - return; - } - - try { - // now lets output to the response - if (log.isTraceEnabled()) { - log.trace(""Resumed continuation and writing response for exchangeId: {}"", result.getExchangeId()); - } - Integer bs = consumer.getEndpoint().getResponseBufferSize(); - if (bs != null) { - log.trace(""Using response buffer size: {}"", bs); - response.setBufferSize(bs); - } - consumer.getBinding().writeResponse(result, response); - } catch (IOException e) { - log.error(""Error processing request"", e); - throw e; - } catch (Exception e) { - log.error(""Error processing request"", e); - throw new ServletException(e); - } finally { - consumer.doneUoW(result); - } - } - -" -291,0," public String getTreeDigest() - { - return DigestUtil.getXMSSDigestName(treeDigest); - } -" -292,0," public void setCustomWorkspace(String customWorkspace) throws IOException { - this.customWorkspace= Util.fixEmptyAndTrim(customWorkspace); - save(); - } - -" -293,0," public String nextElement() { - underlying.nextElement(); - return ""application/json""; - } - - } -}" -294,0," public Set getSupportedTypes(ParseContext context) { - return getWrappedParser().getSupportedTypes(context); - } - - /** - * Acts like a regular parser except it ignores the ContentHandler - * and it automatically sets/overwrites the embedded Parser in the - * ParseContext object. - *

- * To retrieve the results of the parse, use {@link #getMetadata()}. - *

- * Make sure to call {@link #reset()} after each parse. - */ - @Override -" -295,0," private void init(InputStream is) { - if (is == null) { - return; - } - Properties props = new Properties(); - try { - props.load(is); - } catch (IOException e) { - } finally { - if (is != null) { - try { - is.close(); - } catch (IOException e) { - //swallow - } - } - } - - // set parameters for Tesseract - setTesseractPath( - getProp(props, ""tesseractPath"", getTesseractPath())); - setTessdataPath( - getProp(props, ""tessdataPath"", getTessdataPath())); - setLanguage( - getProp(props, ""language"", getLanguage())); - setPageSegMode( - getProp(props, ""pageSegMode"", getPageSegMode())); - setMinFileSizeToOcr( - getProp(props, ""minFileSizeToOcr"", getMinFileSizeToOcr())); - setMaxFileSizeToOcr( - getProp(props, ""maxFileSizeToOcr"", getMaxFileSizeToOcr())); - setTimeout( - getProp(props, ""timeout"", getTimeout())); - setOutputType(getProp(props, ""outputType"", getOutputType().toString())); - setPreserveInterwordSpacing(getProp(props, ""preserveInterwordSpacing"", false)); - - // set parameters for ImageMagick - setEnableImageProcessing( - getProp(props, ""enableImageProcessing"", isEnableImageProcessing())); - setImageMagickPath( - getProp(props, ""ImageMagickPath"", getImageMagickPath())); - setDensity( - getProp(props, ""density"", getDensity())); - setDepth( - getProp(props, ""depth"", getDepth())); - setColorspace( - getProp(props, ""colorspace"", getColorspace())); - setFilter( - getProp(props, ""filter"", getFilter())); - setResize( - getProp(props, ""resize"", getResize())); - setApplyRotation( - getProp(props, ""applyRotation"", getApplyRotation())); - - loadOtherTesseractConfig(props); - } - - /** - * @see #setTesseractPath(String tesseractPath) - */ -" -296,0," public String getInfo() { - - return (info); - - } - - -" -297,0," public int callback(int num_msg, Pointer msg, Pointer resp, Pointer _) { - LOGGER.fine(""pam_conv num_msg=""+num_msg); - if(password==null) - return PAM_CONV_ERR; - - // allocates pam_response[num_msg]. the caller will free this - Pointer m = libc.calloc(pam_response.SIZE,num_msg); - resp.setPointer(0,m); - - for( int i=0; i - * J.3.2, Page 155, ECDSA over the field Fp
- * an example with 239 bit prime - */ -" -300,0," private void debug(String msg) { - if ( logger.isDebugEnabled() ) { - logger.debug(Logger.EVENT_SUCCESS, msg); - } - } -" -301,0," private static DocumentBuilderFactory createDocumentBuilderFactory() throws ParserConfigurationException { - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING , true); - - dbf.setValidating(false); - dbf.setIgnoringComments(false); - dbf.setIgnoringElementContentWhitespace(true); - dbf.setNamespaceAware(true); - // dbf.setCoalescing(true); - // dbf.setExpandEntityReferences(true); - - return dbf; - } - - /** - * Read XML as DOM. - */ -" -302,0," public void changePassword_Resets_All_Sessions() throws Exception { - ScimUser user = createUser(); - - MockHttpSession session = new MockHttpSession(); - MockHttpSession afterLoginSessionA = (MockHttpSession) getMockMvc().perform(post(""/login.do"") - .session(session) - .accept(TEXT_HTML_VALUE) - .param(""username"", user.getUserName()) - .param(""password"", ""secr3T"")) - .andExpect(status().isFound()) - .andExpect(redirectedUrl(""/"")) - .andReturn().getRequest().getSession(false); - - session = new MockHttpSession(); - MockHttpSession afterLoginSessionB = (MockHttpSession) getMockMvc().perform(post(""/login.do"") - .session(session) - .accept(TEXT_HTML_VALUE) - .param(""username"", user.getUserName()) - .param(""password"", ""secr3T"")) - .andExpect(status().isFound()) - .andExpect(redirectedUrl(""/"")) - .andReturn().getRequest().getSession(false); - - - assertNotNull(afterLoginSessionA.getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY)); - assertNotNull(afterLoginSessionB.getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY)); - - getMockMvc().perform(get(""/profile"").session(afterLoginSessionB)) - .andExpect(status().isOk()); - - Thread.sleep(1000 - (System.currentTimeMillis() % 1000) + 1); - - MockHttpSession afterPasswordChange = (MockHttpSession) getMockMvc().perform(post(""/change_password.do"") - .session(afterLoginSessionA) - .with(csrf()) - .accept(TEXT_HTML_VALUE) - .param(""current_password"", ""secr3T"") - .param(""new_password"", ""secr3T1"") - .param(""confirm_password"", ""secr3T1"")) - .andExpect(status().isFound()) - .andExpect(redirectedUrl(""profile"")) - .andReturn().getRequest().getSession(false); - - assertTrue(afterLoginSessionA.isInvalid()); - assertNotNull(afterPasswordChange); - assertNotNull(afterPasswordChange.getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY)); - assertNotSame(afterLoginSessionA, afterPasswordChange); - getMockMvc().perform( - get(""/profile"") - .session(afterLoginSessionB) - .accept(TEXT_HTML)) - .andExpect(status().isFound()) - .andExpect(redirectedUrl(""/login"")); - - } - -" -303,0," public void setValueStackFactory(ValueStackFactory valueStackFactory) { - this.valueStackFactory = valueStackFactory; - } - - @Inject(""devMode"") -" -304,0," private List createAuthInfo(SolrZkClient zkClient) { - List ret = new LinkedList(); - - // 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; - } - } -} -" -305,0," public String changePassword( - Model model, - @RequestParam(""current_password"") String currentPassword, - @RequestParam(""new_password"") String newPassword, - @RequestParam(""confirm_password"") String confirmPassword, - HttpServletResponse response, - HttpServletRequest request) { - - PasswordConfirmationValidation validation = new PasswordConfirmationValidation(newPassword, confirmPassword); - if (!validation.valid()) { - model.addAttribute(""message_code"", validation.getMessageCode()); - response.setStatus(HttpStatus.UNPROCESSABLE_ENTITY.value()); - return ""change_password""; - } - - SecurityContext securityContext = SecurityContextHolder.getContext(); - Authentication authentication = securityContext.getAuthentication(); - String username = authentication.getName(); - - try { - changePasswordService.changePassword(username, currentPassword, newPassword); - request.getSession().invalidate(); - request.getSession(true); - if (authentication instanceof UaaAuthentication) { - UaaAuthentication uaaAuthentication = (UaaAuthentication)authentication; - authentication = new UaaAuthentication( - uaaAuthentication.getPrincipal(), - new LinkedList<>(uaaAuthentication.getAuthorities()), - new UaaAuthenticationDetails(request) - ); - } - securityContext.setAuthentication(authentication); - return ""redirect:profile""; - } catch (BadCredentialsException e) { - model.addAttribute(""message_code"", ""unauthorized""); - } catch (InvalidPasswordException e) { - model.addAttribute(""message"", e.getMessagesAsOneString()); - } - response.setStatus(HttpStatus.UNPROCESSABLE_ENTITY.value()); - return ""change_password""; - } -" -306,0," public void testSnapshotMoreThanOnce() throws ExecutionException, InterruptedException, IOException { - Client client = client(); - final File tempDir = randomRepoPath().getAbsoluteFile(); - logger.info(""--> creating repository""); - assertAcked(client.admin().cluster().preparePutRepository(""test-repo"") - .setType(""fs"").setSettings(ImmutableSettings.settingsBuilder() - .put(""location"", tempDir) - .put(""compress"", randomBoolean()) - .put(""chunk_size"", randomIntBetween(100, 1000)))); - - // only one shard - assertAcked(prepareCreate(""test"").setSettings(ImmutableSettings.builder() - .put(IndexMetaData.SETTING_NUMBER_OF_SHARDS, 1) - .put(IndexMetaData.SETTING_NUMBER_OF_REPLICAS, 0) - )); - ensureYellow(); - logger.info(""--> indexing""); - - final int numDocs = randomIntBetween(10, 100); - IndexRequestBuilder[] builders = new IndexRequestBuilder[numDocs]; - for (int i = 0; i < builders.length; i++) { - builders[i] = client().prepareIndex(""test"", ""doc"", Integer.toString(i)).setSource(""foo"", ""bar"" + i); - } - indexRandom(true, builders); - flushAndRefresh(); - assertNoFailures(client().admin().indices().prepareOptimize(""test"").setFlush(true).setMaxNumSegments(1).get()); - - CreateSnapshotResponse createSnapshotResponseFirst = client.admin().cluster().prepareCreateSnapshot(""test-repo"", ""test"").setWaitForCompletion(true).setIndices(""test"").get(); - assertThat(createSnapshotResponseFirst.getSnapshotInfo().successfulShards(), greaterThan(0)); - assertThat(createSnapshotResponseFirst.getSnapshotInfo().successfulShards(), equalTo(createSnapshotResponseFirst.getSnapshotInfo().totalShards())); - assertThat(client.admin().cluster().prepareGetSnapshots(""test-repo"").setSnapshots(""test"").get().getSnapshots().get(0).state(), equalTo(SnapshotState.SUCCESS)); - { - SnapshotStatus snapshotStatus = client.admin().cluster().prepareSnapshotStatus(""test-repo"").setSnapshots(""test"").get().getSnapshots().get(0); - List shards = snapshotStatus.getShards(); - for (SnapshotIndexShardStatus status : shards) { - assertThat(status.getStats().getProcessedFiles(), greaterThan(1)); - } - } - if (frequently()) { - logger.info(""--> upgrade""); - client().admin().indices().prepareUpdateSettings(""test"").setSettings(ImmutableSettings.builder().put(EnableAllocationDecider.INDEX_ROUTING_ALLOCATION_ENABLE, ""none"")).get(); - backwardsCluster().allowOnAllNodes(""test""); - logClusterState(); - boolean upgraded; - do { - logClusterState(); - CountResponse countResponse = client().prepareCount().get(); - assertHitCount(countResponse, numDocs); - upgraded = backwardsCluster().upgradeOneNode(); - ensureYellow(); - countResponse = client().prepareCount().get(); - assertHitCount(countResponse, numDocs); - } while (upgraded); - client().admin().indices().prepareUpdateSettings(""test"").setSettings(ImmutableSettings.builder().put(EnableAllocationDecider.INDEX_ROUTING_ALLOCATION_ENABLE, ""all"")).get(); - } - if (cluster().numDataNodes() > 1 && randomBoolean()) { // only bump the replicas if we have enough nodes - logger.info(""--> move from 0 to 1 replica""); - client().admin().indices().prepareUpdateSettings(""test"").setSettings(ImmutableSettings.builder().put(IndexMetaData.SETTING_NUMBER_OF_REPLICAS, 1)).get(); - } - logger.debug(""---> repo exists: "" + new File(tempDir, ""indices/test/0"").exists() + "" files: "" + Arrays.toString(new File(tempDir, ""indices/test/0"").list())); // it's only one shard! - CreateSnapshotResponse createSnapshotResponseSecond = client.admin().cluster().prepareCreateSnapshot(""test-repo"", ""test-1"").setWaitForCompletion(true).setIndices(""test"").get(); - assertThat(createSnapshotResponseSecond.getSnapshotInfo().successfulShards(), greaterThan(0)); - assertThat(createSnapshotResponseSecond.getSnapshotInfo().successfulShards(), equalTo(createSnapshotResponseSecond.getSnapshotInfo().totalShards())); - assertThat(client.admin().cluster().prepareGetSnapshots(""test-repo"").setSnapshots(""test-1"").get().getSnapshots().get(0).state(), equalTo(SnapshotState.SUCCESS)); - { - SnapshotStatus snapshotStatus = client.admin().cluster().prepareSnapshotStatus(""test-repo"").setSnapshots(""test-1"").get().getSnapshots().get(0); - List shards = snapshotStatus.getShards(); - for (SnapshotIndexShardStatus status : shards) { - - assertThat(status.getStats().getProcessedFiles(), equalTo(1)); // we flush before the snapshot such that we have to process the segments_N files - } - } - - client().prepareDelete(""test"", ""doc"", ""1"").get(); - CreateSnapshotResponse createSnapshotResponseThird = client.admin().cluster().prepareCreateSnapshot(""test-repo"", ""test-2"").setWaitForCompletion(true).setIndices(""test"").get(); - assertThat(createSnapshotResponseThird.getSnapshotInfo().successfulShards(), greaterThan(0)); - assertThat(createSnapshotResponseThird.getSnapshotInfo().successfulShards(), equalTo(createSnapshotResponseThird.getSnapshotInfo().totalShards())); - assertThat(client.admin().cluster().prepareGetSnapshots(""test-repo"").setSnapshots(""test-2"").get().getSnapshots().get(0).state(), equalTo(SnapshotState.SUCCESS)); - { - SnapshotStatus snapshotStatus = client.admin().cluster().prepareSnapshotStatus(""test-repo"").setSnapshots(""test-2"").get().getSnapshots().get(0); - List shards = snapshotStatus.getShards(); - for (SnapshotIndexShardStatus status : shards) { - assertThat(status.getStats().getProcessedFiles(), equalTo(2)); // we flush before the snapshot such that we have to process the segments_N files plus the .del file - } - } - } -" -307,0," protected static void setupFeatures(DocumentBuilderFactory factory) { - Properties properties = System.getProperties(); - List features = new ArrayList(); - for (Map.Entry prop : properties.entrySet()) { - String key = (String) prop.getKey(); - if (key.startsWith(DOCUMENT_BUILDER_FACTORY_FEATURE)) { - String uri = key.split(DOCUMENT_BUILDER_FACTORY_FEATURE + "":"")[1]; - Boolean value = Boolean.valueOf((String)prop.getValue()); - try { - factory.setFeature(uri, value); - features.add(""feature "" + uri + "" value "" + value); - } catch (ParserConfigurationException e) { - LOG.warn(""DocumentBuilderFactory doesn't support the feature {} with value {}, due to {}."", new Object[]{uri, value, e}); - } - } - } - if (features.size() > 0) { - StringBuffer featureString = new StringBuffer(); - // just log the configured feature - for (String feature : features) { - if (featureString.length() != 0) { - featureString.append("", ""); - } - featureString.append(feature); - } - } - - } - -" -308,0," public void testSaveAndLoad() throws IOException { - assumeTrue(AppleNativeIntegrationTestUtils.isApplePlatformAvailable(ApplePlatform.MACOSX)); - - ProjectWorkspace workspace = - TestDataHelper.createProjectWorkspaceForScenario(this, ""parser_with_cell"", tmp); - workspace.setUp(); - - // Warm the parser cache. - TestContext context = new TestContext(); - ProcessResult runBuckResult = - workspace.runBuckdCommand(context, ""query"", ""deps(//Apps:TestAppsLibrary)""); - runBuckResult.assertSuccess(); - assertThat( - runBuckResult.getStdout(), - Matchers.containsString( - ""//Apps:TestAppsLibrary\n"" - + ""//Libraries/Dep1:Dep1_1\n"" - + ""//Libraries/Dep1:Dep1_2\n"" - + ""bar//Dep2:Dep2"")); - - // Save the parser cache to a file. - NamedTemporaryFile tempFile = new NamedTemporaryFile(""parser_data"", null); - runBuckResult = - workspace.runBuckdCommand(context, ""parser-cache"", ""--save"", tempFile.get().toString()); - runBuckResult.assertSuccess(); - - // Write an empty content to Apps/BUCK. - Path path = tmp.getRoot().resolve(""Apps/BUCK""); - byte[] data = {}; - Files.write(path, data); - - context = new TestContext(); - // Load the parser cache to a new buckd context. - runBuckResult = - workspace.runBuckdCommand(context, ""parser-cache"", ""--load"", tempFile.get().toString()); - runBuckResult.assertSuccess(); - - // Perform the query again. If we didn't load the parser cache, this call would fail because - // Apps/BUCK is empty. - runBuckResult = workspace.runBuckdCommand(context, ""query"", ""deps(//Apps:TestAppsLibrary)""); - runBuckResult.assertSuccess(); - assertThat( - runBuckResult.getStdout(), - Matchers.containsString( - ""//Apps:TestAppsLibrary\n"" - + ""//Libraries/Dep1:Dep1_1\n"" - + ""//Libraries/Dep1:Dep1_2\n"" - + ""bar//Dep2:Dep2"")); - } - - @Test -" -309,0," public void setEnforceAssertionsSigned(boolean enforceAssertionsSigned) { - this.enforceAssertionsSigned = enforceAssertionsSigned; - } - - /** - * Enforce that the Issuer of the received Response/Assertion is known. The default is true. - */ -" -310,0," public void setUp() throws Exception { - SecurityContextHolder.clearContext(); - scimUserProvisioning = mock(ScimUserProvisioning.class); - codeStore = mock(ExpiringCodeStore.class); - passwordValidator = mock(PasswordValidator.class); - clientDetailsService = mock(ClientDetailsService.class); - emailResetPasswordService = new UaaResetPasswordService(scimUserProvisioning, codeStore, passwordValidator, clientDetailsService); - } - - @After -" -311,0," public static final void main(String args[]) { - System.out.println(""Supported pseudo-random functions for KDF (version: "" + kdfVersion + "")""); - System.out.println(""Enum Name\tAlgorithm\t# bits""); - for (PRF_ALGORITHMS prf : PRF_ALGORITHMS.values()) { - System.out.println(prf + ""\t"" + prf.getAlgName() + ""\t"" + prf.getBits()); - } - } -" -312,0," private void doTestExtensionSizeLimit(int len, boolean ok) throws Exception { - // Setup Tomcat instance - Tomcat tomcat = getTomcatInstance(); - - tomcat.getConnector().setProperty( - ""maxExtensionSize"", Integer.toString(EXT_SIZE_LIMIT)); - - // Must have a real docBase - just use temp - Context ctx = - tomcat.addContext("""", System.getProperty(""java.io.tmpdir"")); - - Tomcat.addServlet(ctx, ""servlet"", new EchoHeaderServlet()); - ctx.addServletMapping(""/"", ""servlet""); - - tomcat.start(); - - String extName = "";foo=""; - StringBuilder extValue = new StringBuilder(len); - for (int i = 0; i < (len - extName.length()); i++) { - extValue.append(""x""); - } - - String[] request = new String[]{ - ""POST /echo-params.jsp HTTP/1.1"" + SimpleHttpClient.CRLF + - ""Host: any"" + SimpleHttpClient.CRLF + - ""Transfer-encoding: chunked"" + SimpleHttpClient.CRLF + - ""Content-Type: application/x-www-form-urlencoded"" + - SimpleHttpClient.CRLF + - ""Connection: close"" + SimpleHttpClient.CRLF + - SimpleHttpClient.CRLF + - ""3"" + extName + extValue.toString() + SimpleHttpClient.CRLF + - ""a=0"" + SimpleHttpClient.CRLF + - ""4"" + SimpleHttpClient.CRLF + - ""&b=1"" + SimpleHttpClient.CRLF + - ""0"" + SimpleHttpClient.CRLF + - SimpleHttpClient.CRLF }; - - TrailerClient client = - new TrailerClient(tomcat.getConnector().getLocalPort()); - client.setRequest(request); - - client.connect(); - client.processRequest(); - - if (ok) { - assertTrue(client.isResponse200()); - } else { - assertTrue(client.isResponse500()); - } - } - - @Test -" -313,0," void sendPluginResult(PluginResult pluginResult) { - synchronized (this) { - if (!aborted) { - callbackContext.sendPluginResult(pluginResult); - } - } - } - } - - /** - * Adds an interface method to an InputStream to return the number of bytes - * read from the raw stream. This is used to track total progress against - * the HTTP Content-Length header value from the server. - */ -" -314,0," public void setHttpClient(HttpClient httpClient) { - this.httpClient = httpClient; - } -" -315,0," protected Log getLog() { - return log; - } - - // ------------------------------------------------------------ Constructor - - -" -316,0," public void doStart() throws Exception { - URI rootURI; - if (serverInfo != null) { - rootURI = serverInfo.resolveServer(configuredDir); - } else { - rootURI = configuredDir; - } - if (!rootURI.getScheme().equals(""file"")) { - throw new IllegalStateException(""FileKeystoreManager must have a root that's a local directory (not "" + rootURI + "")""); - } - directory = new File(rootURI); - if (!directory.exists() || !directory.isDirectory() || !directory.canRead()) { - throw new IllegalStateException(""FileKeystoreManager must have a root that's a valid readable directory (not "" + directory.getAbsolutePath() + "")""); - } - log.debug(""Keystore directory is "" + directory.getAbsolutePath()); - } - -" -317,0," public void setMaxSize(String maxSize) { - this.maxSize = Long.parseLong(maxSize); - } - - /** - * Sets the buffer size to be used. - * - * @param bufferSize - */ - @Inject(value = StrutsConstants.STRUTS_MULTIPART_BUFFERSIZE, required = false) -" -318,0," public void execute(FunctionContext context) { - // Verify that the cache exists before continuing. - // When this function is executed by a remote membership listener, it is - // being invoked before the cache is started. - Cache cache = verifyCacheExists(); - - // Register as membership listener - registerAsMembershipListener(cache); - - // Register functions - registerFunctions(); - - // Return status - context.getResultSender().lastResult(Boolean.TRUE); - } - -" -319,0," public void setSocketBuffer(int socketBuffer) { - super.setSocketBuffer(socketBuffer); - outputBuffer.setSocketBuffer(socketBuffer); - } -" -320,0," public void waitForAllNodes(int timeout) throws IOException, InterruptedException { - waitForAllNodes(jettys.size(), timeout); - } - -" -321,0," static MatcherType fromElement(Element elt) { - if (StringUtils.hasText(elt.getAttribute(ATT_MATCHER_TYPE))) { - return valueOf(elt.getAttribute(ATT_MATCHER_TYPE)); - } - - return ant; - } -" -322,0," public int realReadBytes(byte cbuf[], int off, int len) - throws IOException; - } - - /** Same as java.nio.channel.WrittableByteChannel. - */ -" -323,0," public void complete() { - if (log.isDebugEnabled()) { - logDebug(""complete ""); - } - check(); - request.getCoyoteRequest().action(ActionCode.ASYNC_COMPLETE, null); - } - - @Override -" -324,0," public void testContainsExpressionIsFalse() throws Exception { - // given - String anExpression = ""foo""; - - // when - boolean actual = ComponentUtils.containsExpression(anExpression); - - // then - assertFalse(actual); - } -} - -class MockConfigurationProvider implements ConfigurationProvider { - - public void destroy() { - } - - public void init(Configuration configuration) throws ConfigurationException { - } - - public boolean needsReload() { - return false; - } - - public void loadPackages() throws ConfigurationException { - } - - public void register(ContainerBuilder builder, LocatableProperties props) throws ConfigurationException { - builder.constant(StrutsConstants.STRUTS_TAG_ALTSYNTAX, ""false""); - } -" -325,0," @Test(timeout = 1000L) public void testCeilLongMonths() throws Exception { - Calendar cal = Calendar.getInstance(); - cal.set(Calendar.MONTH, Calendar.NOVEMBER); - new CronTab(""0 0 31 * *"").ceil(cal); // would infinite loop - } -" -326,0," public static File unzip(File zip, File toDir, Predicate filter) throws IOException { - if (!toDir.exists()) { - FileUtils.forceMkdir(toDir); - } - - Path targetDirNormalizedPath = toDir.toPath().normalize(); - ZipFile zipFile = new ZipFile(zip); - try { - Enumeration entries = zipFile.entries(); - while (entries.hasMoreElements()) { - ZipEntry entry = entries.nextElement(); - if (filter.test(entry)) { - File target = new File(toDir, entry.getName()); - - verifyInsideTargetDirectory(entry, target.toPath(), targetDirNormalizedPath); - - if (entry.isDirectory()) { - throwExceptionIfDirectoryIsNotCreatable(target); - } else { - File parent = target.getParentFile(); - throwExceptionIfDirectoryIsNotCreatable(parent); - copy(zipFile, entry, target); - } - } - } - return toDir; - - } finally { - zipFile.close(); - } - } - -" -327,0," public Authentication authenticate(Authentication req) throws AuthenticationException { - logger.debug(""Processing authentication request for "" + req.getName()); - - if (req.getCredentials() == null) { - BadCredentialsException e = new BadCredentialsException(""No password supplied""); - publish(new AuthenticationFailureBadCredentialsEvent(req, e)); - throw e; - } - - UaaUser user; - boolean passwordMatches = false; - user = getUaaUser(req); - if (user!=null) { - passwordMatches = - ((CharSequence) req.getCredentials()).length() != 0 && encoder.matches((CharSequence) req.getCredentials(), user.getPassword()); - } else { - user = dummyUser; - } - - if (!accountLoginPolicy.isAllowed(user, req)) { - logger.warn(""Login policy rejected authentication for "" + user.getUsername() + "", "" + user.getId() - + "". Ignoring login request.""); - AuthenticationPolicyRejectionException e = new AuthenticationPolicyRejectionException(""Login policy rejected authentication""); - publish(new AuthenticationFailureLockedEvent(req, e)); - throw e; - } - - if (passwordMatches) { - logger.debug(""Password successfully matched for userId[""+user.getUsername()+""]:""+user.getId()); - - if (!allowUnverifiedUsers && !user.isVerified()) { - publish(new UnverifiedUserAuthenticationEvent(user, req)); - logger.debug(""Account not verified: "" + user.getId()); - throw new AccountNotVerifiedException(""Account not verified""); - } - - int expiringPassword = getPasswordExpiresInMonths(); - if (expiringPassword>0) { - Calendar cal = Calendar.getInstance(); - cal.setTimeInMillis(user.getPasswordLastModified().getTime()); - cal.add(Calendar.MONTH, expiringPassword); - if (cal.getTimeInMillis() < System.currentTimeMillis()) { - throw new PasswordExpiredException(""Your current password has expired. Please reset your password.""); - } - } - - Authentication success = new UaaAuthentication( - new UaaPrincipal(user), - user.getAuthorities(), - (UaaAuthenticationDetails) req.getDetails()); - - publish(new UserAuthenticationSuccessEvent(user, success)); - - return success; - } - - if (user == dummyUser || user == null) { - logger.debug(""No user named '"" + req.getName() + ""' was found for origin:""+ origin); - publish(new UserNotFoundEvent(req)); - } else { - logger.debug(""Password did not match for user "" + req.getName()); - publish(new UserAuthenticationFailureEvent(user, req)); - } - BadCredentialsException e = new BadCredentialsException(""Bad credentials""); - publish(new AuthenticationFailureBadCredentialsEvent(req, e)); - throw e; - } - -" -328,0," public void test_SignedWithoutSignature() throws Exception { - JWT inputJwt = new JWT() - .setSubject(""123456789"") - .setIssuedAt(ZonedDateTime.now(ZoneOffset.UTC)) - .setExpiration(ZonedDateTime.now(ZoneOffset.UTC).plusHours(2)); - - String encodedJWT = JWT.getEncoder().encode(inputJwt, HMACSigner.newSHA256Signer(""secret"")); - String encodedJWTNoSignature = encodedJWT.substring(0, encodedJWT.lastIndexOf('.') + 1); - - expectException(InvalidJWTSignatureException.class, () -> JWT.getDecoder().decode(encodedJWTNoSignature, HMACVerifier.newVerifier(""secret""))); - - // Also cannot be decoded even if the caller calls decode w/out a signature because the header still indicates a signature algorithm. - expectException(InvalidJWTSignatureException.class, () -> JWT.getDecoder().decode(encodedJWTNoSignature)); - } - - @Test -" -329,0," public void initJdbcScimUserProvisioningTests() throws Exception { - db = new JdbcScimUserProvisioning(jdbcTemplate, new JdbcPagingListFactory(jdbcTemplate, limitSqlAdapter)); - zoneDb = new JdbcIdentityZoneProvisioning(jdbcTemplate); - providerDb = new JdbcIdentityProviderProvisioning(jdbcTemplate); - ScimSearchQueryConverter filterConverter = new ScimSearchQueryConverter(); - Map replaceWith = new HashMap(); - replaceWith.put(""emails\\.value"", ""email""); - replaceWith.put(""groups\\.display"", ""authorities""); - replaceWith.put(""phoneNumbers\\.value"", ""phoneNumber""); - filterConverter.setAttributeNameMapper(new SimpleAttributeNameMapper(replaceWith)); - db.setQueryConverter(filterConverter); - BCryptPasswordEncoder pe = new BCryptPasswordEncoder(4); - - existingUserCount = jdbcTemplate.queryForInt(""select count(id) from users""); - - defaultIdentityProviderId = jdbcTemplate.queryForObject(""select id from identity_provider where origin_key = ? and identity_zone_id = ?"", String.class, Origin.UAA, ""uaa""); - - addUser(JOE_ID, ""joe"", pe.encode(""joespassword""), ""joe@joe.com"", ""Joe"", ""User"", ""+1-222-1234567"", defaultIdentityProviderId, ""uaa""); - addUser(MABEL_ID, ""mabel"", pe.encode(""mabelspassword""), ""mabel@mabel.com"", ""Mabel"", ""User"", """", defaultIdentityProviderId, ""uaa""); - } - -" -330,0," public void setUp() throws Exception { - lc = new LoggerContext(); - lc.setName(""testContext""); - logger = lc.getLogger(LoggerSerializationTest.class); - // create the byte output stream - bos = new ByteArrayOutputStream(); - oos = new ObjectOutputStream(bos); - whitelist = LogbackClassicSerializationHelper.getWhilelist(); - whitelist.add(Foo.class.getName()); - } - - @After -" -331,0," public void withFieldsAndXpath() throws Exception { - File tmpdir = File.createTempFile(""test"", ""tmp"", TEMP_DIR); - tmpdir.delete(); - tmpdir.mkdir(); - tmpdir.deleteOnExit(); - createFile(tmpdir, ""x.xsl"", xsl.getBytes(""UTF-8""), false); - Map entityAttrs = createMap(""name"", ""e"", ""url"", ""cd.xml"", - XPathEntityProcessor.FOR_EACH, ""/catalog/cd""); - List fields = new ArrayList(); - fields.add(createMap(""column"", ""title"", ""xpath"", ""/catalog/cd/title"")); - fields.add(createMap(""column"", ""artist"", ""xpath"", ""/catalog/cd/artist"")); - fields.add(createMap(""column"", ""year"", ""xpath"", ""/catalog/cd/year"")); - Context c = getContext(null, - new VariableResolverImpl(), getDataSource(cdData), Context.FULL_DUMP, fields, entityAttrs); - XPathEntityProcessor xPathEntityProcessor = new XPathEntityProcessor(); - xPathEntityProcessor.init(c); - List> result = new ArrayList>(); - while (true) { - Map row = xPathEntityProcessor.nextRow(); - if (row == null) - break; - result.add(row); - } - assertEquals(3, result.size()); - assertEquals(""Empire Burlesque"", result.get(0).get(""title"")); - assertEquals(""Bonnie Tyler"", result.get(1).get(""artist"")); - assertEquals(""1982"", result.get(2).get(""year"")); - } - - @Test -" -332,0," public void handle(Map record, String xpath); - } - -" -333,0," public int hashCode() { - final int prime = 31; - int result = super.hashCode(); - result = prime * result + ( ( getLocation().getMember() == null ) ? 0 : getLocation().getMember().hashCode() ); - return result; - } - - @Override -" -334,0," public int getTransportGuaranteeRedirectStatus() { - return transportGuaranteeRedirectStatus; - } - - - /** - * Set the HTTP status code used when the container needs to issue an HTTP - * redirect to meet the requirements of a configured transport guarantee. - * - * @param transportGuaranteeRedirectStatus The status to use. This value is - * not validated - */ -" -335,0," public void setFireRequestListenersOnForwards(boolean enable) { - fireRequestListenersOnForwards = enable; - } - - - @Override -" -336,0," public void cleanUp() { - if (multi != null) { - multi.cleanUp(); - } - } - -" -337,0," public final int getDegree() - { - return mDegree; - } - - /** - * Returns the fieldpolynomial as a new Bitstring. - * - * @return a copy of the fieldpolynomial as a new Bitstring - */ -" -338,0," public void setXWorkConverter(XWorkConverter conv) { - this.defaultConverter = new OgnlTypeConverterWrapper(conv); - } - - @Inject(XWorkConstants.DEV_MODE) -" -339,0," public void testJvmDecoder1() { - // This should trigger an error but currently passes. Once the JVM is - // fixed, s/false/true/ and s/20/13/ - doJvmDecoder(SRC_BYTES_1, false, 20); - } - - - @Test -" -340,0," protected void doStop() throws Exception { - super.doStop(); - // ensure client is closed when stopping - if (client != null && !client.isClosed()) { - client.close(); - } - client = null; - } - -" -341,0," public O transform(final Object input) { - if (input == null) { - return null; - } - try { - final Class cls = input.getClass(); - final Method method = cls.getMethod(iMethodName, iParamTypes); - return (O) method.invoke(input, iArgs); - } catch (final NoSuchMethodException ex) { - throw new FunctorException(""InvokerTransformer: The method '"" + iMethodName + ""' on '"" + - input.getClass() + ""' does not exist""); - } catch (final IllegalAccessException ex) { - throw new FunctorException(""InvokerTransformer: The method '"" + iMethodName + ""' on '"" + - input.getClass() + ""' cannot be accessed""); - } catch (final InvocationTargetException ex) { - throw new FunctorException(""InvokerTransformer: The method '"" + iMethodName + ""' on '"" + - input.getClass() + ""' threw an exception"", ex); - } - } - -" -342,0," public String getCompression() { - switch (compressionLevel) { - case 0: - return ""off""; - case 1: - return ""on""; - case 2: - return ""force""; - } - return ""off""; - } - - - /** - * Set compression level. - */ -" -343,0," public Reader getData(String query) { - return new StringReader(xml); - } - }; - } - -" -344,0," public String getInfo() { - - return (info); - - } - - -" -345,0," public void setMethods(Set methods) { - this.methods = new HashSet<>(); - for (String method : methods) { - this.methods.add(method.toUpperCase()); - } - } - - /** - * @param authenticationEntryPoint the authenticationEntryPoint to set - */ -" -346,0," public void run() { - synchronized (context) { - File file = context.targetFile; - if (file != null) { - file.delete(); - } - // Trigger the abort callback immediately to minimize latency between it and abort() being called. - JSONObject error = createFileTransferError(ABORTED_ERR, context.source, context.target, null, -1, null); - context.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, error)); - context.aborted = true; - if (context.connection != null) { - context.connection.disconnect(); - } - } - } - }); - } - } -} -" -347,0," public Iterator getGroups() { - - synchronized (groups) { - return (groups.iterator()); - } - - } - - - /** - * Return the set of {@link Role}s assigned specifically to this user. - */ - @Override -" -348,0," public static Encryptor getInstance() throws EncryptionException { - if ( singletonInstance == null ) { - synchronized ( JavaEncryptor.class ) { - if ( singletonInstance == null ) { - singletonInstance = new JavaEncryptor(); - } - } - } - return singletonInstance; - } - -" -349,0," private ApplicationContext getContext() { - return getSharedObject(ApplicationContext.class); - } - - /** - * Allows configuring OpenID based authentication. - * - *

Example Configurations

- * - * A basic example accepting the defaults and not using attribute exchange: - * - *
-	 * @Configuration
-	 * @EnableWebSecurity
-	 * public class OpenIDLoginConfig extends WebSecurityConfigurerAdapter {
-	 *
-	 * 	@Override
-	 * 	protected void configure(HttpSecurity http) {
-	 * 		http.authorizeRequests().antMatchers("/**").hasRole("USER").and().openidLogin()
-	 * 				.permitAll();
-	 * 	}
-	 *
-	 * 	@Override
-	 * 	protected void configure(AuthenticationManagerBuilder auth) throws Exception {
-	 * 		auth.inMemoryAuthentication()
-	 * 				// the username must match the OpenID of the user you are
-	 * 				// logging in with
-	 * 				.withUser(
-	 * 						"https://www.google.com/accounts/o8/id?id=lmkCn9xzPdsxVwG7pjYMuDgNNdASFmobNkcRPaWU")
-	 * 				.password("password").roles("USER");
-	 * 	}
-	 * }
-	 * 
- * - * A more advanced example demonstrating using attribute exchange and providing a - * custom AuthenticationUserDetailsService that will make any user that authenticates - * a valid user. - * - *
-	 * @Configuration
-	 * @EnableWebSecurity
-	 * public class OpenIDLoginConfig extends WebSecurityConfigurerAdapter {
-	 *
-	 * 	@Override
-	 * 	protected void configure(HttpSecurity http) {
-	 * 		http.authorizeRequests()
-	 * 				.antMatchers("/**")
-	 * 				.hasRole("USER")
-	 * 				.and()
-	 * 				.openidLogin()
-	 * 				.loginPage("/login")
-	 * 				.permitAll()
-	 * 				.authenticationUserDetailsService(
-	 * 						new AutoProvisioningUserDetailsService())
-	 * 				.attributeExchange("https://www.google.com/.*").attribute("email")
-	 * 				.type("http://axschema.org/contact/email").required(true).and()
-	 * 				.attribute("firstname").type("http://axschema.org/namePerson/first")
-	 * 				.required(true).and().attribute("lastname")
-	 * 				.type("http://axschema.org/namePerson/last").required(true).and().and()
-	 * 				.attributeExchange(".*yahoo.com.*").attribute("email")
-	 * 				.type("http://schema.openid.net/contact/email").required(true).and()
-	 * 				.attribute("fullname").type("http://axschema.org/namePerson")
-	 * 				.required(true).and().and().attributeExchange(".*myopenid.com.*")
-	 * 				.attribute("email").type("http://schema.openid.net/contact/email")
-	 * 				.required(true).and().attribute("fullname")
-	 * 				.type("http://schema.openid.net/namePerson").required(true);
-	 * 	}
-	 * }
-	 *
-	 * public class AutoProvisioningUserDetailsService implements
-	 * 		AuthenticationUserDetailsService<OpenIDAuthenticationToken> {
-	 * 	public UserDetails loadUserDetails(OpenIDAuthenticationToken token)
-	 * 			throws UsernameNotFoundException {
-	 * 		return new User(token.getName(), "NOTUSED",
-	 * 				AuthorityUtils.createAuthorityList("ROLE_USER"));
-	 * 	}
-	 * }
-	 * 
- * - * @return the {@link OpenIDLoginConfigurer} for further customizations. - * - * @throws Exception - * @see OpenIDLoginConfigurer - */ -" -350,0," public URL getConfigFile() { return configFile; } - @Override -" -351,0," void version(String version); - - @LogMessage(level = INFO) - @Message(id = 2, value = ""Ignoring XML configuration."") -" -352,0," public void copyToRepository(InputStream source, int size, Artifact destination, FileWriteMonitor monitor) throws IOException { - if(!destination.isResolved()) { - throw new IllegalArgumentException(""Artifact ""+destination+"" is not fully resolved""); - } - // is this a writable repository - if (!rootFile.canWrite()) { - throw new IllegalStateException(""This repository is not writable: "" + rootFile.getAbsolutePath() + "")""); - } - - // where are we going to install the file - File location = getLocation(destination); - - // assure that there isn't already a file installed at the specified location - if (location.exists()) { - throw new IllegalArgumentException(""Destination "" + location.getAbsolutePath() + "" already exists!""); - } - - ArtifactTypeHandler typeHandler = typeHandlers.get(destination.getType()); - if (typeHandler == null) typeHandler = DEFAULT_TYPE_HANDLER; - typeHandler.install(source, size, destination, monitor, location); - - if (destination.getType().equalsIgnoreCase(""car"")) { - log.debug(""Installed module configuration; id={}; location={}"", destination, location); - } - } -" -353,0," public void testRead7ZipMultiVolumeArchiveForFile() throws IOException { - final File file = getFile(""apache-maven-2.2.1.zip.001""); - ZipFile zf = new ZipFile(file); - zf.close(); - } -" -354,0," public boolean getMapperDirectoryRedirectEnabled(); -" -355,0," public void testFloatInHeader() { - Response response = WebClient.create(endPoint + TIKA_PATH) - .type(""application/pdf"") - .accept(""text/plain"") - .header(TikaResource.X_TIKA_PDF_HEADER_PREFIX + - ""averageCharTolerance"", - ""2.0"") - .put(ClassLoader.getSystemResourceAsStream(""testOCR.pdf"")); - assertEquals(200, response.getStatus()); - - } -" -356,0," private void testKeyGenerationAll() - throws Exception - { - testKeyGeneration(1024); - testKeyGeneration(2048); - testKeyGeneration(3072); - } - -" -357,0," public static String normalizeChildProjectValue(String actualValue){ - actualValue = actualValue.replaceAll(""(,[ ]*,)"", "", ""); - actualValue = actualValue.replaceAll(""(^,|,$)"", """"); - return actualValue.trim(); - } - -" -358,0," public void sendRequest(DiscoveryNode node, long requestId, String action, TransportRequest request, TransportRequestOptions options) throws IOException, TransportException { - if (recoveryActionToBlock.equals(action) || requestBlocked.getCount() == 0) { - logger.info(""--> preventing {} request"", action); - requestBlocked.countDown(); - if (dropRequests) { - return; - } - throw new ConnectTransportException(node, ""DISCONNECT: prevented "" + action + "" request""); - } - transport.sendRequest(node, requestId, action, request, options); - } - } -} -" -359,0," protected void stopInternal() throws LifecycleException { - - super.stopInternal(); - - // Close any open DB connection - close(this.dbConnection); - - } - - -" -360,0," public static String getPathWithinApplication(HttpServletRequest request) { - String contextPath = getContextPath(request); - String requestUri = getRequestUri(request); - if (StringUtils.startsWithIgnoreCase(requestUri, contextPath)) { - // Normal case: URI contains context path. - String path = requestUri.substring(contextPath.length()); - return (StringUtils.hasText(path) ? path : ""/""); - } else { - // Special case: rather unusual. - return requestUri; - } - } - - /** - * Return the request URI for the given request, detecting an include request - * URL if called within a RequestDispatcher include. - *

As the value returned by request.getRequestURI() is not - * decoded by the servlet container, this method will decode it. - *

The URI that the web container resolves should be correct, but some - * containers like JBoss/Jetty incorrectly include "";"" strings like "";jsessionid"" - * in the URI. This method cuts off such incorrect appendices. - * - * @param request current HTTP request - * @return the request URI - */ -" -361,0," public boolean getAllowCasualMultipartParsing(); - - - /** - * Set to true to allow requests mapped to servlets that - * do not explicitly declare @MultipartConfig or have - * <multipart-config> specified in web.xml to parse - * multipart/form-data requests. - * - * @param allowCasualMultipartParsing true to allow such - * casual parsing, false otherwise. - */ -" -362,0," public void setCharset(Charset charset) { - if( !byteC.isNull() ) { - // if the encoding changes we need to reset the conversion results - charC.recycle(); - hasStrValue=false; - } - byteC.setCharset(charset); - } - - /** - * Sets the content to be a char[] - * - * @param c the bytes - * @param off the start offset of the bytes - * @param len the length of the bytes - */ -" -363,0," public final GF2nElement convert(GF2nElement elem, GF2nField basis) - throws RuntimeException - { - if (basis == this) - { - return (GF2nElement)elem.clone(); - } - if (fieldPolynomial.equals(basis.fieldPolynomial)) - { - return (GF2nElement)elem.clone(); - } - if (mDegree != basis.mDegree) - { - throw new RuntimeException(""GF2nField.convert: B1 has a"" - + "" different degree and thus cannot be coverted to!""); - } - - int i; - GF2Polynomial[] COBMatrix; - i = fields.indexOf(basis); - if (i == -1) - { - computeCOBMatrix(basis); - i = fields.indexOf(basis); - } - COBMatrix = (GF2Polynomial[])matrices.elementAt(i); - - GF2nElement elemCopy = (GF2nElement)elem.clone(); - if (elemCopy instanceof GF2nONBElement) - { - // remember: ONB treats its bits in reverse order - ((GF2nONBElement)elemCopy).reverseOrder(); - } - GF2Polynomial bs = new GF2Polynomial(mDegree, elemCopy.toFlexiBigInt()); - bs.expandN(mDegree); - GF2Polynomial result = new GF2Polynomial(mDegree); - for (i = 0; i < mDegree; i++) - { - if (bs.vectorMult(COBMatrix[i])) - { - result.setBit(mDegree - 1 - i); - } - } - if (basis instanceof GF2nPolynomialField) - { - return new GF2nPolynomialElement((GF2nPolynomialField)basis, - result); - } - else if (basis instanceof GF2nONBField) - { - GF2nONBElement res = new GF2nONBElement((GF2nONBField)basis, - result.toFlexiBigInt()); - // TODO Remember: ONB treats its Bits in reverse order !!! - res.reverseOrder(); - return res; - } - else - { - throw new RuntimeException( - ""GF2nField.convert: B1 must be an instance of "" - + ""GF2nPolynomialField or GF2nONBField!""); - } - - } - -" -364,0," public CsrfConfigurer csrfTokenRepository( - CsrfTokenRepository csrfTokenRepository) { - Assert.notNull(csrfTokenRepository, ""csrfTokenRepository cannot be null""); - this.csrfTokenRepository = csrfTokenRepository; - return this; - } - - /** - * Specify the {@link RequestMatcher} to use for determining when CSRF should be - * applied. The default is to ignore GET, HEAD, TRACE, OPTIONS and process all other - * requests. - * - * @param requireCsrfProtectionMatcher the {@link RequestMatcher} to use - * @return the {@link CsrfConfigurer} for further customizations - */ -" -365,0," private BigInteger[] derDecode( - byte[] encoding) - throws IOException - { - ASN1Sequence s = (ASN1Sequence)ASN1Primitive.fromByteArray(encoding); - if (s.size() != 2) - { - throw new IOException(""malformed signature""); - } - if (!Arrays.areEqual(encoding, s.getEncoded(ASN1Encoding.DER))) - { - throw new IOException(""malformed signature""); - } - - return new BigInteger[]{ - ((ASN1Integer)s.getObjectAt(0)).getValue(), - ((ASN1Integer)s.getObjectAt(1)).getValue() - }; - } - -" -366,0," protected UserDetailsContextMapper getUserDetailsContextMapper() { - return userDetailsContextMapper; - } -" -367,0," public abstract void perform() throws IOException; -" -368,0," public long getFailureCount() { - return failureCounter.get(); - } - -" -369,0," public long getTimestamp() { - return timestamp; - } - } -} -" -370,0," public int getTransportGuaranteeRedirectStatus() { - return transportGuaranteeRedirectStatus; - } - - - /** - * Set the HTTP status code used when the container needs to issue an HTTP - * redirect to meet the requirements of a configured transport guarantee. - * - * @param transportGuaranteeRedirectStatus The status to use. This value is - * not validated - */ -" -371,0," public void setRedirectUri(String redirectUri) { - this.redirectUri = redirectUri; - } -" -372,0," public boolean isDoLoop() { - return iDoLoop; - } - -" -373,0," public void testCompatibilityWith_v1_0_12() throws IOException, ClassNotFoundException { - FileInputStream fis = new FileInputStream(SERIALIZATION_PREFIX + ""logger_v1.0.12.ser""); - ObjectInputStream ois = new ObjectInputStream(fis); - Logger a = (Logger) ois.readObject(); - ois.close(); - assertEquals(""a"", a.getName()); - } - -" -374,0," public Tomcat getTomcatInstance() { - return tomcat; - } - - /** - * Make the Tomcat instance preconfigured with test/webapp available to - * sub-classes. - * @param addJstl Should JSTL support be added to the test webapp - * @param start Should the Tomcat instance be started - * - * @return A Tomcat instance pre-configured with the web application located - * at test/webapp - * - * @throws LifecycleException If a problem occurs while starting the - * instance - */ -" -375,0," @CheckForNull public TimeZone getTimeZone() { - if (this.specTimezone == null) { - return null; - } - return TimeZone.getTimeZone(this.specTimezone); - } -" -376,0," public int getCacheSize() { - return cacheSize; - } - - - /** - * @param cacheSize The cacheSize to set. - */ -" -377,0," protected Log getLog() { - return log; - } - - - @Override -" -378,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); - } -" -379,0," public String getRmiBindAddress() { - return rmiBindAddress; - } - - /** - * Set the inet address on which the Platform RMI server is exported. - * @param theRmiBindAddress The textual representation of inet address - */ -" -380,0," public ClientLockoutPolicyRetriever setEnabled(boolean enabled) { - isEnabled = enabled; - return this; - } -" -381,0," private Page createPage() - { - if (pageCreator == null) - { - return null; - } - else - { - return pageCreator.createPage(); - } - } - - /** - * @see org.apache.wicket.Component#onBeforeRender() - */ - @Override -" -382,0," public Object getTarget() { - Jenkins.getInstance().checkPermission(Jenkins.ADMINISTER); - return this; - } - - @Override -" -383,0," public void testSpecifiedIndexUnavailable_multipleIndices() throws Exception { - createIndex(""test1""); - ensureYellow(); - - // Verify defaults - verify(search(""test1"", ""test2""), true); - verify(msearch(null, ""test1"", ""test2""), true); - verify(count(""test1"", ""test2""), true); - verify(clearCache(""test1"", ""test2""), true); - verify(_flush(""test1"", ""test2""),true); - verify(segments(""test1"", ""test2""), true); - verify(stats(""test1"", ""test2""), true); - verify(status(""test1"", ""test2""), true); - verify(optimize(""test1"", ""test2""), true); - verify(refresh(""test1"", ""test2""), true); - verify(validateQuery(""test1"", ""test2""), true); - verify(aliasExists(""test1"", ""test2""), true); - verify(typesExists(""test1"", ""test2""), true); - verify(deleteByQuery(""test1"", ""test2""), true); - verify(percolate(""test1"", ""test2""), true); - verify(mpercolate(null, ""test1"", ""test2""), false); - verify(suggest(""test1"", ""test2""), true); - verify(getAliases(""test1"", ""test2""), true); - verify(getFieldMapping(""test1"", ""test2""), true); - verify(getMapping(""test1"", ""test2""), true); - verify(getWarmer(""test1"", ""test2""), true); - verify(getSettings(""test1"", ""test2""), true); - - IndicesOptions options = IndicesOptions.strictExpandOpen(); - verify(search(""test1"", ""test2"").setIndicesOptions(options), true); - verify(msearch(options, ""test1"", ""test2""), true); - verify(count(""test1"", ""test2"").setIndicesOptions(options), true); - verify(clearCache(""test1"", ""test2"").setIndicesOptions(options), true); - verify(_flush(""test1"", ""test2"").setIndicesOptions(options),true); - verify(segments(""test1"", ""test2"").setIndicesOptions(options), true); - verify(stats(""test1"", ""test2"").setIndicesOptions(options), true); - verify(status(""test1"", ""test2"").setIndicesOptions(options), true); - verify(optimize(""test1"", ""test2"").setIndicesOptions(options), true); - verify(refresh(""test1"", ""test2"").setIndicesOptions(options), true); - verify(validateQuery(""test1"", ""test2"").setIndicesOptions(options), true); - verify(aliasExists(""test1"", ""test2"").setIndicesOptions(options), true); - verify(typesExists(""test1"", ""test2"").setIndicesOptions(options), true); - verify(deleteByQuery(""test1"", ""test2"").setIndicesOptions(options), true); - verify(percolate(""test1"", ""test2"").setIndicesOptions(options), true); - verify(mpercolate(options, ""test1"", ""test2"").setIndicesOptions(options), false); - verify(suggest(""test1"", ""test2"").setIndicesOptions(options), true); - verify(getAliases(""test1"", ""test2"").setIndicesOptions(options), true); - verify(getFieldMapping(""test1"", ""test2"").setIndicesOptions(options), true); - verify(getMapping(""test1"", ""test2"").setIndicesOptions(options), true); - verify(getWarmer(""test1"", ""test2"").setIndicesOptions(options), true); - verify(getSettings(""test1"", ""test2"").setIndicesOptions(options), true); - - options = IndicesOptions.lenientExpandOpen(); - verify(search(""test1"", ""test2"").setIndicesOptions(options), false); - verify(msearch(options, ""test1"", ""test2"").setIndicesOptions(options), false); - verify(count(""test1"", ""test2"").setIndicesOptions(options), false); - verify(clearCache(""test1"", ""test2"").setIndicesOptions(options), false); - verify(_flush(""test1"", ""test2"").setIndicesOptions(options), false); - verify(segments(""test1"", ""test2"").setIndicesOptions(options), false); - verify(stats(""test1"", ""test2"").setIndicesOptions(options), false); - verify(status(""test1"", ""test2"").setIndicesOptions(options), false); - verify(optimize(""test1"", ""test2"").setIndicesOptions(options), false); - verify(refresh(""test1"", ""test2"").setIndicesOptions(options), false); - verify(validateQuery(""test1"", ""test2"").setIndicesOptions(options), false); - verify(aliasExists(""test1"", ""test2"").setIndicesOptions(options), false); - verify(typesExists(""test1"", ""test2"").setIndicesOptions(options), false); - verify(deleteByQuery(""test1"", ""test2"").setIndicesOptions(options), false); - verify(percolate(""test1"", ""test2"").setIndicesOptions(options), false); - verify(mpercolate(options, ""test1"", ""test2"").setIndicesOptions(options), false); - verify(suggest(""test1"", ""test2"").setIndicesOptions(options), false); - verify(getAliases(""test1"", ""test2"").setIndicesOptions(options), false); - verify(getFieldMapping(""test1"", ""test2"").setIndicesOptions(options), false); - verify(getMapping(""test1"", ""test2"").setIndicesOptions(options), false); - verify(getWarmer(""test1"", ""test2"").setIndicesOptions(options), false); - verify(getSettings(""test1"", ""test2"").setIndicesOptions(options), false); - - options = IndicesOptions.strictExpandOpen(); - assertAcked(prepareCreate(""test2"")); - ensureYellow(); - verify(search(""test1"", ""test2"").setIndicesOptions(options), false); - verify(msearch(options, ""test1"", ""test2"").setIndicesOptions(options), false); - verify(count(""test1"", ""test2"").setIndicesOptions(options), false); - verify(clearCache(""test1"", ""test2"").setIndicesOptions(options), false); - verify(_flush(""test1"", ""test2"").setIndicesOptions(options),false); - verify(segments(""test1"", ""test2"").setIndicesOptions(options), false); - verify(stats(""test1"", ""test2"").setIndicesOptions(options), false); - verify(status(""test1"", ""test2"").setIndicesOptions(options), false); - verify(optimize(""test1"", ""test2"").setIndicesOptions(options), false); - verify(refresh(""test1"", ""test2"").setIndicesOptions(options), false); - verify(validateQuery(""test1"", ""test2"").setIndicesOptions(options), false); - verify(aliasExists(""test1"", ""test2"").setIndicesOptions(options), false); - verify(typesExists(""test1"", ""test2"").setIndicesOptions(options), false); - verify(deleteByQuery(""test1"", ""test2"").setIndicesOptions(options), false); - verify(percolate(""test1"", ""test2"").setIndicesOptions(options), false); - verify(mpercolate(options, ""test1"", ""test2"").setIndicesOptions(options), false); - verify(suggest(""test1"", ""test2"").setIndicesOptions(options), false); - verify(getAliases(""test1"", ""test2"").setIndicesOptions(options), false); - verify(getFieldMapping(""test1"", ""test2"").setIndicesOptions(options), false); - verify(getMapping(""test1"", ""test2"").setIndicesOptions(options), false); - verify(getWarmer(""test1"", ""test2"").setIndicesOptions(options), false); - verify(getSettings(""test1"", ""test2"").setIndicesOptions(options), false); - } - - @Test -" -384,0," public boolean isEraseCredentialsAfterAuthentication() { - return false; - } -" -385,0," public void copyToRepository(InputStream source, int size, Artifact destination, FileWriteMonitor monitor) throws IOException { - if(!destination.isResolved()) { - throw new IllegalArgumentException(""Artifact ""+destination+"" is not fully resolved""); - } - // is this a writable repository - if (!rootFile.canWrite()) { - throw new IllegalStateException(""This repository is not writable: "" + rootFile.getAbsolutePath() + "")""); - } - - // where are we going to install the file - File location = getLocation(destination); - - // assure that there isn't already a file installed at the specified location - if (location.exists()) { - throw new IllegalArgumentException(""Destination "" + location.getAbsolutePath() + "" already exists!""); - } - - ArtifactTypeHandler typeHandler = typeHandlers.get(destination.getType()); - if (typeHandler == null) typeHandler = DEFAULT_TYPE_HANDLER; - typeHandler.install(source, size, destination, monitor, location); - - if (destination.getType().equalsIgnoreCase(""car"")) { - log.debug(""Installed module configuration; id="" + destination + ""; location="" + location); - } - } -" -386,0," public void setAllowJavaSerializedObject(boolean allowJavaSerializedObject) { - // need to override and call super for component docs - super.setAllowJavaSerializedObject(allowJavaSerializedObject); - } -" -387,0," public void testChunkHeaderCRLF() throws Exception { - doTestChunkingCRLF(true, true, true, true, true, true); - } - - @Test -" -388,0," protected Log getLog() { - return log; - } - - // ----------------------------------------------------------- Constructors - - -" -389,0," void readRequest(HttpServletRequest request, HttpMessage message); - - /** - * Parses the body from a {@link org.apache.camel.http.common.HttpMessage} - * - * @param httpMessage the http message - * @return the parsed body returned as either a {@link java.io.InputStream} or a {@link java.io.Reader} - * depending on the {@link #setUseReaderForPayload(boolean)} property. - * @throws java.io.IOException can be thrown - */ -" -390,0," public void setUp() throws Exception { - provider = new ActiveDirectoryLdapAuthenticationProvider(""mydomain.eu"", ""ldap://192.168.1.200/""); - } - - @Test -" -391,0," public Collection getRequiredPermissions(String regionName) { - return Collections.singletonList(new ResourcePermission(ResourcePermission.Resource.DATA, - ResourcePermission.Operation.READ, regionName)); - } - -" -392,0," public void testConstructor1() - throws Exception - { - SimpleBindRequest bindRequest = new SimpleBindRequest(); - bindRequest = bindRequest.duplicate(); - - assertNotNull(bindRequest.getBindDN()); - assertEquals(bindRequest.getBindDN(), """"); - - assertNotNull(bindRequest.getPassword()); - assertEquals(bindRequest.getPassword().stringValue(), """"); - - assertNotNull(bindRequest.getControls()); - assertEquals(bindRequest.getControls().length, 0); - - assertEquals(bindRequest.getBindType(), ""SIMPLE""); - - SimpleBindRequest rebindRequest = - bindRequest.getRebindRequest(getTestHost(), getTestPort()); - assertNotNull(bindRequest.getRebindRequest(getTestHost(), - getTestPort())); - assertEquals(rebindRequest.getBindDN(), - bindRequest.getBindDN()); - assertEquals(rebindRequest.getPassword(), - bindRequest.getPassword()); - - assertEquals(bindRequest.getProtocolOpType(), - LDAPMessage.PROTOCOL_OP_TYPE_BIND_REQUEST); - - bindRequest.getLastMessageID(); - - assertNotNull(bindRequest.encodeProtocolOp()); - - assertNotNull(bindRequest.toString()); - - final ArrayList toCodeLines = new ArrayList(10); - bindRequest.toCode(toCodeLines, ""foo"", 0, false); - assertFalse(toCodeLines.isEmpty()); - - toCodeLines.clear(); - bindRequest.toCode(toCodeLines, ""bar"", 4, true); - assertFalse(toCodeLines.isEmpty()); - } - - - - /** - * Tests the second constructor, which takes a bind DN and password, using - * non-null, non-empty values. - * - * @throws Exception If an unexpected problem occurs. - */ - @Test() -" -393,0," public PackageConfig getPackageConfig(String name) { - return packageContexts.get(name); - } - -" -394,0," public String[] getRoles(Principal principal) { - if (principal instanceof GenericPrincipal) { - return ((GenericPrincipal) principal).getRoles(); - } - - String className = principal.getClass().getSimpleName(); - throw new IllegalStateException(sm.getString(""realmBase.cannotGetRoles"", className)); - } -" -395,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(); - } -" -396,0," public ParameterMetaData build() { - return new ParameterMetaData( - parameterIndex, - name, - parameterType, - adaptOriginsAndImplicitGroups( getConstraints() ), - isCascading(), - getGroupConversions(), - requiresUnwrapping() - ); - } - } -} -" -397,0," public String createDB(String dbName) { - - // ensure there are no illegal chars in DB name - InputUtils.validateSafeInput(dbName); - - String result = DB_CREATED_MSG + "": "" + dbName; - - Connection conn = null; - try { - conn = DerbyConnectionUtil.getDerbyConnection(dbName, - DerbyConnectionUtil.CREATE_DB_PROP); - } catch (Throwable e) { - if (e instanceof SQLException) { - result = getSQLError((SQLException) e); - } else { - result = e.getMessage(); - } - } finally { - // close DB connection - try { - if (conn != null) { - conn.close(); - } - } catch (SQLException e) { - result = ""Problem closing DB connection""; - } - } - - return result; - } - -" -398,0," protected void onUnsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) throws IOException { - super.onUnsuccessfulAuthentication(request, response, failed); - LOGGER.log(Level.INFO, ""Login attempt failed"", failed); - } - -" -399,0," public static File resolve(File[] roots, String path) { - for (File root : roots) { - File file = new File(path); - final File normalizedPath; - try { - if (file.isAbsolute()) { - normalizedPath = file.getCanonicalFile(); - } else { - normalizedPath = new File(root, path).getCanonicalFile(); - } - } catch (IOException ex) { - continue; - } - if(normalizedPath.getAbsolutePath().startsWith(root.getAbsolutePath())) { - return normalizedPath; - } - } - return null; - } - - -" -400,0," public Collection getRequiredPermissions(String regionName) { - return Collections.singletonList(ResourcePermissions.CLUSTER_MANAGE); - } - -" -401,0," private static ErrorPage findErrorPage - (Context context, Throwable exception) { - - if (exception == null) { - return (null); - } - Class clazz = exception.getClass(); - String name = clazz.getName(); - while (!Object.class.equals(clazz)) { - ErrorPage errorPage = context.findErrorPage(name); - if (errorPage != null) { - return (errorPage); - } - clazz = clazz.getSuperclass(); - if (clazz == null) { - break; - } - name = clazz.getName(); - } - return (null); - - } -" -402,0," protected void setUp() throws Exception { - super.setUp(); - req = new MockHttpServletRequest(); - req.setupGetParameterMap(new HashMap()); - req.setupGetContextPath(""/my/namespace""); - - config = new DefaultConfiguration(); - PackageConfig pkg = new PackageConfig.Builder(""myns"") - .namespace(""/my/namespace"").build(); - PackageConfig pkg2 = new PackageConfig.Builder(""my"").namespace(""/my"").build(); - config.addPackageConfig(""mvns"", pkg); - config.addPackageConfig(""my"", pkg2); - configManager = new ConfigurationManager() { - public Configuration getConfiguration() { - return config; - } - }; - } - -" -403,0," public String getName() { - // Should we return the ID for the principal name? (No, because the - // UaaUserDatabase retrieves users by name.) - return principal.getName(); - } - - @Override -" -404,0," public static IdStrategy idStrategy() { - Jenkins j = Jenkins.getInstance(); - SecurityRealm realm = j.getSecurityRealm(); - if (realm == null) { - return IdStrategy.CASE_INSENSITIVE; - } - return realm.getUserIdStrategy(); - } - -" -405,0," private static void verify(ActionRequestBuilder requestBuilder, boolean fail, long expectedCount) { - if (fail) { - if (requestBuilder instanceof MultiSearchRequestBuilder) { - MultiSearchResponse multiSearchResponse = ((MultiSearchRequestBuilder) requestBuilder).get(); - assertThat(multiSearchResponse.getResponses().length, equalTo(1)); - assertThat(multiSearchResponse.getResponses()[0].getResponse(), nullValue()); - } else { - try { - requestBuilder.get(); - fail(""IndexMissingException or IndexClosedException was expected""); - } catch (IndexMissingException | IndexClosedException e) {} - } - } else { - if (requestBuilder instanceof SearchRequestBuilder) { - SearchRequestBuilder searchRequestBuilder = (SearchRequestBuilder) requestBuilder; - assertHitCount(searchRequestBuilder.get(), expectedCount); - } else if (requestBuilder instanceof CountRequestBuilder) { - CountRequestBuilder countRequestBuilder = (CountRequestBuilder) requestBuilder; - assertHitCount(countRequestBuilder.get(), expectedCount); - } else if (requestBuilder instanceof MultiSearchRequestBuilder) { - MultiSearchResponse multiSearchResponse = ((MultiSearchRequestBuilder) requestBuilder).get(); - assertThat(multiSearchResponse.getResponses().length, equalTo(1)); - assertThat(multiSearchResponse.getResponses()[0].getResponse(), notNullValue()); - } else { - requestBuilder.get(); - } - } - } - -" -406,0," public void setUp() throws Exception { - TestClient testClient = new TestClient(getMockMvc()); - adminToken = testClient.getClientCredentialsOAuthAccessToken(""admin"", ""adminsecret"", - ""clients.read clients.write clients.secret scim.write""); - String clientId = generator.generate().toLowerCase(); - String clientSecret = generator.generate().toLowerCase(); - - BaseClientDetails clientDetails = new BaseClientDetails(clientId, null, null, ""client_credentials"", ""password.write""); - clientDetails.setClientSecret(clientSecret); - - utils().createClient(getMockMvc(), adminToken, clientDetails); - - passwordWriteToken = testClient.getClientCredentialsOAuthAccessToken(clientId, clientSecret,""password.write""); - } - - @Test -" -407,0," public Iterator getGroups() { - - synchronized (groups) { - return (groups.values().iterator()); - } - - } - - - /** - * Return the unique global identifier of this user database. - */ - @Override -" -408,0," public boolean refersDirectlyTo(PyObject ob) { - if (ob == null || co_consts == null) { - return false; - } else { - for (PyObject obj: co_consts) { - if (obj == ob) { - return true; - } - } - return false; - } - } -" -409,0," public Charset getCharset() { - if (charset == null) { - charset = DEFAULT_CHARSET; - } - return charset; - } - - /** - * Returns the message bytes. - */ -" -410,0," public String getDisplayName() { - return Messages.UpstreamComitterRecipientProvider_DisplayName(); - } - } -} -" -411,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(); - } - - - -" -412,0," public final void parse(Set mappingStreams) { - try { - // JAXBContext#newInstance() requires several permissions internally and doesn't use any privileged blocks - // itself; Wrapping it here avoids that all calling code bases need to have these permissions as well - JAXBContext jc = run( NewJaxbContext.action( ConstraintMappingsType.class ) ); - - Set alreadyProcessedConstraintDefinitions = newHashSet(); - for ( InputStream in : mappingStreams ) { - String schemaVersion = xmlParserHelper.getSchemaVersion( ""constraint mapping file"", in ); - String schemaResourceName = getSchemaResourceName( schemaVersion ); - Schema schema = xmlParserHelper.getSchema( schemaResourceName ); - - Unmarshaller unmarshaller = jc.createUnmarshaller(); - unmarshaller.setSchema( schema ); - - ConstraintMappingsType mapping = getValidationConfig( in, unmarshaller ); - String defaultPackage = mapping.getDefaultPackage(); - - parseConstraintDefinitions( - mapping.getConstraintDefinition(), - defaultPackage, - alreadyProcessedConstraintDefinitions - ); - - for ( BeanType bean : mapping.getBean() ) { - Class beanClass = ClassLoadingHelper.loadClass( bean.getClazz(), defaultPackage ); - checkClassHasNotBeenProcessed( processedClasses, beanClass ); - - // update annotation ignores - annotationProcessingOptions.ignoreAnnotationConstraintForClass( - beanClass, - bean.getIgnoreAnnotations() - ); - - ConstrainedType constrainedType = ConstrainedTypeBuilder.buildConstrainedType( - bean.getClassType(), - beanClass, - defaultPackage, - constraintHelper, - annotationProcessingOptions, - defaultSequences - ); - if ( constrainedType != null ) { - addConstrainedElement( beanClass, constrainedType ); - } - - Set constrainedFields = ConstrainedFieldBuilder.buildConstrainedFields( - bean.getField(), - beanClass, - defaultPackage, - constraintHelper, - annotationProcessingOptions - ); - addConstrainedElements( beanClass, constrainedFields ); - - Set constrainedGetters = ConstrainedGetterBuilder.buildConstrainedGetters( - bean.getGetter(), - beanClass, - defaultPackage, - constraintHelper, - annotationProcessingOptions - ); - addConstrainedElements( beanClass, constrainedGetters ); - - Set constrainedConstructors = ConstrainedExecutableBuilder.buildConstructorConstrainedExecutable( - bean.getConstructor(), - beanClass, - defaultPackage, - parameterNameProvider, - constraintHelper, - annotationProcessingOptions - ); - addConstrainedElements( beanClass, constrainedConstructors ); - - Set constrainedMethods = ConstrainedExecutableBuilder.buildMethodConstrainedExecutable( - bean.getMethod(), - beanClass, - defaultPackage, - parameterNameProvider, - constraintHelper, - annotationProcessingOptions - ); - addConstrainedElements( beanClass, constrainedMethods ); - - processedClasses.add( beanClass ); - } - } - } - catch ( JAXBException e ) { - throw log.getErrorParsingMappingFileException( e ); - } - } - -" -413,0," static ASN1Enumerated fromOctetString(byte[] enc) - { - if (enc.length > 1) - { - return new ASN1Enumerated(enc); - } - - if (enc.length == 0) - { - throw new IllegalArgumentException(""ENUMERATED has zero length""); - } - int value = enc[0] & 0xff; - - if (value >= cache.length) - { - return new ASN1Enumerated(Arrays.clone(enc)); - } - - ASN1Enumerated possibleMatch = cache[value]; - - if (possibleMatch == null) - { - possibleMatch = cache[value] = new ASN1Enumerated(Arrays.clone(enc)); - } - - return possibleMatch; - } -" -414,0," public void addRecipients(final ExtendedEmailPublisherContext context, EnvVars env, Set to, Set cc, Set 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(); - Set users = RecipientProviderUtilities.getChangeSetAuthors(Collections.>singleton(context.getRun()), debug); - RecipientProviderUtilities.addUsers(users, context, env, to, cc, bcc, debug); - } - - @Extension -" -415,0," protected void handleParams(ActionMapping mapping, StringBuilder uri) { - String name = mapping.getName(); - String params = """"; - if (name.indexOf('?') != -1) { - params = name.substring(name.indexOf('?')); - } - if (params.length() > 0) { - uri.append(params); - } - } - -" -416,0," public static void copyRecursively(final Path source, final Path target, boolean overwrite) throws IOException { - final CopyOption[] options; - if (overwrite) { - options = new CopyOption[]{StandardCopyOption.COPY_ATTRIBUTES, StandardCopyOption.REPLACE_EXISTING}; - } else { - options = new CopyOption[]{StandardCopyOption.COPY_ATTRIBUTES}; - } - Files.walkFileTree(source, new FileVisitor() { - @Override - public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { - Files.copy(dir, target.resolve(source.relativize(dir)), options); - return FileVisitResult.CONTINUE; - } - - @Override - public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { - Files.copy(file, target.resolve(source.relativize(file)), options); - return FileVisitResult.CONTINUE; - } - - @Override - public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException { - DeploymentRepositoryLogger.ROOT_LOGGER.cannotCopyFile(exc, file); - return FileVisitResult.CONTINUE; - } - - @Override - public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { - return FileVisitResult.CONTINUE; - } - }); - } - - /** - * Delete a path recursively, not throwing Exception if it fails or if the path is null. - * @param path a Path pointing to a file or a directory that may not exists anymore. - */ -" -417,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 - */ -" -418,0," public static Factory prototypeFactory(final T prototype) { - if (prototype == null) { - return ConstantFactory.constantFactory(null); - } - try { - final Method method = prototype.getClass().getMethod(""clone"", (Class[]) null); - return new PrototypeCloneFactory(prototype, method); - - } catch (final NoSuchMethodException ex) { - try { - prototype.getClass().getConstructor(new Class[] { prototype.getClass() }); - return new InstantiateFactory( - (Class) prototype.getClass(), - new Class[] { prototype.getClass() }, - new Object[] { prototype }); - } catch (final NoSuchMethodException ex2) { - if (prototype instanceof Serializable) { - return (Factory) new PrototypeSerializationFactory((Serializable) prototype); - } - } - } - throw new IllegalArgumentException(""The prototype must be cloneable via a public clone method""); - } - - /** - * Restricted constructor. - */ -" -419,0," public void sec2500PreventAnonymousBind() { - provider.authenticate(new UsernamePasswordAuthenticationToken(""rwinch"", """")); - } - - @SuppressWarnings(""unchecked"") - @Test(expected = IncorrectResultSizeDataAccessException.class) -" -420,0," protected void checkConfig() throws IOException { - // Create an unbound server socket - ServerSocket socket = - JdkCompat.getJdkCompat().getUnboundSocket(sslProxy); - if (socket == null) { - // Can create unbound sockets (1.3 JVM) - can't test the connection - return; - } - initServerSocket(socket); - - try { - // Set the timeout to 1ms as all we care about is if it throws an - // SSLException on accept. - socket.setSoTimeout(1); - - socket.accept(); - // Will never get here - no client can connect to an unbound port - } catch (SSLException ssle) { - // SSL configuration is invalid. Possibly cert doesn't match ciphers - IOException ioe = new IOException(sm.getString( - ""jsse.invalid_ssl_conf"", ssle.getMessage())); - JdkCompat.getJdkCompat().chainException(ioe, ssle); - throw ioe; - } catch (Exception e) { - /* - * Possible ways of getting here - * socket.accept() throws a SecurityException - * socket.setSoTimeout() throws a SocketException - * socket.accept() throws some other exception (after a JDK change) - * In these cases the test won't work so carry on - essentially - * the behaviour before this patch - * socket.accept() throws a SocketTimeoutException - * In this case all is well so carry on - */ - } finally { - // Should be open here but just in case - try { - socket.close(); - } catch (IOException ioe) { - // Ignore - } - } - - } -" -421,0," private static boolean startsWithStringArray(String sArray[], String value) { - if (value == null) { - return false; - } - for (int i = 0; i < sArray.length; i++) { - if (value.startsWith(sArray[i])) { - return true; - } - } - return false; - } - - - /** - * Check if the resource could be compressed, if the client supports it. - */ -" -422,0," protected String getProtocolName() { - return ""Http""; - } - - - // ------------------------------------------------ HTTP specific properties - // ------------------------------------------ managed in the ProtocolHandler - -" -423,0," public String toString() { - return ""parameter:'"" + parameterName + ""'""; - } - } - -} -" -424,0," public long getAvailable(); - - - /** - * Set the available date/time for this servlet, in milliseconds since the - * epoch. If this date/time is in the future, any request for this servlet - * will return an SC_SERVICE_UNAVAILABLE error. A value equal to - * Long.MAX_VALUE is considered to mean that unavailability is permanent. - * - * @param available The new available date/time - */ -" -425,0," protected abstract Log getLog(); -" -426,0," private static ManagedMap parseInterceptUrlsForFilterInvocationRequestMap( - MatcherType matcherType, List urlElts, boolean useExpressions, - boolean addAuthenticatedAll, ParserContext parserContext) { - - ManagedMap filterInvocationDefinitionMap = new ManagedMap(); - - for (Element urlElt : urlElts) { - String access = urlElt.getAttribute(ATT_ACCESS); - if (!StringUtils.hasText(access)) { - continue; - } - - String path = urlElt.getAttribute(ATT_PATTERN); - - if (!StringUtils.hasText(path)) { - parserContext.getReaderContext().error( - ""path attribute cannot be empty or null"", urlElt); - } - - String method = urlElt.getAttribute(ATT_HTTP_METHOD); - if (!StringUtils.hasText(method)) { - method = null; - } - - BeanDefinition matcher = matcherType.createMatcher(parserContext, path, - method); - BeanDefinitionBuilder attributeBuilder = BeanDefinitionBuilder - .rootBeanDefinition(SecurityConfig.class); - - if (useExpressions) { - logger.info(""Creating access control expression attribute '"" + access - + ""' for "" + path); - // The single expression will be parsed later by the - // ExpressionFilterInvocationSecurityMetadataSource - attributeBuilder.addConstructorArgValue(new String[] { access }); - attributeBuilder.setFactoryMethod(""createList""); - - } - else { - attributeBuilder.addConstructorArgValue(access); - attributeBuilder.setFactoryMethod(""createListFromCommaDelimitedString""); - } - - if (filterInvocationDefinitionMap.containsKey(matcher)) { - logger.warn(""Duplicate URL defined: "" + path - + "". The original attribute values will be overwritten""); - } - - filterInvocationDefinitionMap.put(matcher, - attributeBuilder.getBeanDefinition()); - } - - if (addAuthenticatedAll && filterInvocationDefinitionMap.isEmpty()) { - - BeanDefinition matcher = matcherType.createMatcher(parserContext, ""/**"", - null); - BeanDefinitionBuilder attributeBuilder = BeanDefinitionBuilder - .rootBeanDefinition(SecurityConfig.class); - attributeBuilder.addConstructorArgValue(new String[] { ""authenticated"" }); - attributeBuilder.setFactoryMethod(""createList""); - filterInvocationDefinitionMap.put(matcher, - attributeBuilder.getBeanDefinition()); - } - - return filterInvocationDefinitionMap; - } - -" -427,0," public DeserializerFactory withConfig(DeserializerFactoryConfig config) - { - if (_factoryConfig == config) { - return this; - } - /* 22-Nov-2010, tatu: Handling of subtypes is tricky if we do immutable-with-copy-ctor; - * and we pretty much have to here either choose between losing subtype instance - * when registering additional deserializers, or losing deserializers. - * Instead, let's actually just throw an error if this method is called when subtype - * has not properly overridden this method; this to indicate problem as soon as possible. - */ - if (getClass() != BeanDeserializerFactory.class) { - throw new IllegalStateException(""Subtype of BeanDeserializerFactory (""+getClass().getName() - +"") has not properly overridden method 'withAdditionalDeserializers': can not instantiate subtype with "" - +""additional deserializer definitions""); - } - return new BeanDeserializerFactory(config); - } - - /* - /********************************************************** - /* DeserializerFactory API implementation - /********************************************************** - */ - - /** - * Method that {@link DeserializerCache}s call to create a new - * deserializer for types other than Collections, Maps, arrays and - * enums. - */ - @Override -" -428,0," public void setApplicationContext(ApplicationContext applicationContext) - throws BeansException { - this.defaultWebSecurityExpressionHandler - .setApplicationContext(applicationContext); - this.ignoredRequestRegistry = new IgnoredRequestConfigurer(applicationContext); - } -" -429,0," private SessionCreationPolicy createPolicy(String createSession) { - if (""ifRequired"".equals(createSession)) { - return SessionCreationPolicy.IF_REQUIRED; - } - else if (""always"".equals(createSession)) { - return SessionCreationPolicy.ALWAYS; - } - else if (""never"".equals(createSession)) { - return SessionCreationPolicy.NEVER; - } - else if (""stateless"".equals(createSession)) { - return SessionCreationPolicy.STATELESS; - } - - throw new IllegalStateException(""Cannot convert "" + createSession + "" to "" - + SessionCreationPolicy.class.getName()); - } - - @SuppressWarnings(""rawtypes"") -" -430,1," public PlainText decrypt(SecretKey key, CipherText ciphertext) - throws EncryptionException, IllegalArgumentException - { - long start = System.nanoTime(); // Current time in nanosecs; used to prevent timing attacks - if ( key == null ) { - throw new IllegalArgumentException(""SecretKey arg may not be null""); - } - if ( ciphertext == null ) { - throw new IllegalArgumentException(""Ciphertext may arg not be null""); - } - - if ( ! CryptoHelper.isAllowedCipherMode(ciphertext.getCipherMode()) ) { - // This really should be an illegal argument exception, but it could - // mean that a partner encrypted something using a cipher mode that - // you do not accept, so it's a bit more complex than that. Also - // throwing an IllegalArgumentException doesn't allow us to provide - // the two separate error messages or automatically log it. - throw new EncryptionException(DECRYPTION_FAILED, - ""Invalid cipher mode "" + ciphertext.getCipherMode() + - "" not permitted for decryption or encryption operations.""); - } - logger.debug(Logger.EVENT_SUCCESS, - ""Args valid for JavaEncryptor.decrypt(SecretKey,CipherText): "" + - ciphertext); - - PlainText plaintext = null; - boolean caughtException = false; - int progressMark = 0; - try { - // First we validate the MAC. - boolean valid = CryptoHelper.isCipherTextMACvalid(key, ciphertext); - if ( !valid ) { - try { - // This is going to fail, but we want the same processing - // to occur as much as possible so as to prevent timing - // attacks. We _could_ just be satisfied by the additional - // sleep in the 'finally' clause, but an attacker on the - // same server who can run something like 'ps' can tell - // CPU time versus when the process is sleeping. Hence we - // try to make this as close as possible. Since we know - // it is going to fail, we ignore the result and ignore - // the (expected) exception. - handleDecryption(key, ciphertext); // Ignore return (should fail). - } catch(Exception ex) { - ; // Ignore - } - throw new EncryptionException(DECRYPTION_FAILED, - ""Decryption failed because MAC invalid for "" + - ciphertext); - } - progressMark++; - // The decryption only counts if the MAC was valid. - plaintext = handleDecryption(key, ciphertext); - progressMark++; - } catch(EncryptionException ex) { - caughtException = true; - String logMsg = null; - switch( progressMark ) { - case 1: - logMsg = ""Decryption failed because MAC invalid. See logged exception for details.""; - break; - case 2: - logMsg = ""Decryption failed because handleDecryption() failed. See logged exception for details.""; - break; - default: - logMsg = ""Programming error: unexpected progress mark == "" + progressMark; - break; - } - logger.error(Logger.SECURITY_FAILURE, logMsg); - throw ex; // Re-throw - } - finally { - if ( caughtException ) { - // The rest of this code is to try to account for any minute differences - // in the time it might take for the various reasons that decryption fails - // in order to prevent any other possible timing attacks. Perhaps it is - // going overboard. If nothing else, if N_SECS is large enough, it might - // deter attempted repeated attacks by making them take much longer. - long now = System.nanoTime(); - long elapsed = now - start; - final long NANOSECS_IN_SEC = 1000000000L; // nanosec is 10**-9 sec - long nSecs = N_SECS * NANOSECS_IN_SEC; // N seconds in nano seconds - if ( elapsed < nSecs ) { - // Want to sleep so total time taken is N seconds. - long extraSleep = nSecs - elapsed; - - // 'extraSleep' is in nanoseconds. Need to convert to a millisec - // part and nanosec part. Nanosec is 10**-9, millsec is - // 10**-3, so divide by (10**-9 / 10**-3), or 10**6 to - // convert to from nanoseconds to milliseconds. - long millis = extraSleep / 1000000L; - long nanos = (extraSleep - (millis * 1000000L)); - assert nanos >= 0 && nanos <= Integer.MAX_VALUE : - ""Nanosecs out of bounds; nanos = "" + nanos; - try { - Thread.sleep(millis, (int)nanos); - } catch(InterruptedException ex) { - ; // Ignore - } - } // Else ... time already exceeds N_SECS sec, so do not sleep. - } - } - return plaintext; - } - - // Handle the actual decryption portion. At this point it is assumed that - // any MAC has already been validated. (But see ""DISCUSS"" issue, below.) -" -431,1," public List getAclForPath(String path) { - List acls = zkACLProvider.getACLsToAdd(path); - return acls; - } - }; - } - -" -432,1," protected Object readResolve() - throws ObjectStreamException { - AbstractBrokerFactory factory = getPooledFactoryForKey(_poolKey); - if (factory != null) - return factory; - - // reset these transient fields to empty values - _transactional = new ConcurrentHashMap(); - _brokers = newBrokerSet(); - - makeReadOnly(); - return this; - } - -" -433,1," public void testRepositoryCreation() throws Exception { - Client client = client(); - - File location = newTempDir(LifecycleScope.SUITE); - - logger.info(""--> creating repository""); - PutRepositoryResponse putRepositoryResponse = client.admin().cluster().preparePutRepository(""test-repo-1"") - .setType(""fs"").setSettings(ImmutableSettings.settingsBuilder() - .put(""location"", location) - ).get(); - assertThat(putRepositoryResponse.isAcknowledged(), equalTo(true)); - - logger.info(""--> verify the repository""); - int numberOfFiles = location.listFiles().length; - VerifyRepositoryResponse verifyRepositoryResponse = client.admin().cluster().prepareVerifyRepository(""test-repo-1"").get(); - assertThat(verifyRepositoryResponse.getNodes().length, equalTo(cluster().numDataAndMasterNodes())); - - logger.info(""--> verify that we didn't leave any files as a result of verification""); - assertThat(location.listFiles().length, equalTo(numberOfFiles)); - - logger.info(""--> check that repository is really there""); - ClusterStateResponse clusterStateResponse = client.admin().cluster().prepareState().clear().setMetaData(true).get(); - MetaData metaData = clusterStateResponse.getState().getMetaData(); - RepositoriesMetaData repositoriesMetaData = metaData.custom(RepositoriesMetaData.TYPE); - assertThat(repositoriesMetaData, notNullValue()); - assertThat(repositoriesMetaData.repository(""test-repo-1""), notNullValue()); - assertThat(repositoriesMetaData.repository(""test-repo-1"").type(), equalTo(""fs"")); - - logger.info(""--> creating another repository""); - putRepositoryResponse = client.admin().cluster().preparePutRepository(""test-repo-2"") - .setType(""fs"").setSettings(ImmutableSettings.settingsBuilder() - .put(""location"", newTempDir(LifecycleScope.SUITE)) - ).get(); - assertThat(putRepositoryResponse.isAcknowledged(), equalTo(true)); - - logger.info(""--> check that both repositories are in cluster state""); - clusterStateResponse = client.admin().cluster().prepareState().clear().setMetaData(true).get(); - metaData = clusterStateResponse.getState().getMetaData(); - repositoriesMetaData = metaData.custom(RepositoriesMetaData.TYPE); - assertThat(repositoriesMetaData, notNullValue()); - assertThat(repositoriesMetaData.repositories().size(), equalTo(2)); - assertThat(repositoriesMetaData.repository(""test-repo-1""), notNullValue()); - assertThat(repositoriesMetaData.repository(""test-repo-1"").type(), equalTo(""fs"")); - assertThat(repositoriesMetaData.repository(""test-repo-2""), notNullValue()); - assertThat(repositoriesMetaData.repository(""test-repo-2"").type(), equalTo(""fs"")); - - logger.info(""--> check that both repositories can be retrieved by getRepositories query""); - GetRepositoriesResponse repositoriesResponse = client.admin().cluster().prepareGetRepositories().get(); - assertThat(repositoriesResponse.repositories().size(), equalTo(2)); - assertThat(findRepository(repositoriesResponse.repositories(), ""test-repo-1""), notNullValue()); - assertThat(findRepository(repositoriesResponse.repositories(), ""test-repo-2""), notNullValue()); - - logger.info(""--> delete repository test-repo-1""); - client.admin().cluster().prepareDeleteRepository(""test-repo-1"").get(); - repositoriesResponse = client.admin().cluster().prepareGetRepositories().get(); - assertThat(repositoriesResponse.repositories().size(), equalTo(1)); - assertThat(findRepository(repositoriesResponse.repositories(), ""test-repo-2""), notNullValue()); - - logger.info(""--> delete repository test-repo-2""); - client.admin().cluster().prepareDeleteRepository(""test-repo-2"").get(); - repositoriesResponse = client.admin().cluster().prepareGetRepositories().get(); - assertThat(repositoriesResponse.repositories().size(), equalTo(0)); - } - -" -434,1," protected void parseParameters() { - - parametersParsed = true; - - Parameters parameters = coyoteRequest.getParameters(); - - // getCharacterEncoding() may have been overridden to search for - // hidden form field containing request encoding - String enc = getCharacterEncoding(); - - boolean useBodyEncodingForURI = connector.getUseBodyEncodingForURI(); - if (enc != null) { - parameters.setEncoding(enc); - if (useBodyEncodingForURI) { - parameters.setQueryStringEncoding(enc); - } - } else { - parameters.setEncoding - (org.apache.coyote.Constants.DEFAULT_CHARACTER_ENCODING); - if (useBodyEncodingForURI) { - parameters.setQueryStringEncoding - (org.apache.coyote.Constants.DEFAULT_CHARACTER_ENCODING); - } - } - - parameters.handleQueryParameters(); - - if (usingInputStream || usingReader) - return; - - if (!getMethod().equalsIgnoreCase(""POST"")) - return; - - String contentType = getContentType(); - if (contentType == null) - contentType = """"; - int semicolon = contentType.indexOf(';'); - if (semicolon >= 0) { - contentType = contentType.substring(0, semicolon).trim(); - } else { - contentType = contentType.trim(); - } - if (!(""application/x-www-form-urlencoded"".equals(contentType))) - return; - - int len = getContentLength(); - - if (len > 0) { - int maxPostSize = connector.getMaxPostSize(); - if ((maxPostSize > 0) && (len > maxPostSize)) { - context.getLogger().info - (sm.getString(""coyoteRequest.postTooLarge"")); - throw new IllegalStateException(""Post too large""); - } - try { - byte[] formData = null; - if (len < CACHED_POST_LEN) { - if (postData == null) - postData = new byte[CACHED_POST_LEN]; - formData = postData; - } else { - formData = new byte[len]; - } - int actualLen = readPostBody(formData, len); - if (actualLen == len) { - parameters.processParameters(formData, 0, len); - } - } catch (Throwable t) { - context.getLogger().warn - (sm.getString(""coyoteRequest.parseParameters""), t); - } - } else if (""chunked"".equalsIgnoreCase( - coyoteRequest.getHeader(""transfer-encoding""))) { - byte[] formData = null; - try { - formData = readChunkedPostBody(); - } catch (IOException e) { - // Client disconnect - if (context.getLogger().isDebugEnabled()) { - context.getLogger().debug( - sm.getString(""coyoteRequest.parseParameters""), e); - } - return; - } - if (formData != null) { - parameters.processParameters(formData, 0, formData.length); - } - } - - } - - - /** - * Read post body in an array. - */ -" -435,1," public void unzipping_stream_extracts_subset_of_files() throws IOException { - InputStream zip = urlToZip().openStream(); - File toDir = temp.newFolder(); - - ZipUtils.unzip(zip, toDir, (ZipUtils.ZipEntryFilter)ze -> ze.getName().equals(""foo.txt"")); - assertThat(toDir.listFiles()).containsOnly(new File(toDir, ""foo.txt"")); - } - -" -436,1," protected boolean addInputFilter(InputFilter[] inputFilters, - String encodingName) { - if (encodingName.equals(""identity"")) { - // Skip - } else if (encodingName.equals(""chunked"")) { - inputBuffer.addActiveFilter - (inputFilters[Constants.CHUNKED_FILTER]); - contentDelimitation = true; - } else { - for (int i = 2; i < inputFilters.length; i++) { - if (inputFilters[i].getEncodingName() - .toString().equals(encodingName)) { - inputBuffer.addActiveFilter(inputFilters[i]); - return true; - } - } - return false; - } - return true; - } - - - /** - * Specialized utility method: find a sequence of lower case bytes inside - * a ByteChunk. - */ -" -437,1," public KeystoreInstance createKeystore(String name, char[] password, String keystoreType) throws KeystoreException { - File test = new File(directory, name); - if(test.exists()) { - throw new IllegalArgumentException(""Keystore already exists ""+test.getAbsolutePath()+""!""); - } - try { - KeyStore keystore = KeyStore.getInstance(keystoreType); - keystore.load(null, password); - OutputStream out = new BufferedOutputStream(new FileOutputStream(test)); - keystore.store(out, password); - out.flush(); - out.close(); - return getKeystore(name, keystoreType); - } catch (KeyStoreException e) { - throw new KeystoreException(""Unable to create keystore"", e); - } catch (IOException e) { - throw new KeystoreException(""Unable to create keystore"", e); - } catch (NoSuchAlgorithmException e) { - throw new KeystoreException(""Unable to create keystore"", e); - } catch (CertificateException e) { - throw new KeystoreException(""Unable to create keystore"", e); - } - } - -" -438,1," private ControllerInfo parseCInfoString(String cInfoString) { - Annotations annotation; - - String[] config = cInfoString.split("",""); - if (config.length == 2) { - String[] pair = config[1].split(""=""); - - if (pair.length == 2) { - annotation = DefaultAnnotations.builder() - .set(pair[0], pair[1]).build(); - } else { - print(""Wrong format {}"", config[1]); - return null; - } - - String[] data = config[0].split("":""); - String type = data[0]; - IpAddress ip = IpAddress.valueOf(data[1]); - int port = Integer.parseInt(data[2]); - - return new ControllerInfo(ip, port, type, annotation); - } else { - print(config[0]); - return new ControllerInfo(config[0]); - } - } -" -439,1," public void filterWithParameter() throws IOException, ServletException { - MockHttpServletRequest request = new MockHttpServletRequest(""POST"", ""/hotels""); - request.addParameter(""_method"", ""delete""); - MockHttpServletResponse response = new MockHttpServletResponse(); - - FilterChain filterChain = new FilterChain() { - - @Override - public void doFilter(ServletRequest filterRequest, - ServletResponse filterResponse) throws IOException, ServletException { - assertEquals(""Invalid method"", ""DELETE"", - ((HttpServletRequest) filterRequest).getMethod()); - } - }; - filter.doFilter(request, response, filterChain); - } - - @Test -" -440,1," public Authentication authenticate(Authentication authentication) throws AuthenticationException { - Assert.isInstanceOf(UsernamePasswordAuthenticationToken.class, authentication, - messages.getMessage(""LdapAuthenticationProvider.onlySupports"", - ""Only UsernamePasswordAuthenticationToken is supported"")); - - final UsernamePasswordAuthenticationToken userToken = (UsernamePasswordAuthenticationToken)authentication; - - String username = userToken.getName(); - String password = (String) authentication.getCredentials(); - - if (logger.isDebugEnabled()) { - logger.debug(""Processing authentication request for user: "" + username); - } - - if (!StringUtils.hasLength(username)) { - throw new BadCredentialsException(messages.getMessage(""LdapAuthenticationProvider.emptyUsername"", - ""Empty Username"")); - } - - Assert.notNull(password, ""Null password was supplied in authentication token""); - - DirContextOperations userData = doAuthentication(userToken); - - UserDetails user = userDetailsContextMapper.mapUserFromContext(userData, authentication.getName(), - loadUserAuthorities(userData, authentication.getName(), (String)authentication.getCredentials())); - - return createSuccessfulAuthentication(userToken, user); - } - -" -441,1," public CsrfConfigurer ignoringAntMatchers(String... antPatterns) { - return new IgnoreCsrfProtectionRegistry().antMatchers(antPatterns).and(); - } - - @SuppressWarnings(""unchecked"") - @Override -" -442,1," 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 headers = redirectionResponse.getHeaders(); - if (!headers.isEmpty()) { - for (Entry entry : headers.entrySet()) { - hresponse.addHeader(entry.getKey(), entry.getValue()); - } - } - - } 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); - - } - -" -443,1," public void testWithVariantRequestOnly() throws Exception { - params.put(I18nInterceptor.DEFAULT_REQUESTONLY_PARAMETER, ""fr_CA_xx""); - interceptor.intercept(mai); - - assertNull(params.get(I18nInterceptor.DEFAULT_PARAMETER)); // should have been removed - assertNull(session.get(I18nInterceptor.DEFAULT_SESSION_ATTRIBUTE)); - - Locale variant = new Locale(""fr"", ""CA"", ""xx""); - Locale locale = mai.getInvocationContext().getLocale(); - assertNotNull(locale); // should be stored here - assertEquals(variant, locale); - assertEquals(""xx"", locale.getVariant()); - } - - @Test -" -444,1," private T run(PrivilegedAction action) { - return System.getSecurityManager() != null ? AccessController.doPrivileged( action ) : action.run(); - } -" -445,1," public void execute(FunctionContext context) { - ResultSender resultSender = context.getResultSender(); - - Cache cache = context.getCache(); - String memberNameOrId = context.getMemberName(); - - RegionFunctionArgs regionCreateArgs = (RegionFunctionArgs) context.getArguments(); - - if (regionCreateArgs.isSkipIfExists()) { - Region region = cache.getRegion(regionCreateArgs.getRegionPath()); - if (region != null) { - resultSender.lastResult(new CliFunctionResult(memberNameOrId, true, - CliStrings.format( - CliStrings.CREATE_REGION__MSG__SKIPPING_0_REGION_PATH_1_ALREADY_EXISTS, - memberNameOrId, regionCreateArgs.getRegionPath()))); - return; - } - } - - try { - Region createdRegion = createRegion(cache, regionCreateArgs); - XmlEntity xmlEntity = new XmlEntity(CacheXml.REGION, ""name"", createdRegion.getName()); - resultSender.lastResult(new CliFunctionResult(memberNameOrId, xmlEntity, - CliStrings.format(CliStrings.CREATE_REGION__MSG__REGION_0_CREATED_ON_1, - createdRegion.getFullPath(), memberNameOrId))); - } catch (IllegalStateException e) { - String exceptionMsg = e.getMessage(); - String localizedString = - LocalizedStrings.DiskStore_IS_USED_IN_NONPERSISTENT_REGION.toLocalizedString(); - if (localizedString.equals(e.getMessage())) { - exceptionMsg = exceptionMsg + "" "" - + CliStrings.format(CliStrings.CREATE_REGION__MSG__USE_ONE_OF_THESE_SHORTCUTS_0, - new Object[] {String.valueOf(RegionCommandsUtils.PERSISTENT_OVERFLOW_SHORTCUTS)}); - } - resultSender.lastResult(handleException(memberNameOrId, exceptionMsg, null/* do not log */)); - } catch (IllegalArgumentException e) { - resultSender.lastResult(handleException(memberNameOrId, e.getMessage(), e)); - } catch (RegionExistsException e) { - String exceptionMsg = - CliStrings.format(CliStrings.CREATE_REGION__MSG__REGION_PATH_0_ALREADY_EXISTS_ON_1, - regionCreateArgs.getRegionPath(), memberNameOrId); - resultSender.lastResult(handleException(memberNameOrId, exceptionMsg, e)); - } catch (Exception e) { - String exceptionMsg = e.getMessage(); - if (exceptionMsg == null) { - exceptionMsg = CliUtil.stackTraceAsString(e); - } - resultSender.lastResult(handleException(memberNameOrId, exceptionMsg, e)); - } - } - -" -446,1," public static Document signMetaInfo(Crypto crypto, String keyAlias, String keyPassword, - InputStream metaInfo, 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 transformList = new ArrayList(); - 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 x509Content = new ArrayList(); - x509Content.add(cert.getSubjectX500Principal().getName()); - x509Content.add(cert); - X509Data xd = kif.newX509Data(x509Content); - KeyInfo ki = kif.newKeyInfo(Collections.singletonList(xd)); - - // step3 - // Instantiate the document to be signed. - Document doc = DOC_BUILDER_FACTORY.newDocumentBuilder().parse(metaInfo); - - // 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; - } - -" -447,1," public void testCorruptFileThenSnapshotAndRestore() throws ExecutionException, InterruptedException, IOException { - int numDocs = scaledRandomIntBetween(100, 1000); - internalCluster().ensureAtLeastNumDataNodes(2); - - assertAcked(prepareCreate(""test"").setSettings(ImmutableSettings.builder() - .put(IndexMetaData.SETTING_NUMBER_OF_REPLICAS, ""0"") // no replicas for this test - .put(MergePolicyModule.MERGE_POLICY_TYPE_KEY, NoMergePolicyProvider.class) - .put(MockFSDirectoryService.CHECK_INDEX_ON_CLOSE, false) // no checkindex - we corrupt shards on purpose - .put(EngineConfig.INDEX_FAIL_ON_CORRUPTION_SETTING, true) - .put(TranslogService.INDEX_TRANSLOG_DISABLE_FLUSH, true) // no translog based flush - it might change the .liv / segments.N files - .put(""indices.recovery.concurrent_streams"", 10) - )); - ensureGreen(); - IndexRequestBuilder[] builders = new IndexRequestBuilder[numDocs]; - for (int i = 0; i < builders.length; i++) { - builders[i] = client().prepareIndex(""test"", ""type"").setSource(""field"", ""value""); - } - indexRandom(true, builders); - ensureGreen(); - assertAllSuccessful(client().admin().indices().prepareFlush().setForce(true).setWaitIfOngoing(true).execute().actionGet()); - // we have to flush at least once here since we don't corrupt the translog - CountResponse countResponse = client().prepareCount().get(); - assertHitCount(countResponse, numDocs); - - ShardRouting shardRouting = corruptRandomPrimaryFile(false); - // we don't corrupt segments.gen since S/R doesn't snapshot this file - // the other problem here why we can't corrupt segments.X files is that the snapshot flushes again before - // it snapshots and that will write a new segments.X+1 file - logger.info(""--> creating repository""); - assertAcked(client().admin().cluster().preparePutRepository(""test-repo"") - .setType(""fs"").setSettings(ImmutableSettings.settingsBuilder() - .put(""location"", newTempDir(LifecycleScope.SUITE).getAbsolutePath()) - .put(""compress"", randomBoolean()) - .put(""chunk_size"", randomIntBetween(100, 1000)))); - logger.info(""--> snapshot""); - CreateSnapshotResponse createSnapshotResponse = client().admin().cluster().prepareCreateSnapshot(""test-repo"", ""test-snap"").setWaitForCompletion(true).setIndices(""test"").get(); - assertThat(createSnapshotResponse.getSnapshotInfo().state(), equalTo(SnapshotState.PARTIAL)); - logger.info(""failed during snapshot -- maybe SI file got corrupted""); - final List files = listShardFiles(shardRouting); - File corruptedFile = null; - for (File file : files) { - if (file.getName().startsWith(""corrupted_"")) { - corruptedFile = file; - break; - } - } - assertThat(corruptedFile, notNullValue()); - } - - /** - * This test verifies that if we corrupt a replica, we can still get to green, even though - * listing its store fails. Note, we need to make sure that replicas are allocated on all data - * nodes, so that replica won't be sneaky and allocated on a node that doesn't have a corrupted - * replica. - */ - @Test -" -448,1," public void parse(InputStream stream, ContentHandler ignore, - Metadata metadata, ParseContext context) throws IOException, - SAXException, TikaException { - //Test to see if we should avoid parsing - if (parserState.recursiveParserWrapperHandler.hasHitMaximumEmbeddedResources()) { - return; - } - // Work out what this thing is - String objectName = getResourceName(metadata, parserState); - String objectLocation = this.location + objectName; - - metadata.add(AbstractRecursiveParserWrapperHandler.EMBEDDED_RESOURCE_PATH, objectLocation); - - - //get a fresh handler - ContentHandler localHandler = parserState.recursiveParserWrapperHandler.getNewContentHandler(); - parserState.recursiveParserWrapperHandler.startEmbeddedDocument(localHandler, metadata); - - Parser preContextParser = context.get(Parser.class); - context.set(Parser.class, new EmbeddedParserDecorator(getWrappedParser(), objectLocation, parserState)); - long started = System.currentTimeMillis(); - try { - super.parse(stream, localHandler, metadata, context); - } catch (SAXException e) { - boolean wlr = isWriteLimitReached(e); - if (wlr == true) { - metadata.add(WRITE_LIMIT_REACHED, ""true""); - } else { - if (catchEmbeddedExceptions) { - ParserUtils.recordParserFailure(this, e, metadata); - } else { - throw e; - } - } - } catch (TikaException e) { - if (catchEmbeddedExceptions) { - ParserUtils.recordParserFailure(this, e, metadata); - } else { - throw e; - } - } finally { - context.set(Parser.class, preContextParser); - long elapsedMillis = System.currentTimeMillis() - started; - metadata.set(RecursiveParserWrapperHandler.PARSE_TIME_MILLIS, Long.toString(elapsedMillis)); - parserState.recursiveParserWrapperHandler.endEmbeddedDocument(localHandler, metadata); - } - } - } - - /** - * This tracks the state of the parse of a single document. - * In future versions, this will allow the RecursiveParserWrapper to be thread safe. - */ - private class ParserState { - private int unknownCount = 0; - private final AbstractRecursiveParserWrapperHandler recursiveParserWrapperHandler; - private ParserState(AbstractRecursiveParserWrapperHandler handler) { - this.recursiveParserWrapperHandler = handler; - } - - - } -} -" -449,1," private boolean breakKeepAliveLoop(SocketWrapperBase socketWrapper) { - openSocket = keepAlive; - // Do sendfile as needed: add socket to sendfile and end - if (sendfileData != null && !getErrorState().isError()) { - sendfileData.keepAlive = keepAlive; - switch (socketWrapper.processSendfile(sendfileData)) { - case DONE: - // If sendfile is complete, no need to break keep-alive loop - sendfileData = null; - return false; - case PENDING: - return true; - case ERROR: - // Write failed - if (log.isDebugEnabled()) { - log.debug(sm.getString(""http11processor.sendfile.error"")); - } - setErrorState(ErrorState.CLOSE_CONNECTION_NOW, null); - return true; - } - } - return false; - } - - - @Override -" -450,1," public void execute(FunctionContext context) { - RegionFunctionContext rfc = (RegionFunctionContext) context; - Set keys = (Set) 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); - } - -" -451,1," private static void unzip(final ZipFile zip, final Path targetDir) throws IOException { - final Enumeration entries = zip.entries(); - while (entries.hasMoreElements()) { - final ZipEntry entry = entries.nextElement(); - final String name = entry.getName(); - final Path current = targetDir.resolve(name); - if (entry.isDirectory()) { - if (!Files.exists(current)) { - Files.createDirectories(current); - } - } else { - if (Files.notExists(current.getParent())) { - Files.createDirectories(current.getParent()); - } - try (final InputStream eis = zip.getInputStream(entry)) { - Files.copy(eis, current); - } - } - try { - Files.getFileAttributeView(current, BasicFileAttributeView.class).setTimes(entry.getLastModifiedTime(), entry.getLastAccessTime(), entry.getCreationTime()); - } catch (IOException e) { - //ignore, if we cannot set it, world will not end - } - } - } - -" -452,1," private void updateGraphFromRequest(ActionRequest actionRequest, Graph graph) { - graph.setGraphName1(actionRequest.getParameter(""name"")); - graph.setDescription(actionRequest.getParameter(""description"")); - graph.setXlabel(actionRequest.getParameter(""xlabel"")); - graph.setYlabel(actionRequest.getParameter(""ylabel"")); - graph.setTimeFrame(Integer.parseInt(actionRequest.getParameter(""timeframe""))); - graph.setMBeanName(actionRequest.getParameter(""mbean"")); - graph.setDataName1(actionRequest.getParameter(""dataname1"")); - graph.setData1operation(actionRequest.getParameter(""data1operation"").charAt(0)); - - graph.setOperation(actionRequest.getParameter(""operation"")); - if (graph.getOperation().equals(""other"")) { - graph.setOperation(actionRequest.getParameter(""othermath"")); - } - - graph.setShowArchive(actionRequest.getParameter(""showArchive"") != null - && actionRequest.getParameter(""showArchive"").equals(""on"")); - - graph.setDataName2(actionRequest.getParameter(""dataname2"")); - graph.setData2operation(actionRequest.getParameter(""data2operation"") == null? 'A': actionRequest.getParameter(""data2operation"").charAt(0)); - } - -" -453,1," 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(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 filterChain = new ManagedList( - filterBeanNames.length); - - for (String name : filterBeanNames) { - filterChain.add(new RuntimeBeanReference(name)); - } - - builder.addConstructorArgValue(filterChain); - } - - return builder.getBeanDefinition(); - } -" -454,1," protected Principal authenticate(Connection dbConnection, - String username, - String credentials) { - // No user or no credentials - // Can't possibly authenticate, don't bother the database then - if (username == null || credentials == null) { - if (containerLog.isTraceEnabled()) - containerLog.trace(sm.getString(""dataSourceRealm.authenticateFailure"", - username)); - return null; - } - - // Look up the user's credentials - String dbCredentials = getPassword(dbConnection, username); - - if(dbCredentials == null) { - // User was not found in the database. - - if (containerLog.isTraceEnabled()) - containerLog.trace(sm.getString(""dataSourceRealm.authenticateFailure"", - username)); - return null; - } - - // Validate the user's credentials - boolean validated = getCredentialHandler().matches(credentials, dbCredentials); - - if (validated) { - if (containerLog.isTraceEnabled()) - containerLog.trace(sm.getString(""dataSourceRealm.authenticateSuccess"", - username)); - } else { - if (containerLog.isTraceEnabled()) - containerLog.trace(sm.getString(""dataSourceRealm.authenticateFailure"", - username)); - return null; - } - - ArrayList list = getRoles(dbConnection, username); - - // Create and return a suitable Principal for this user - return new GenericPrincipal(username, credentials, list); - } - - - /** - * Close the specified database connection. - * - * @param dbConnection The connection to be closed - */ -" -455,1," public BeanDefinitionHolder decorate(Node node, BeanDefinitionHolder holder, - ParserContext parserContext) { - BeanDefinition filterChainProxy = holder.getBeanDefinition(); - - ManagedList securityFilterChains = new ManagedList(); - Element elt = (Element) node; - - MatcherType matcherType = MatcherType.fromElement(elt); - - List filterChainElts = DomUtils.getChildElementsByTagName(elt, - Elements.FILTER_CHAIN); - - for (Element chain : filterChainElts) { - String path = chain - .getAttribute(HttpSecurityBeanDefinitionParser.ATT_PATH_PATTERN); - String filters = chain - .getAttribute(HttpSecurityBeanDefinitionParser.ATT_FILTERS); - - if (!StringUtils.hasText(path)) { - parserContext.getReaderContext().error( - ""The attribute '"" - + HttpSecurityBeanDefinitionParser.ATT_PATH_PATTERN - + ""' must not be empty"", elt); - } - - if (!StringUtils.hasText(filters)) { - parserContext.getReaderContext().error( - ""The attribute '"" + HttpSecurityBeanDefinitionParser.ATT_FILTERS - + ""'must not be empty"", elt); - } - - BeanDefinition matcher = matcherType.createMatcher(path, null); - - if (filters.equals(HttpSecurityBeanDefinitionParser.OPT_FILTERS_NONE)) { - securityFilterChains.add(createSecurityFilterChain(matcher, - new ManagedList(0))); - } - else { - String[] filterBeanNames = StringUtils - .tokenizeToStringArray(filters, "",""); - ManagedList filterChain = new ManagedList(filterBeanNames.length); - - for (String name : filterBeanNames) { - filterChain.add(new RuntimeBeanReference(name)); - } - - securityFilterChains.add(createSecurityFilterChain(matcher, filterChain)); - } - } - - filterChainProxy.getConstructorArgumentValues().addGenericArgumentValue( - securityFilterChains); - - return holder; - } - -" -456,1," public XObject execute(XPathContext xctxt) throws javax.xml.transform.TransformerException - { - - String fullName = m_arg0.execute(xctxt).str(); - int indexOfNSSep = fullName.indexOf(':'); - String result; - String propName = """"; - - // List of properties where the name of the - // property argument is to be looked for. - Properties xsltInfo = new Properties(); - - loadPropertyFile(XSLT_PROPERTIES, xsltInfo); - - if (indexOfNSSep > 0) - { - String prefix = (indexOfNSSep >= 0) - ? fullName.substring(0, indexOfNSSep) : """"; - String namespace; - - namespace = xctxt.getNamespaceContext().getNamespaceForPrefix(prefix); - propName = (indexOfNSSep < 0) - ? fullName : fullName.substring(indexOfNSSep + 1); - - if (namespace.startsWith(""http://www.w3.org/XSL/Transform"") - || namespace.equals(""http://www.w3.org/1999/XSL/Transform"")) - { - result = xsltInfo.getProperty(propName); - - if (null == result) - { - warn(xctxt, XPATHErrorResources.WG_PROPERTY_NOT_SUPPORTED, - new Object[]{ fullName }); //""XSL Property not supported: ""+fullName); - - return XString.EMPTYSTRING; - } - } - else - { - warn(xctxt, XPATHErrorResources.WG_DONT_DO_ANYTHING_WITH_NS, - new Object[]{ namespace, - fullName }); //""Don't currently do anything with namespace ""+namespace+"" in property: ""+fullName); - - try - { - result = System.getProperty(propName); - - if (null == result) - { - - // result = System.getenv(propName); - return XString.EMPTYSTRING; - } - } - catch (SecurityException se) - { - warn(xctxt, XPATHErrorResources.WG_SECURITY_EXCEPTION, - new Object[]{ fullName }); //""SecurityException when trying to access XSL system property: ""+fullName); - - return XString.EMPTYSTRING; - } - } - } - else - { - try - { - result = System.getProperty(fullName); - - if (null == result) - { - - // result = System.getenv(fullName); - return XString.EMPTYSTRING; - } - } - catch (SecurityException se) - { - warn(xctxt, XPATHErrorResources.WG_SECURITY_EXCEPTION, - new Object[]{ fullName }); //""SecurityException when trying to access XSL system property: ""+fullName); - - return XString.EMPTYSTRING; - } - } - - if (propName.equals(""version"") && result.length() > 0) - { - try - { - // Needs to return the version number of the spec we conform to. - return new XString(""1.0""); - } - catch (Exception ex) - { - return new XString(result); - } - } - else - return new XString(result); - } - - /** - * Retrieve a propery bundle from a specified file - * - * @param file The string name of the property file. The name - * should already be fully qualified as path/filename - * @param target The target property bag the file will be placed into. - */ -" -457,1," private T run(PrivilegedAction action) { - return System.getSecurityManager() != null ? AccessController.doPrivileged( action ) : action.run(); - } -" -458,1," protected Locale getLocaleFromParam(Object requestedLocale) { - Locale locale = null; - if (requestedLocale != null) { - locale = (requestedLocale instanceof Locale) ? - (Locale) requestedLocale : - LocalizedTextUtil.localeFromString(requestedLocale.toString(), null); - if (locale != null) { - LOG.debug(""Applied request locale: {}"", locale); - } - } - return locale; - } - - /** - * Reads the locale from the session, and if not found from the - * current invocation (=browser) - * - * @param invocation the current invocation - * @param session the current session - * @return the read locale - */ -" -459,1," public static HierarchicalConfiguration loadXml(InputStream xmlStream) { - XMLConfiguration cfg = new XMLConfiguration(); - try { - cfg.load(xmlStream); - return cfg; - } catch (ConfigurationException e) { - throw new IllegalArgumentException(""Cannot load xml from Stream"", e); - } - } - -" -460,1," private void multiByteReadConsistentlyReturnsMinusOneAtEof(File file) throws Exception { - byte[] buf = new byte[2]; - try (FileInputStream in = new FileInputStream(getFile(""bla.zip"")); - ZipArchiveInputStream archive = new ZipArchiveInputStream(in)) { - ArchiveEntry e = archive.getNextEntry(); - IOUtils.toByteArray(archive); - assertEquals(-1, archive.read(buf)); - assertEquals(-1, archive.read(buf)); - } - } - -" -461,1," 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()); - } - - // 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) -" -462,1," void setByteChunk( ByteChunk mb ) { - initialized = (mb!=null); - bc = mb; - } - -" -463,1," public void testUpdate() throws Exception - { - String xml = - """" + - "" "" + - "" "" + - "" "" + - "" "" + - "" "" + - "" "" + - "" "" + - """"; - - Map args = new HashMap(); - args.put(CommonParams.TR, ""xsl-update-handler-test.xsl""); - - SolrCore core = h.getCore(); - LocalSolrQueryRequest req = new LocalSolrQueryRequest( core, new MapSolrParams( args) ); - ArrayList streams = new ArrayList(); - streams.add(new ContentStreamBase.StringStream(xml)); - req.setContentStreams(streams); - SolrQueryResponse rsp = new SolrQueryResponse(); - UpdateRequestHandler handler = new UpdateRequestHandler(); - handler.init(new NamedList()); - handler.handleRequestBody(req, rsp); - StringWriter sw = new StringWriter(32000); - QueryResponseWriter responseWriter = core.getQueryResponseWriter(req); - responseWriter.write(sw,req,rsp); - req.close(); - String response = sw.toString(); - assertU(response); - assertU(commit()); - - assertQ(""test document was correctly committed"", req(""q"",""*:*"") - , ""//result[@numFound='1']"" - , ""//int[@name='id'][.='12345']"" - ); - } -" -464,1," protected Container createBootstrapContainer(List providers) { - ContainerBuilder builder = new ContainerBuilder(); - boolean fmFactoryRegistered = false; - for (ContainerProvider provider : providers) { - if (provider instanceof FileManagerProvider) { - provider.register(builder, null); - } - if (provider instanceof FileManagerFactoryProvider) { - provider.register(builder, null); - fmFactoryRegistered = true; - } - } - builder.factory(ObjectFactory.class, Scope.SINGLETON); - builder.factory(FileManager.class, ""system"", DefaultFileManager.class, Scope.SINGLETON); - if (!fmFactoryRegistered) { - builder.factory(FileManagerFactory.class, DefaultFileManagerFactory.class, Scope.SINGLETON); - } - builder.factory(ReflectionProvider.class, OgnlReflectionProvider.class, Scope.SINGLETON); - builder.factory(ValueStackFactory.class, OgnlValueStackFactory.class, Scope.SINGLETON); - - builder.factory(XWorkConverter.class, Scope.SINGLETON); - builder.factory(ConversionPropertiesProcessor.class, DefaultConversionPropertiesProcessor.class, Scope.SINGLETON); - builder.factory(ConversionFileProcessor.class, DefaultConversionFileProcessor.class, Scope.SINGLETON); - builder.factory(ConversionAnnotationProcessor.class, DefaultConversionAnnotationProcessor.class, Scope.SINGLETON); - builder.factory(TypeConverterCreator.class, DefaultTypeConverterCreator.class, Scope.SINGLETON); - builder.factory(TypeConverterHolder.class, DefaultTypeConverterHolder.class, Scope.SINGLETON); - - builder.factory(XWorkBasicConverter.class, Scope.SINGLETON); - builder.factory(TypeConverter.class, XWorkConstants.COLLECTION_CONVERTER, CollectionConverter.class, Scope.SINGLETON); - builder.factory(TypeConverter.class, XWorkConstants.ARRAY_CONVERTER, ArrayConverter.class, Scope.SINGLETON); - builder.factory(TypeConverter.class, XWorkConstants.DATE_CONVERTER, DateConverter.class, Scope.SINGLETON); - builder.factory(TypeConverter.class, XWorkConstants.NUMBER_CONVERTER, NumberConverter.class, Scope.SINGLETON); - builder.factory(TypeConverter.class, XWorkConstants.STRING_CONVERTER, StringConverter.class, Scope.SINGLETON); - builder.factory(TextProvider.class, ""system"", DefaultTextProvider.class, Scope.SINGLETON); - builder.factory(ObjectTypeDeterminer.class, DefaultObjectTypeDeterminer.class, Scope.SINGLETON); - builder.factory(PropertyAccessor.class, CompoundRoot.class.getName(), CompoundRootAccessor.class, Scope.SINGLETON); - builder.factory(OgnlUtil.class, Scope.SINGLETON); - builder.constant(XWorkConstants.DEV_MODE, ""false""); - builder.constant(XWorkConstants.LOG_MISSING_PROPERTIES, ""false""); - builder.constant(XWorkConstants.RELOAD_XML_CONFIGURATION, ""false""); - return builder.create(true); - } - - /** - * This builds the internal runtime configuration used by Xwork for finding and configuring Actions from the - * programmatic configuration data structures. All of the old runtime configuration will be discarded and rebuilt. - * - *

- * It basically flattens the data structures to make the information easier to access. It will take - * an {@link ActionConfig} and combine its data with all inherited dast. For example, if the {@link ActionConfig} - * is in a package that contains a global result and it also contains a result, the resulting {@link ActionConfig} - * will have two results. - */ -" -465,1," protected void initOther() throws ServletException { - PropertyUtils.addBeanIntrospector( - SuppressPropertiesBeanIntrospector.SUPPRESS_CLASS); - PropertyUtils.clearDescriptors(); - - String value = null; - value = getServletConfig().getInitParameter(""config""); - if (value != null) { - config = value; - } - - // Backwards compatibility for form beans of Java wrapper classes - // Set to true for strict Struts 1.0 compatibility - value = getServletConfig().getInitParameter(""convertNull""); - if (""true"".equalsIgnoreCase(value) - || ""yes"".equalsIgnoreCase(value) - || ""on"".equalsIgnoreCase(value) - || ""y"".equalsIgnoreCase(value) - || ""1"".equalsIgnoreCase(value)) { - - convertNull = true; - } - - if (convertNull) { - ConvertUtils.deregister(); - ConvertUtils.register(new BigDecimalConverter(null), BigDecimal.class); - ConvertUtils.register(new BigIntegerConverter(null), BigInteger.class); - ConvertUtils.register(new BooleanConverter(null), Boolean.class); - ConvertUtils.register(new ByteConverter(null), Byte.class); - ConvertUtils.register(new CharacterConverter(null), Character.class); - ConvertUtils.register(new DoubleConverter(null), Double.class); - ConvertUtils.register(new FloatConverter(null), Float.class); - ConvertUtils.register(new IntegerConverter(null), Integer.class); - ConvertUtils.register(new LongConverter(null), Long.class); - ConvertUtils.register(new ShortConverter(null), Short.class); - } - - } - - - /** - *

Initialize the servlet mapping under which our controller servlet - * is being accessed. This will be used in the &html:form> - * tag to generate correct destination URLs for form submissions.

- * - * @throws ServletException if error happens while scanning web.xml - */ -" -466,1," private void parseUsingSAX(InputStream is) throws IOException, ParserConfigurationException, SAXException, SAXNotRecognizedException, SAXNotSupportedException - { - // Invoke the SAX XML parser on the input. - SAXParserFactory spf = SAXParserFactory.newInstance(); - - // Disable external entity resolving - spf.setFeature(""http://xml.org/sax/features/external-general-entities"", false); - spf.setFeature(""http://xml.org/sax/features/external-parameter-entities"", false); - - SAXParser sp = spf.newSAXParser(); - XMLReader xr = sp.getXMLReader(); - - SAXHandler handler = new SAXHandler(); - xr.setContentHandler(handler); - xr.setProperty(""http://xml.org/sax/properties/lexical-handler"", handler); - - xr.parse(new InputSource(is)); - } - - -" -467,1," private ManagedMap parseInterceptUrlsForChannelSecurity() { - - ManagedMap channelRequestMap = new ManagedMap(); - - for (Element urlElt : interceptUrls) { - String path = urlElt.getAttribute(ATT_PATH_PATTERN); - String method = urlElt.getAttribute(ATT_HTTP_METHOD); - - if (!StringUtils.hasText(path)) { - pc.getReaderContext().error(""pattern attribute cannot be empty or null"", - urlElt); - } - - String requiredChannel = urlElt.getAttribute(ATT_REQUIRES_CHANNEL); - - if (StringUtils.hasText(requiredChannel)) { - BeanDefinition matcher = matcherType.createMatcher(path, method); - - RootBeanDefinition channelAttributes = new RootBeanDefinition( - ChannelAttributeFactory.class); - channelAttributes.getConstructorArgumentValues().addGenericArgumentValue( - requiredChannel); - channelAttributes.setFactoryMethodName(""createChannelAttributes""); - - channelRequestMap.put(matcher, channelAttributes); - } - } - - return channelRequestMap; - } - -" -468,1," public void doConfigSubmit(StaplerRequest req, StaplerResponse rsp) throws ServletException, - IOException, - InterruptedException { - if (logger.isDebugEnabled()) { - logger.debug(""submit {}"", req.toString()); - } - JSONObject form = req.getSubmittedForm(); - PluginConfig pluginConfig = PluginImpl.getPluginConfig_(); - if (pluginConfig != null) { - pluginConfig.setValues(form); - PluginImpl.save_(); - GerritSendCommandQueue.configure(pluginConfig); - } - //TODO reconfigure the incoming worker threads as well - - rsp.sendRedirect("".""); - } - -" -469,1," 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 result = SignatureUtils.signMetaInfo( - config.getSigningKey().getCrypto(), config.getSigningKey().getKeyAlias(), config.getSigningKey().getKeyPassword(), is, 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()); - } - - } - -" -470,1," public void testMavenTriggerEvenWhenUnstable() throws Exception { - doMavenTriggerTest(true); - } -" -471,1," boolean isTransferException(); - - /** - * 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. - *

- * The default range is 200-299 - */ -" -472,1," public Object instantiate(Class type, Configuration conf, boolean fatal) { - Object obj = newInstance(_name, type, conf, fatal); - Configurations.configureInstance(obj, conf, _props, - (fatal) ? getProperty() : null); - if (_singleton) - set(obj, true); - return obj; - } - -" -473,1," public ScimGroup delete(String id, int version) throws ScimResourceNotFoundException { - ScimGroup group = retrieve(id); - membershipManager.removeMembersByGroupId(id); - externalGroupMappingManager.unmapAll(id); - int deleted; - if (version > 0) { - deleted = jdbcTemplate.update(DELETE_GROUP_SQL + "" and version=?;"", id, IdentityZoneHolder.get().getId(),version); - } else { - deleted = jdbcTemplate.update(DELETE_GROUP_SQL, id, IdentityZoneHolder.get().getId()); - } - if (deleted != 1) { - throw new IncorrectResultSizeDataAccessException(1, deleted); - } - return group; - } - -" -474,1," public Authentication attemptAuthentication(HttpServletRequest request) throws AuthenticationException { - - SecurityContext context = SecurityContextHolder.getContext(); - if (context != null) { - Authentication authentication = context.getAuthentication(); - if (authentication instanceof FederationAuthenticationToken) { - // If we reach this point then the token must be expired - throw new ExpiredTokenException(""Token is expired""); - } - } - - String wa = request.getParameter(FederationConstants.PARAM_ACTION); - String responseToken = getResponseToken(request); - FedizRequest wfReq = new FedizRequest(); - wfReq.setAction(wa); - wfReq.setResponseToken(responseToken); - wfReq.setState(request.getParameter(SAMLSSOConstants.RELAY_STATE)); - wfReq.setRequest(request); - - X509Certificate certs[] = - (X509Certificate[])request.getAttribute(""javax.servlet.request.X509Certificate""); - wfReq.setCerts(certs); - - final UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(null, wfReq); - - authRequest.setDetails(authenticationDetailsSource.buildDetails(request)); - - return this.getAuthenticationManager().authenticate(authRequest); - } - - @Override -" -475,1," public void testPrototypeFactoryPublicSerialization() throws Exception { - final Integer proto = Integer.valueOf(9); - final Factory factory = FactoryUtils.prototypeFactory(proto); - assertNotNull(factory); - final Integer created = factory.create(); - assertTrue(proto != created); - assertEquals(proto, created); - - // check serialisation works - final ByteArrayOutputStream buffer = new ByteArrayOutputStream(); - final ObjectOutputStream out = new ObjectOutputStream(buffer); - out.writeObject(factory); - out.close(); - final ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(buffer.toByteArray())); - in.readObject(); - in.close(); - } - - @Test -" -476,1," protected void configure(HttpSecurity http) throws Exception { - logger.debug(""Using default configure(HttpSecurity). If subclassed this will potentially override subclass configure(HttpSecurity).""); - - http - .authorizeRequests() - .anyRequest().authenticated() - .and() - .formLogin().and() - .httpBasic(); - } - // @formatter:on - - @Autowired -" -477,1," public SocketState process(SocketWrapper socket) - throws IOException { - RequestInfo rp = request.getRequestProcessor(); - rp.setStage(org.apache.coyote.Constants.STAGE_PARSE); - - // Setting up the socket - this.socket = socket; - input = socket.getSocket().getInputStream(); - output = socket.getSocket().getOutputStream(); - int soTimeout = -1; - if (keepAliveTimeout > 0) { - soTimeout = socket.getSocket().getSoTimeout(); - } - - // Error flag - error = false; - - while (!error && !endpoint.isPaused()) { - - // Parsing the request header - try { - // Set keep alive timeout if enabled - if (keepAliveTimeout > 0) { - socket.getSocket().setSoTimeout(keepAliveTimeout); - } - // Get first message of the request - if (!readMessage(requestHeaderMessage)) { - // This means a connection timeout - break; - } - // Set back timeout if keep alive timeout is enabled - if (keepAliveTimeout > 0) { - socket.getSocket().setSoTimeout(soTimeout); - } - // Check message type, process right away and break if - // not regular request processing - int type = requestHeaderMessage.getByte(); - if (type == Constants.JK_AJP13_CPING_REQUEST) { - try { - output.write(pongMessageArray); - } catch (IOException e) { - error = true; - } - continue; - } else if(type != Constants.JK_AJP13_FORWARD_REQUEST) { - // Usually the servlet didn't read the previous request body - if(log.isDebugEnabled()) { - log.debug(""Unexpected message: ""+type); - } - continue; - } - - request.setStartTime(System.currentTimeMillis()); - } catch (IOException e) { - error = true; - break; - } catch (Throwable t) { - ExceptionUtils.handleThrowable(t); - log.debug(sm.getString(""ajpprocessor.header.error""), t); - // 400 - Bad Request - response.setStatus(400); - adapter.log(request, response, 0); - error = true; - } - - if (!error) { - // Setting up filters, and parse some request headers - rp.setStage(org.apache.coyote.Constants.STAGE_PREPARE); - try { - prepareRequest(); - } catch (Throwable t) { - ExceptionUtils.handleThrowable(t); - log.debug(sm.getString(""ajpprocessor.request.prepare""), t); - // 400 - Internal Server Error - response.setStatus(400); - adapter.log(request, response, 0); - error = true; - } - } - - if (endpoint.isPaused()) { - // 503 - Service unavailable - response.setStatus(503); - adapter.log(request, response, 0); - error = true; - } - - // Process the request in the adapter - if (!error) { - try { - rp.setStage(org.apache.coyote.Constants.STAGE_SERVICE); - adapter.service(request, response); - } catch (InterruptedIOException e) { - error = true; - } catch (Throwable t) { - ExceptionUtils.handleThrowable(t); - log.error(sm.getString(""ajpprocessor.request.process""), t); - // 500 - Internal Server Error - response.setStatus(500); - adapter.log(request, response, 0); - error = true; - } - } - - if (isAsync() && !error) { - break; - } - - // Finish the response if not done yet - if (!finished) { - try { - finish(); - } catch (Throwable t) { - ExceptionUtils.handleThrowable(t); - error = true; - } - } - - // If there was an error, make sure the request is counted as - // and error, and update the statistics counter - if (error) { - response.setStatus(500); - } - request.updateCounters(); - - rp.setStage(org.apache.coyote.Constants.STAGE_KEEPALIVE); - recycle(false); - } - - rp.setStage(org.apache.coyote.Constants.STAGE_ENDED); - - if (isAsync() && !error && !endpoint.isPaused()) { - return SocketState.LONG; - } else { - input = null; - output = null; - return SocketState.CLOSED; - } - - } - - @Override -" -478,1," public void send(final String format, final Object... args) { - descriptor.debug(logger, format, args); - } - } - final Debug debug = new Debug(); - Run run = context.getRun(); - final Result runResult = run.getResult(); - if (run instanceof AbstractBuild) { - Set users = ((AbstractBuild)run).getCulprits(); - RecipientProviderUtilities.addUsers(users, context.getListener(), env, to, cc, bcc, debug); - } else if (runResult != null) { - List> builds = new ArrayList<>(); - Run build = run; - builds.add(build); - build = build.getPreviousCompletedBuild(); - while (build != null) { - final Result buildResult = build.getResult(); - if (buildResult != null) { - if (buildResult.isWorseThan(Result.SUCCESS)) { - debug.send(""Including build %s with status %s"", build.getId(), buildResult); - builds.add(build); - } else { - break; - } - } - build = build.getPreviousCompletedBuild(); - } - Set users = RecipientProviderUtilities.getChangeSetAuthors(builds, debug); - RecipientProviderUtilities.addUsers(users, context.getListener(), env, to, cc, bcc, debug); - } - } - - @Extension - public static final class DescriptorImpl extends RecipientProviderDescriptor { - - @Override - public String getDisplayName() { - return ""Culprits""; - } - - } - -} -" -479,1," public Object getValue(Object parent) { - return ReflectionHelper.getValue( cascadingMember, parent ); - } - - @Override -" -480,1," public void testSnapshotAndRestore() throws ExecutionException, InterruptedException, IOException { - logger.info(""--> creating repository""); - assertAcked(client().admin().cluster().preparePutRepository(""test-repo"") - .setType(""fs"").setSettings(ImmutableSettings.settingsBuilder() - .put(""location"", newTempDir(LifecycleScope.SUITE).getAbsolutePath()) - .put(""compress"", randomBoolean()) - .put(""chunk_size"", randomIntBetween(100, 1000)))); - String[] indicesBefore = new String[randomIntBetween(2,5)]; - String[] indicesAfter = new String[randomIntBetween(2,5)]; - for (int i = 0; i < indicesBefore.length; i++) { - indicesBefore[i] = ""index_before_"" + i; - createIndex(indicesBefore[i]); - } - for (int i = 0; i < indicesAfter.length; i++) { - indicesAfter[i] = ""index_after_"" + i; - createIndex(indicesAfter[i]); - } - String[] indices = new String[indicesBefore.length + indicesAfter.length]; - System.arraycopy(indicesBefore, 0, indices, 0, indicesBefore.length); - System.arraycopy(indicesAfter, 0, indices, indicesBefore.length, indicesAfter.length); - ensureYellow(); - logger.info(""--> indexing some data""); - IndexRequestBuilder[] buildersBefore = new IndexRequestBuilder[randomIntBetween(10, 200)]; - for (int i = 0; i < buildersBefore.length; i++) { - buildersBefore[i] = client().prepareIndex(RandomPicks.randomFrom(getRandom(), indicesBefore), ""foo"", Integer.toString(i)).setSource(""{ \""foo\"" : \""bar\"" } ""); - } - IndexRequestBuilder[] buildersAfter = new IndexRequestBuilder[randomIntBetween(10, 200)]; - for (int i = 0; i < buildersAfter.length; i++) { - buildersAfter[i] = client().prepareIndex(RandomPicks.randomFrom(getRandom(), indicesBefore), ""bar"", Integer.toString(i)).setSource(""{ \""foo\"" : \""bar\"" } ""); - } - indexRandom(true, buildersBefore); - indexRandom(true, buildersAfter); - assertThat(client().prepareCount(indices).get().getCount(), equalTo((long) (buildersBefore.length + buildersAfter.length))); - long[] counts = new long[indices.length]; - for (int i = 0; i < indices.length; i++) { - counts[i] = client().prepareCount(indices[i]).get().getCount(); - } - - logger.info(""--> snapshot subset of indices before upgrage""); - CreateSnapshotResponse createSnapshotResponse = client().admin().cluster().prepareCreateSnapshot(""test-repo"", ""test-snap-1"").setWaitForCompletion(true).setIndices(""index_before_*"").get(); - assertThat(createSnapshotResponse.getSnapshotInfo().successfulShards(), greaterThan(0)); - assertThat(createSnapshotResponse.getSnapshotInfo().successfulShards(), equalTo(createSnapshotResponse.getSnapshotInfo().totalShards())); - - assertThat(client().admin().cluster().prepareGetSnapshots(""test-repo"").setSnapshots(""test-snap-1"").get().getSnapshots().get(0).state(), equalTo(SnapshotState.SUCCESS)); - - logger.info(""--> delete some data from indices that were already snapshotted""); - int howMany = randomIntBetween(1, buildersBefore.length); - - for (int i = 0; i < howMany; i++) { - IndexRequestBuilder indexRequestBuilder = RandomPicks.randomFrom(getRandom(), buildersBefore); - IndexRequest request = indexRequestBuilder.request(); - client().prepareDelete(request.index(), request.type(), request.id()).get(); - } - refresh(); - final long numDocs = client().prepareCount(indices).get().getCount(); - assertThat(client().prepareCount(indices).get().getCount(), lessThan((long) (buildersBefore.length + buildersAfter.length))); - - - client().admin().indices().prepareUpdateSettings(indices).setSettings(ImmutableSettings.builder().put(EnableAllocationDecider.INDEX_ROUTING_ALLOCATION_ENABLE, ""none"")).get(); - backwardsCluster().allowOnAllNodes(indices); - logClusterState(); - boolean upgraded; - do { - logClusterState(); - CountResponse countResponse = client().prepareCount().get(); - assertHitCount(countResponse, numDocs); - upgraded = backwardsCluster().upgradeOneNode(); - ensureYellow(); - countResponse = client().prepareCount().get(); - assertHitCount(countResponse, numDocs); - } while (upgraded); - client().admin().indices().prepareUpdateSettings(indices).setSettings(ImmutableSettings.builder().put(EnableAllocationDecider.INDEX_ROUTING_ALLOCATION_ENABLE, ""all"")).get(); - - logger.info(""--> close indices""); - client().admin().indices().prepareClose(""index_before_*"").get(); - - logger.info(""--> verify repository""); - client().admin().cluster().prepareVerifyRepository(""test-repo"").get(); - - logger.info(""--> restore all indices from the snapshot""); - RestoreSnapshotResponse restoreSnapshotResponse = client().admin().cluster().prepareRestoreSnapshot(""test-repo"", ""test-snap-1"").setWaitForCompletion(true).execute().actionGet(); - assertThat(restoreSnapshotResponse.getRestoreInfo().totalShards(), greaterThan(0)); - - ensureYellow(); - assertThat(client().prepareCount(indices).get().getCount(), equalTo((long) (buildersBefore.length + buildersAfter.length))); - for (int i = 0; i < indices.length; i++) { - assertThat(counts[i], equalTo(client().prepareCount(indices[i]).get().getCount())); - } - - logger.info(""--> snapshot subset of indices after upgrade""); - createSnapshotResponse = client().admin().cluster().prepareCreateSnapshot(""test-repo"", ""test-snap-2"").setWaitForCompletion(true).setIndices(""index_*"").get(); - assertThat(createSnapshotResponse.getSnapshotInfo().successfulShards(), greaterThan(0)); - assertThat(createSnapshotResponse.getSnapshotInfo().successfulShards(), equalTo(createSnapshotResponse.getSnapshotInfo().totalShards())); - - // Test restore after index deletion - logger.info(""--> delete indices""); - String index = RandomPicks.randomFrom(getRandom(), indices); - cluster().wipeIndices(index); - logger.info(""--> restore one index after deletion""); - restoreSnapshotResponse = client().admin().cluster().prepareRestoreSnapshot(""test-repo"", ""test-snap-2"").setWaitForCompletion(true).setIndices(index).execute().actionGet(); - assertThat(restoreSnapshotResponse.getRestoreInfo().totalShards(), greaterThan(0)); - ensureYellow(); - assertThat(client().prepareCount(indices).get().getCount(), equalTo((long) (buildersBefore.length + buildersAfter.length))); - for (int i = 0; i < indices.length; i++) { - assertThat(counts[i], equalTo(client().prepareCount(indices[i]).get().getCount())); - } - } - -" -481,1," public void canModifyPassword() throws Exception { - ScimUser user = new ScimUser(null, generator.generate()+ ""@foo.com"", ""Jo"", ""User""); - user.addEmail(user.getUserName()); - ScimUser created = db.createUser(user, ""j7hyqpassX""); - assertNull(user.getPasswordLastModified()); - assertNotNull(created.getPasswordLastModified()); - assertEquals(created.getMeta().getCreated(), created.getPasswordLastModified()); - Thread.sleep(10); - db.changePassword(created.getId(), ""j7hyqpassX"", ""j7hyqpassXXX""); - - user = db.retrieve(created.getId()); - assertNotNull(user.getPasswordLastModified()); - assertEquals(user.getMeta().getLastModified(), user.getPasswordLastModified()); - } - - @Test -" -482,1," public void addRecipients(final ExtendedEmailPublisherContext context, EnvVars env, Set to, Set cc, Set 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(); - // looking for Upstream build. - Run cur = context.getRun(); - Cause.UpstreamCause upc = cur.getCause(Cause.UpstreamCause.class); - while (upc != null) { - // UpstreamCause.getUpStreamProject() returns the full name, so use getItemByFullName - 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); - } - addUserTriggeringTheBuild(cur, to, cc, bcc, env, context.getListener(), debug); - } - -" -483,1," public void doHarmonyDecoder(byte[] src, boolean errorExpected, - int failPosExpected) { - CharsetDecoder decoder = new Utf8Decoder(); - - ByteBuffer bb = ByteBuffer.allocate(src.length); - CharBuffer cb = CharBuffer.allocate(bb.limit()); - - boolean error = false; - int i = 0; - for (; i < src.length; i++) { - bb.put(src[i]); - bb.flip(); - CoderResult cr = decoder.decode(bb, cb, false); - if (cr.isError()) { - error = true; - break; - } - bb.compact(); - } - - assertEquals(Boolean.valueOf(errorExpected), Boolean.valueOf(error)); - assertEquals(failPosExpected, i); - } -" -484,1," public byte[] asPortableSerializedByteArray() throws EncryptionException { - // Check if this CipherText object is ""complete"", i.e., all - // mandatory has been collected. - if ( ! collectedAll() ) { - String msg = ""Can't serialize this CipherText object yet as not "" + - ""all mandatory information has been collected""; - throw new EncryptionException(""Can't serialize incomplete ciphertext info"", msg); - } - - // If we are supposed to be using a (separate) MAC, also make sure - // that it has been computed/stored. - boolean usesMAC = ESAPI.securityConfiguration().useMACforCipherText(); - if ( usesMAC && ! macComputed() ) { - String msg = ""Programming error: MAC is required for this cipher mode ("" + - getCipherMode() + ""), but MAC has not yet been "" + - ""computed and stored. Call the method "" + - ""computeAndStoreMAC(SecretKey) first before "" + - ""attempting serialization.""; - throw new EncryptionException(""Can't serialize ciphertext info: Data integrity issue."", - msg); - } - - // OK, everything ready, so give it a shot. - return new CipherTextSerializer(this).asSerializedByteArray(); - } - - ///// Setters ///// - /** - * Set the raw ciphertext. - * @param ciphertext The raw ciphertext. - * @throws EncryptionException Thrown if the MAC has already been computed - * via {@link #computeAndStoreMAC(SecretKey)}. - */ -" -485,1," protected void handle(Message msg) throws IOException { - inbound.offer(msg); - } - - } - -} -" -486,1," protected void doPost(HttpServletRequest req, HttpServletResponse resp) - throws ServletException, IOException { - doGet(req, resp); - } - } - - @ServletSecurity(@HttpConstraint(EmptyRoleSemantic.DENY)) - public static class DenyAllServlet extends TestServlet { - private static final long serialVersionUID = 1L; - } - - public static class SubclassDenyAllServlet extends DenyAllServlet { - private static final long serialVersionUID = 1L; - } - - @ServletSecurity(@HttpConstraint(EmptyRoleSemantic.PERMIT)) - public static class SubclassAllowAllServlet extends DenyAllServlet { - private static final long serialVersionUID = 1L; - } - - @ServletSecurity(value= @HttpConstraint(EmptyRoleSemantic.PERMIT), - httpMethodConstraints = { - @HttpMethodConstraint(value=""GET"", - emptyRoleSemantic = EmptyRoleSemantic.DENY) - } - ) - public static class MethodConstraintServlet extends TestServlet { - private static final long serialVersionUID = 1L; - } - - @ServletSecurity(@HttpConstraint(rolesAllowed = ""testRole"")) - public static class RoleAllowServlet extends TestServlet { - private static final long serialVersionUID = 1L; - } - - @ServletSecurity(@HttpConstraint(rolesAllowed = ""otherRole"")) - public static class RoleDenyServlet extends TestServlet { - private static final long serialVersionUID = 1L; - } -} -" -487,1," protected Http11Processor createProcessor() { - Http11Processor processor = new Http11Processor( - proto.getMaxHttpHeaderSize(), (JIoEndpoint)proto.endpoint, - proto.getMaxTrailerSize()); - processor.setAdapter(proto.getAdapter()); - processor.setMaxKeepAliveRequests(proto.getMaxKeepAliveRequests()); - processor.setKeepAliveTimeout(proto.getKeepAliveTimeout()); - processor.setConnectionUploadTimeout( - proto.getConnectionUploadTimeout()); - processor.setDisableUploadTimeout(proto.getDisableUploadTimeout()); - processor.setCompressionMinSize(proto.getCompressionMinSize()); - processor.setCompression(proto.getCompression()); - processor.setNoCompressionUserAgents(proto.getNoCompressionUserAgents()); - processor.setCompressableMimeTypes(proto.getCompressableMimeTypes()); - processor.setRestrictedUserAgents(proto.getRestrictedUserAgents()); - processor.setSocketBuffer(proto.getSocketBuffer()); - processor.setMaxSavePostSize(proto.getMaxSavePostSize()); - processor.setServer(proto.getServer()); - processor.setDisableKeepAlivePercentage( - proto.getDisableKeepAlivePercentage()); - register(processor); - return processor; - } - - @Override -" -488,1," public SocketState process(SocketWrapper socket) - throws IOException { - RequestInfo rp = request.getRequestProcessor(); - rp.setStage(org.apache.coyote.Constants.STAGE_PARSE); - - // Setting up the socket - this.socket = socket.getSocket(); - - long soTimeout = endpoint.getSoTimeout(); - - // Error flag - error = false; - - while (!error && !endpoint.isPaused()) { - // Parsing the request header - try { - // Get first message of the request - int bytesRead = readMessage(requestHeaderMessage, false); - if (bytesRead == 0) { - break; - } - // Set back timeout if keep alive timeout is enabled - if (keepAliveTimeout > 0) { - socket.setTimeout(soTimeout); - } - // Check message type, process right away and break if - // not regular request processing - int type = requestHeaderMessage.getByte(); - if (type == Constants.JK_AJP13_CPING_REQUEST) { - try { - output(pongMessageArray, 0, pongMessageArray.length); - } catch (IOException e) { - error = true; - } - recycle(false); - continue; - } else if(type != Constants.JK_AJP13_FORWARD_REQUEST) { - // Usually the servlet didn't read the previous request body - if(log.isDebugEnabled()) { - log.debug(""Unexpected message: ""+type); - } - recycle(true); - continue; - } - request.setStartTime(System.currentTimeMillis()); - } catch (IOException e) { - error = true; - break; - } catch (Throwable t) { - ExceptionUtils.handleThrowable(t); - log.debug(sm.getString(""ajpprocessor.header.error""), t); - // 400 - Bad Request - response.setStatus(400); - adapter.log(request, response, 0); - error = true; - } - - if (!error) { - // Setting up filters, and parse some request headers - rp.setStage(org.apache.coyote.Constants.STAGE_PREPARE); - try { - prepareRequest(); - } catch (Throwable t) { - ExceptionUtils.handleThrowable(t); - log.debug(sm.getString(""ajpprocessor.request.prepare""), t); - // 400 - Internal Server Error - response.setStatus(400); - adapter.log(request, response, 0); - error = true; - } - } - - if (endpoint.isPaused()) { - // 503 - Service unavailable - response.setStatus(503); - adapter.log(request, response, 0); - error = true; - } - - // Process the request in the adapter - if (!error) { - try { - rp.setStage(org.apache.coyote.Constants.STAGE_SERVICE); - adapter.service(request, response); - } catch (InterruptedIOException e) { - error = true; - } catch (Throwable t) { - ExceptionUtils.handleThrowable(t); - log.error(sm.getString(""ajpprocessor.request.process""), t); - // 500 - Internal Server Error - response.setStatus(500); - adapter.log(request, response, 0); - error = true; - } - } - - if (isAsync() && !error) { - break; - } - - // Finish the response if not done yet - if (!finished) { - try { - finish(); - } catch (Throwable t) { - ExceptionUtils.handleThrowable(t); - error = true; - } - } - - // If there was an error, make sure the request is counted as - // and error, and update the statistics counter - if (error) { - response.setStatus(500); - } - request.updateCounters(); - - rp.setStage(org.apache.coyote.Constants.STAGE_KEEPALIVE); - // Set keep alive timeout if enabled - if (keepAliveTimeout > 0) { - socket.setTimeout(keepAliveTimeout); - } - - recycle(false); - } - - rp.setStage(org.apache.coyote.Constants.STAGE_ENDED); - - if (!error && !endpoint.isPaused()) { - if (isAsync()) { - return SocketState.LONG; - } else { - return SocketState.OPEN; - } - } else { - return SocketState.CLOSED; - } - - } - - - // ----------------------------------------------------- ActionHook Methods - - - /** - * Send an action to the connector. - * - * @param actionCode Type of the action - * @param param Action parameter - */ - @Override -" -489,1," public void invoke(Request request, Response response) - throws IOException, ServletException { - - if (log.isDebugEnabled()) - log.debug(""Security checking request "" + - request.getMethod() + "" "" + request.getRequestURI()); - LoginConfig config = this.context.getLoginConfig(); - - // Have we got a cached authenticated Principal to record? - if (cache) { - Principal principal = request.getUserPrincipal(); - if (principal == null) { - Session session = request.getSessionInternal(false); - if (session != null) { - principal = session.getPrincipal(); - if (principal != null) { - if (log.isDebugEnabled()) - log.debug(""We have cached auth type "" + - session.getAuthType() + - "" for principal "" + - session.getPrincipal()); - request.setAuthType(session.getAuthType()); - request.setUserPrincipal(principal); - } - } - } - } - - // Special handling for form-based logins to deal with the case - // where the login form (and therefore the ""j_security_check"" URI - // to which it submits) might be outside the secured area - String contextPath = this.context.getPath(); - String requestURI = request.getDecodedRequestURI(); - if (requestURI.startsWith(contextPath) && - requestURI.endsWith(Constants.FORM_ACTION)) { - if (!authenticate(request, response, config)) { - if (log.isDebugEnabled()) - log.debug("" Failed authenticate() test ??"" + requestURI ); - return; - } - } - - // The Servlet may specify security constraints through annotations. - // Ensure that they have been processed before constraints are checked - Wrapper wrapper = (Wrapper) request.getMappingData().wrapper; - if (wrapper.getServlet() == null) { - wrapper.load(); - } - - Realm realm = this.context.getRealm(); - // Is this request URI subject to a security constraint? - SecurityConstraint [] constraints - = realm.findSecurityConstraints(request, this.context); - - if ((constraints == null) /* && - (!Constants.FORM_METHOD.equals(config.getAuthMethod())) */ ) { - if (log.isDebugEnabled()) - log.debug("" Not subject to any constraint""); - getNext().invoke(request, response); - return; - } - - // Make sure that constrained resources are not cached by web proxies - // or browsers as caching can provide a security hole - if (disableProxyCaching && - // FIXME: Disabled for Mozilla FORM support over SSL - // (improper caching issue) - //!request.isSecure() && - !""POST"".equalsIgnoreCase(request.getMethod())) { - if (securePagesWithPragma) { - // FIXME: These cause problems with downloading office docs - // from IE under SSL and may not be needed for newer Mozilla - // clients. - response.setHeader(""Pragma"", ""No-cache""); - response.setHeader(""Cache-Control"", ""no-cache""); - } else { - response.setHeader(""Cache-Control"", ""private""); - } - response.setHeader(""Expires"", DATE_ONE); - } - - int i; - // Enforce any user data constraint for this security constraint - if (log.isDebugEnabled()) { - log.debug("" Calling hasUserDataPermission()""); - } - if (!realm.hasUserDataPermission(request, response, - constraints)) { - if (log.isDebugEnabled()) { - log.debug("" Failed hasUserDataPermission() test""); - } - /* - * ASSERT: Authenticator already set the appropriate - * HTTP status code, so we do not have to do anything special - */ - return; - } - - // Since authenticate modifies the response on failure, - // we have to check for allow-from-all first. - boolean authRequired = true; - for(i=0; i < constraints.length && authRequired; i++) { - if(!constraints[i].getAuthConstraint()) { - authRequired = false; - } else if(!constraints[i].getAllRoles()) { - String [] roles = constraints[i].findAuthRoles(); - if(roles == null || roles.length == 0) { - authRequired = false; - } - } - } - - if(authRequired) { - if (log.isDebugEnabled()) { - log.debug("" Calling authenticate()""); - } - if (!authenticate(request, response, config)) { - if (log.isDebugEnabled()) { - log.debug("" Failed authenticate() test""); - } - /* - * ASSERT: Authenticator already set the appropriate - * HTTP status code, so we do not have to do anything - * special - */ - return; - } - - } - - if (log.isDebugEnabled()) { - log.debug("" Calling accessControl()""); - } - if (!realm.hasResourcePermission(request, response, - constraints, - this.context)) { - if (log.isDebugEnabled()) { - log.debug("" Failed accessControl() test""); - } - /* - * ASSERT: AccessControl method has already set the - * appropriate HTTP status code, so we do not have to do - * anything special - */ - return; - } - - // Any and all specified constraints have been satisfied - if (log.isDebugEnabled()) { - log.debug("" Successfully passed all security constraints""); - } - getNext().invoke(request, response); - - } - - - // ------------------------------------------------------ Protected Methods - - - /** - * Associate the specified single sign on identifier with the - * specified Session. - * - * @param ssoId Single sign on identifier - * @param session Session to be associated - */ -" -490,1," public void setUp() throws Exception - { - super.setUp(); - _expectedResult = mock(AuthenticationResult.class); - _authenticationProvider = mock(UsernamePasswordAuthenticationProvider.class); - when(_authenticationProvider.authenticate(eq(VALID_USERNAME), eq(VALID_PASSWORD))).thenReturn(_expectedResult); - _negotiator = new PlainNegotiator(_authenticationProvider); - } - - @Override -" -491,1," public byte[] toByteArray() - { - /* index || secretKeySeed || secretKeyPRF || publicSeed || root */ - int n = params.getDigestSize(); - int indexSize = (params.getHeight() + 7) / 8; - int secretKeySize = n; - int secretKeyPRFSize = n; - int publicSeedSize = n; - int rootSize = n; - int totalSize = indexSize + secretKeySize + secretKeyPRFSize + publicSeedSize + rootSize; - byte[] out = new byte[totalSize]; - int position = 0; - /* copy index */ - byte[] indexBytes = XMSSUtil.toBytesBigEndian(index, indexSize); - XMSSUtil.copyBytesAtOffset(out, indexBytes, position); - position += indexSize; - /* copy secretKeySeed */ - XMSSUtil.copyBytesAtOffset(out, secretKeySeed, position); - position += secretKeySize; - /* copy secretKeyPRF */ - XMSSUtil.copyBytesAtOffset(out, secretKeyPRF, position); - position += secretKeyPRFSize; - /* copy publicSeed */ - XMSSUtil.copyBytesAtOffset(out, publicSeed, position); - position += publicSeedSize; - /* copy root */ - XMSSUtil.copyBytesAtOffset(out, root, position); - /* concatenate bdsState */ - byte[] bdsStateOut = null; - try - { - bdsStateOut = XMSSUtil.serialize(bdsState); - } - catch (IOException e) - { - e.printStackTrace(); - throw new RuntimeException(""error serializing bds state""); - } - return Arrays.concatenate(out, bdsStateOut); - } - -" -492,1," public TransformerFactory createTransformerFactory() { - TransformerFactory factory = TransformerFactory.newInstance(); - factory.setErrorListener(new XmlErrorListener()); - return factory; - } - -" -493,1," public static void addUsers(final Set users, final TaskListener listener, final EnvVars env, - final Set to, final Set cc, final Set bcc, final IDebug debug) { - for (final User user : users) { - if (EmailRecipientUtils.isExcludedRecipient(user, listener)) { - debug.send(""User %s is an excluded recipient."", user.getFullName()); - } else { - final String userAddress = EmailRecipientUtils.getUserConfiguredEmail(user); - if (userAddress != null) { - debug.send(""Adding %s with address %s"", user.getFullName(), userAddress); - EmailRecipientUtils.addAddressesFromRecipientList(to, cc, bcc, userAddress, env, listener); - } else { - listener.getLogger().println(""Failed to send e-mail to "" - + user.getFullName() - + "" because no e-mail address is known, and no default e-mail domain is configured""); - } - } - } - } -" -494,1," PlainText decrypt(SecretKey key, CipherText ciphertext) throws EncryptionException; - - /** - * Create a digital signature for the provided data and return it in a - * string. - *

- * Limitations: A new public/private key pair used for ESAPI 2.0 digital - * signatures with this method and {@link #verifySignature(String, String)} - * are dynamically created when the default reference implementation class, - * {@link org.owasp.esapi.reference.crypto.JavaEncryptor} is first created. - * Because this key pair is not persisted nor is the public key shared, - * this method and the corresponding {@link #verifySignature(String, String)} - * can not be used with expected results across JVM instances. This limitation - * will be addressed in ESAPI 2.1. - *

- * - * @param data - * the data to sign - * - * @return - * the digital signature stored as a String - * - * @throws EncryptionException - * if the specified signature algorithm cannot be found - */ -" -495,1," public void init(KeyGenerationParameters param) - { - this.param = (RSAKeyGenerationParameters)param; - this.iterations = getNumberOfIterations(this.param.getStrength(), this.param.getCertainty()); - } - -" -496,1," private ResetPasswordResponse changePasswordCodeAuthenticated(String code, String newPassword) { - ExpiringCode expiringCode = expiringCodeStore.retrieveCode(code); - if (expiringCode == null) { - throw new InvalidCodeException(""invalid_code"", ""Sorry, your reset password link is no longer valid. Please request a new one"", 422); - } - String userId; - String userName = null; - Date passwordLastModified = null; - String clientId = null; - String redirectUri = null; - try { - PasswordChange change = JsonUtils.readValue(expiringCode.getData(), PasswordChange.class); - userId = change.getUserId(); - userName = change.getUsername(); - passwordLastModified = change.getPasswordModifiedTime(); - clientId = change.getClientId(); - redirectUri = change.getRedirectUri(); - } catch (JsonUtils.JsonUtilException x) { - userId = expiringCode.getData(); - } - ScimUser user = scimUserProvisioning.retrieve(userId); - try { - if (isUserModified(user, expiringCode.getExpiresAt(), userName, passwordLastModified)) { - throw new UaaException(""Invalid password reset request.""); - } - if (!user.isVerified()) { - scimUserProvisioning.verifyUser(userId, -1); - } - if (scimUserProvisioning.checkPasswordMatches(userId, newPassword)) { - throw new InvalidPasswordException(""Your new password cannot be the same as the old password."", UNPROCESSABLE_ENTITY); - } - scimUserProvisioning.changePassword(userId, null, newPassword); - publish(new PasswordChangeEvent(""Password changed"", getUaaUser(user), SecurityContextHolder.getContext().getAuthentication())); - - String redirectLocation = ""home""; - if (!isEmpty(clientId) && !isEmpty(redirectUri)) { - try { - ClientDetails clientDetails = clientDetailsService.loadClientByClientId(clientId); - Set redirectUris = clientDetails.getRegisteredRedirectUri() == null ? Collections.emptySet() : - clientDetails.getRegisteredRedirectUri(); - String matchingRedirectUri = UaaUrlUtils.findMatchingRedirectUri(redirectUris, redirectUri, null); - if (matchingRedirectUri != null) { - redirectLocation = matchingRedirectUri; - } - } catch (NoSuchClientException nsce) {} - } - return new ResetPasswordResponse(user, redirectLocation, clientId); - } catch (Exception e) { - publish(new PasswordChangeFailureEvent(e.getMessage(), getUaaUser(user), SecurityContextHolder.getContext().getAuthentication())); - throw e; - } - } - - @Override -" -497,1," public boolean accept(File pathname) { - return pathname.isDirectory() && new File(pathname, ""config.xml"").isFile() && idStrategy().equals( - pathname.getName(), id); - } - }); - } - - /** - * Gets the directory where Hudson stores user information. - */ -" -498,1," public void register(ContainerBuilder builder, LocatableProperties props) { - alias(ObjectFactory.class, StrutsConstants.STRUTS_OBJECTFACTORY, builder, props); - alias(FileManagerFactory.class, StrutsConstants.STRUTS_FILE_MANAGER_FACTORY, builder, props, Scope.SINGLETON); - - alias(XWorkConverter.class, StrutsConstants.STRUTS_XWORKCONVERTER, builder, props); - alias(CollectionConverter.class, StrutsConstants.STRUTS_CONVERTER_COLLECTION, builder, props); - alias(ArrayConverter.class, StrutsConstants.STRUTS_CONVERTER_ARRAY, builder, props); - alias(DateConverter.class, StrutsConstants.STRUTS_CONVERTER_DATE, builder, props); - alias(NumberConverter.class, StrutsConstants.STRUTS_CONVERTER_NUMBER, builder, props); - alias(StringConverter.class, StrutsConstants.STRUTS_CONVERTER_STRING, builder, props); - - alias(ConversionPropertiesProcessor.class, StrutsConstants.STRUTS_CONVERTER_PROPERTIES_PROCESSOR, builder, props); - alias(ConversionFileProcessor.class, StrutsConstants.STRUTS_CONVERTER_FILE_PROCESSOR, builder, props); - alias(ConversionAnnotationProcessor.class, StrutsConstants.STRUTS_CONVERTER_ANNOTATION_PROCESSOR, builder, props); - alias(TypeConverterCreator.class, StrutsConstants.STRUTS_CONVERTER_CREATOR, builder, props); - alias(TypeConverterHolder.class, StrutsConstants.STRUTS_CONVERTER_HOLDER, builder, props); - - alias(TextProvider.class, StrutsConstants.STRUTS_XWORKTEXTPROVIDER, builder, props, Scope.DEFAULT); - - alias(LocaleProvider.class, StrutsConstants.STRUTS_LOCALE_PROVIDER, builder, props); - alias(ActionProxyFactory.class, StrutsConstants.STRUTS_ACTIONPROXYFACTORY, builder, props); - alias(ObjectTypeDeterminer.class, StrutsConstants.STRUTS_OBJECTTYPEDETERMINER, builder, props); - alias(ActionMapper.class, StrutsConstants.STRUTS_MAPPER_CLASS, builder, props); - alias(MultiPartRequest.class, StrutsConstants.STRUTS_MULTIPART_PARSER, builder, props, Scope.DEFAULT); - alias(FreemarkerManager.class, StrutsConstants.STRUTS_FREEMARKER_MANAGER_CLASSNAME, builder, props); - alias(VelocityManager.class, StrutsConstants.STRUTS_VELOCITY_MANAGER_CLASSNAME, builder, props); - alias(UrlRenderer.class, StrutsConstants.STRUTS_URL_RENDERER, builder, props); - alias(ActionValidatorManager.class, StrutsConstants.STRUTS_ACTIONVALIDATORMANAGER, builder, props); - alias(ValueStackFactory.class, StrutsConstants.STRUTS_VALUESTACKFACTORY, builder, props); - alias(ReflectionProvider.class, StrutsConstants.STRUTS_REFLECTIONPROVIDER, builder, props); - alias(ReflectionContextFactory.class, StrutsConstants.STRUTS_REFLECTIONCONTEXTFACTORY, builder, props); - alias(PatternMatcher.class, StrutsConstants.STRUTS_PATTERNMATCHER, builder, props); - alias(StaticContentLoader.class, StrutsConstants.STRUTS_STATIC_CONTENT_LOADER, builder, props); - alias(UnknownHandlerManager.class, StrutsConstants.STRUTS_UNKNOWN_HANDLER_MANAGER, builder, props); - alias(UrlHelper.class, StrutsConstants.STRUTS_URL_HELPER, builder, props); - - alias(TextParser.class, StrutsConstants.STRUTS_EXPRESSION_PARSER, builder, props); - - if (""true"".equalsIgnoreCase(props.getProperty(StrutsConstants.STRUTS_DEVMODE))) { - props.setProperty(StrutsConstants.STRUTS_I18N_RELOAD, ""true""); - props.setProperty(StrutsConstants.STRUTS_CONFIGURATION_XML_RELOAD, ""true""); - props.setProperty(StrutsConstants.STRUTS_FREEMARKER_TEMPLATES_CACHE, ""false""); - props.setProperty(StrutsConstants.STRUTS_FREEMARKER_TEMPLATES_CACHE_UPDATE_DELAY, ""0""); - // Convert struts properties into ones that xwork expects - props.setProperty(XWorkConstants.DEV_MODE, ""true""); - } else { - props.setProperty(XWorkConstants.DEV_MODE, ""false""); - } - - // Convert Struts properties into XWork properties - convertIfExist(props, StrutsConstants.STRUTS_LOG_MISSING_PROPERTIES, XWorkConstants.LOG_MISSING_PROPERTIES); - convertIfExist(props, StrutsConstants.STRUTS_ENABLE_OGNL_EXPRESSION_CACHE, XWorkConstants.ENABLE_OGNL_EXPRESSION_CACHE); - convertIfExist(props, StrutsConstants.STRUTS_ALLOW_STATIC_METHOD_ACCESS, XWorkConstants.ALLOW_STATIC_METHOD_ACCESS); - convertIfExist(props, StrutsConstants.STRUTS_CONFIGURATION_XML_RELOAD, XWorkConstants.RELOAD_XML_CONFIGURATION); - - LocalizedTextUtil.addDefaultResourceBundle(""org/apache/struts2/struts-messages""); - loadCustomResourceBundles(props); - } - -" -499,1," public void changePassword_Returns422UnprocessableEntity_NewPasswordSameAsOld() throws Exception { - - Mockito.reset(passwordValidator); - - when(expiringCodeStore.retrieveCode(""emailed_code"")) - .thenReturn(new ExpiringCode(""emailed_code"", new Timestamp(System.currentTimeMillis()+ UaaResetPasswordService.PASSWORD_RESET_LIFETIME), ""eyedee"", null)); - - ScimUser scimUser = new ScimUser(""eyedee"", ""user@example.com"", ""User"", ""Man""); - scimUser.setMeta(new ScimMeta(new Date(System.currentTimeMillis()-(1000*60*60*24)), new Date(System.currentTimeMillis()-(1000*60*60*24)), 0)); - scimUser.addEmail(""user@example.com""); - scimUser.setVerified(true); - - when(scimUserProvisioning.retrieve(""eyedee"")).thenReturn(scimUser); - when(scimUserProvisioning.checkPasswordMatches(""eyedee"", ""new_secret"")).thenReturn(true); - - MockHttpServletRequestBuilder post = post(""/password_change"") - .contentType(APPLICATION_JSON) - .content(""{\""code\"":\""emailed_code\"",\""new_password\"":\""new_secret\""}"") - .accept(APPLICATION_JSON); - - SecurityContextHolder.getContext().setAuthentication(new MockAuthentication()); - - mockMvc.perform(post) - .andExpect(status().isUnprocessableEntity()) - .andExpect(content().string(JsonObjectMatcherUtils.matchesJsonObject(new JSONObject().put(""error_description"", ""Your new password cannot be the same as the old password."").put(""message"", ""Your new password cannot be the same as the old password."").put(""error"", ""invalid_password"")))); - } -" -500,1," private void setValidatedValueHandlerToValueContextIfPresent(ValidationContext validationContext, - ValueContext valueContext, ConstraintMetaData metaData) { - if ( metaData.requiresUnwrapping() ) { - @SuppressWarnings(""unchecked"") //we know the handler matches the value type - ValidatedValueUnwrapper handler = (ValidatedValueUnwrapper) getValidatedValueHandler( - metaData.getType() - ); - - if ( handler == null ) { - throw log.getNoUnwrapperFoundForTypeException( metaData.getType().toString() ); - } - - valueContext.setValidatedValueHandler( handler ); - } - } -" -501,1," public boolean getValidateClientProvidedNewSessionId() { return false; } -" -502,1," protected Object findValue(String expr, Class toType) { - if (altSyntax() && toType == String.class) { - return TextParseUtil.translateVariables('%', expr, stack); - } else { - expr = stripExpressionIfAltSyntax(expr); - - return getStack().findValue(expr, toType, throwExceptionOnELFailure); - } - } - - /** - * Renders an action URL by consulting the {@link org.apache.struts2.dispatcher.mapper.ActionMapper}. - * @param action the action - * @param namespace the namespace - * @param method the method - * @param req HTTP request - * @param res HTTP response - * @param parameters parameters - * @param scheme http or https - * @param includeContext should the context path be included or not - * @param encodeResult should the url be encoded - * @param forceAddSchemeHostAndPort should the scheme host and port be forced - * @param escapeAmp should ampersand (&) be escaped to &amp; - * @return the action url. - */ -" -503,1," public HttpBinding getBinding() { - if (this.binding == null) { - this.binding = new AttachmentHttpBinding(); - this.binding.setTransferException(isTransferException()); - this.binding.setHeaderFilterStrategy(getHeaderFilterStrategy()); - } - return this.binding; - } - - @Override -" -504,1," public HttpBinding getBinding() { - if (binding == null) { - // create a new binding and use the options from this endpoint - binding = new DefaultHttpBinding(); - binding.setHeaderFilterStrategy(getHeaderFilterStrategy()); - binding.setTransferException(isTransferException()); - binding.setEagerCheckContentAvailable(isEagerCheckContentAvailable()); - } - return binding; - } - - /** - * To use a custom HttpBinding to control the mapping between Camel message and HttpClient. - */ -" -505,1," public void setMaxTrailerSize(int maxTrailerSize) { - this.maxTrailerSize = maxTrailerSize; - } - - - /** - * This field indicates if the protocol is treated as if it is secure. This - * normally means https is being used but can be used to fake https e.g - * behind a reverse proxy. - */ -" -506,1," public void addRecipients(final ExtendedEmailPublisherContext context, final EnvVars env, - final Set to, final Set cc, final Set 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(); - - Set users = null; - - final Run currentRun = context.getRun(); - if (currentRun == null) { - debug.send(""currentRun was null""); - } else { - if (!Objects.equals(currentRun.getResult(), Result.FAILURE)) { - debug.send(""currentBuild did not fail""); - } else { - users = new HashSet<>(); - debug.send(""Collecting builds with suspects...""); - final HashSet> buildsWithSuspects = new HashSet<>(); - Run firstFailedBuild = currentRun; - Run candidate = currentRun; - while (candidate != null) { - final Result candidateResult = candidate.getResult(); - if ( candidateResult == null || !candidateResult.isWorseOrEqualTo(Result.FAILURE) ) { - break; - } - firstFailedBuild = candidate; - candidate = candidate.getPreviousCompletedBuild(); - } - if (firstFailedBuild instanceof AbstractBuild) { - buildsWithSuspects.add(firstFailedBuild); - } else { - debug.send("" firstFailedBuild was not an instance of AbstractBuild""); - } - debug.send(""Collecting suspects...""); - users.addAll(RecipientProviderUtilities.getChangeSetAuthors(buildsWithSuspects, debug)); - users.addAll(RecipientProviderUtilities.getUsersTriggeringTheBuilds(buildsWithSuspects, debug)); - } - } - if (users != null) { - RecipientProviderUtilities.addUsers(users, context.getListener(), env, to, cc, bcc, debug); - } - } - - @Extension -" -507,1," public void doFilter(ServletRequest filterRequest, - ServletResponse filterResponse) throws IOException, ServletException { - assertEquals(""Invalid method"", ""POST"", - ((HttpServletRequest) filterRequest).getMethod()); - } - }; -" -508,1," public void restorePersistentSettingsTest() throws Exception { - logger.info(""--> start 2 nodes""); - Settings nodeSettings = settingsBuilder() - .put(""discovery.type"", ""zen"") - .put(""discovery.zen.ping_timeout"", ""200ms"") - .put(""discovery.initial_state_timeout"", ""500ms"") - .build(); - internalCluster().startNode(nodeSettings); - Client client = client(); - String secondNode = internalCluster().startNode(nodeSettings); - logger.info(""--> wait for the second node to join the cluster""); - assertThat(client.admin().cluster().prepareHealth().setWaitForNodes(""2"").get().isTimedOut(), equalTo(false)); - - int random = randomIntBetween(10, 42); - - logger.info(""--> set test persistent setting""); - client.admin().cluster().prepareUpdateSettings().setPersistentSettings( - ImmutableSettings.settingsBuilder() - .put(ElectMasterService.DISCOVERY_ZEN_MINIMUM_MASTER_NODES, 2) - .put(IndicesTTLService.INDICES_TTL_INTERVAL, random, TimeUnit.MINUTES)) - .execute().actionGet(); - - assertThat(client.admin().cluster().prepareState().setRoutingTable(false).setNodes(false).execute().actionGet().getState() - .getMetaData().persistentSettings().getAsTime(IndicesTTLService.INDICES_TTL_INTERVAL, TimeValue.timeValueMinutes(1)).millis(), equalTo(TimeValue.timeValueMinutes(random).millis())); - assertThat(client.admin().cluster().prepareState().setRoutingTable(false).setNodes(false).execute().actionGet().getState() - .getMetaData().persistentSettings().getAsInt(ElectMasterService.DISCOVERY_ZEN_MINIMUM_MASTER_NODES, -1), equalTo(2)); - - logger.info(""--> create repository""); - PutRepositoryResponse putRepositoryResponse = client.admin().cluster().preparePutRepository(""test-repo"") - .setType(""fs"").setSettings(ImmutableSettings.settingsBuilder().put(""location"", newTempDir())).execute().actionGet(); - assertThat(putRepositoryResponse.isAcknowledged(), equalTo(true)); - - logger.info(""--> start snapshot""); - CreateSnapshotResponse createSnapshotResponse = client.admin().cluster().prepareCreateSnapshot(""test-repo"", ""test-snap"").setWaitForCompletion(true).execute().actionGet(); - assertThat(createSnapshotResponse.getSnapshotInfo().totalShards(), equalTo(0)); - assertThat(createSnapshotResponse.getSnapshotInfo().successfulShards(), equalTo(0)); - assertThat(client.admin().cluster().prepareGetSnapshots(""test-repo"").setSnapshots(""test-snap"").execute().actionGet().getSnapshots().get(0).state(), equalTo(SnapshotState.SUCCESS)); - - logger.info(""--> clean the test persistent setting""); - client.admin().cluster().prepareUpdateSettings().setPersistentSettings( - ImmutableSettings.settingsBuilder() - .put(ElectMasterService.DISCOVERY_ZEN_MINIMUM_MASTER_NODES, 1) - .put(IndicesTTLService.INDICES_TTL_INTERVAL, TimeValue.timeValueMinutes(1))) - .execute().actionGet(); - assertThat(client.admin().cluster().prepareState().setRoutingTable(false).setNodes(false).execute().actionGet().getState() - .getMetaData().persistentSettings().getAsTime(IndicesTTLService.INDICES_TTL_INTERVAL, TimeValue.timeValueMinutes(1)).millis(), equalTo(TimeValue.timeValueMinutes(1).millis())); - - stopNode(secondNode); - assertThat(client.admin().cluster().prepareHealth().setWaitForNodes(""1"").get().isTimedOut(), equalTo(false)); - - logger.info(""--> restore snapshot""); - client.admin().cluster().prepareRestoreSnapshot(""test-repo"", ""test-snap"").setRestoreGlobalState(true).setWaitForCompletion(true).execute().actionGet(); - assertThat(client.admin().cluster().prepareState().setRoutingTable(false).setNodes(false).execute().actionGet().getState() - .getMetaData().persistentSettings().getAsTime(IndicesTTLService.INDICES_TTL_INTERVAL, TimeValue.timeValueMinutes(1)).millis(), equalTo(TimeValue.timeValueMinutes(random).millis())); - - logger.info(""--> ensure that zen discovery minimum master nodes wasn't restored""); - assertThat(client.admin().cluster().prepareState().setRoutingTable(false).setNodes(false).execute().actionGet().getState() - .getMetaData().persistentSettings().getAsInt(ElectMasterService.DISCOVERY_ZEN_MINIMUM_MASTER_NODES, -1), not(equalTo(2))); - } - - @Test -" -509,1," public void init(FilterConfig conf) throws ServletException { - if (conf != null && ""zookeeper"".equals(conf.getInitParameter(""signer.secret.provider""))) { - SolrZkClient zkClient = - (SolrZkClient)conf.getServletContext().getAttribute(KerberosPlugin.DELEGATION_TOKEN_ZK_CLIENT); - conf.getServletContext().setAttribute(""signer.secret.provider.zookeeper.curator.client"", - getCuratorClient(zkClient)); - } - super.init(conf); - } - - /** - * Return the ProxyUser Configuration. FilterConfig properties beginning with - * ""solr.impersonator.user.name"" will be added to the configuration. - */ - @Override -" -510,1," Attributes setPropertiesFromAttributes( - StylesheetHandler handler, String rawName, Attributes attributes, - ElemTemplateElement target, boolean throwError) - throws org.xml.sax.SAXException - { - - XSLTElementDef def = getElemDef(); - AttributesImpl undefines = null; - boolean isCompatibleMode = ((null != handler.getStylesheet() - && handler.getStylesheet().getCompatibleMode()) - || !throwError); - if (isCompatibleMode) - undefines = new AttributesImpl(); - - - // Keep track of which XSLTAttributeDefs have been processed, so - // I can see which default values need to be set. - List processedDefs = new ArrayList(); - - // Keep track of XSLTAttributeDefs that were invalid - List errorDefs = new ArrayList(); - int nAttrs = attributes.getLength(); - - for (int i = 0; i < nAttrs; i++) - { - String attrUri = attributes.getURI(i); - // Hack for Crimson. -sb - if((null != attrUri) && (attrUri.length() == 0) - && (attributes.getQName(i).startsWith(""xmlns:"") || - attributes.getQName(i).equals(""xmlns""))) - { - attrUri = org.apache.xalan.templates.Constants.S_XMLNAMESPACEURI; - } - String attrLocalName = attributes.getLocalName(i); - XSLTAttributeDef attrDef = def.getAttributeDef(attrUri, attrLocalName); - - if (null == attrDef) - { - if (!isCompatibleMode) - { - - // Then barf, because this element does not allow this attribute. - handler.error(XSLTErrorResources.ER_ATTR_NOT_ALLOWED, new Object[]{attributes.getQName(i), rawName}, null);//""\""""+attributes.getQName(i)+""\"""" - //+ "" attribute is not allowed on the "" + rawName - // + "" element!"", null); - } - else - { - undefines.addAttribute(attrUri, attrLocalName, - attributes.getQName(i), - attributes.getType(i), - attributes.getValue(i)); - } - } - else - { - // Can we switch the order here: - - boolean success = attrDef.setAttrValue(handler, attrUri, attrLocalName, - attributes.getQName(i), attributes.getValue(i), - target); - - // Now we only add the element if it passed a validation check - if (success) - processedDefs.add(attrDef); - else - errorDefs.add(attrDef); - } - } - - XSLTAttributeDef[] attrDefs = def.getAttributes(); - int nAttrDefs = attrDefs.length; - - for (int i = 0; i < nAttrDefs; i++) - { - XSLTAttributeDef attrDef = attrDefs[i]; - String defVal = attrDef.getDefault(); - - if (null != defVal) - { - if (!processedDefs.contains(attrDef)) - { - attrDef.setDefAttrValue(handler, target); - } - } - - if (attrDef.getRequired()) - { - if ((!processedDefs.contains(attrDef)) && (!errorDefs.contains(attrDef))) - handler.error( - XSLMessages.createMessage( - XSLTErrorResources.ER_REQUIRES_ATTRIB, new Object[]{ rawName, - attrDef.getName() }), null); - } - } - - return undefines; - } -" -511,1," public SecurityConstraint [] findSecurityConstraints(Request request, - Context context) { - - ArrayList results = null; - // Are there any defined security constraints? - SecurityConstraint constraints[] = context.findConstraints(); - if ((constraints == null) || (constraints.length == 0)) { - if (log.isDebugEnabled()) - log.debug("" No applicable constraints defined""); - return null; - } - - // Check each defined security constraint - String uri = request.getRequestPathMB().toString(); - // Bug47080 - in rare cases this may be null - // Mapper treats as '/' do the same to prevent NPE - if (uri == null) { - uri = ""/""; - } - - String method = request.getMethod(); - int i; - boolean found = false; - for (i = 0; i < constraints.length; i++) { - SecurityCollection [] collection = constraints[i].findCollections(); - - // If collection is null, continue to avoid an NPE - // See Bugzilla 30624 - if ( collection == null) { - continue; - } - - if (log.isDebugEnabled()) { - log.debug("" Checking constraint '"" + constraints[i] + - ""' against "" + method + "" "" + uri + "" --> "" + - constraints[i].included(uri, method)); - } - - for(int j=0; j < collection.length; j++){ - String [] patterns = collection[j].findPatterns(); - - // If patterns is null, continue to avoid an NPE - // See Bugzilla 30624 - if ( patterns == null) { - continue; - } - - for(int k=0; k < patterns.length; k++) { - if(uri.equals(patterns[k])) { - found = true; - if(collection[j].findMethod(method)) { - if(results == null) { - results = new ArrayList<>(); - } - results.add(constraints[i]); - } - } - } - } - } - - if(found) { - return resultsToArray(results); - } - - int longest = -1; - - for (i = 0; i < constraints.length; i++) { - SecurityCollection [] collection = constraints[i].findCollections(); - - // If collection is null, continue to avoid an NPE - // See Bugzilla 30624 - if ( collection == null) { - continue; - } - - if (log.isDebugEnabled()) { - log.debug("" Checking constraint '"" + constraints[i] + - ""' against "" + method + "" "" + uri + "" --> "" + - constraints[i].included(uri, method)); - } - - for(int j=0; j < collection.length; j++){ - String [] patterns = collection[j].findPatterns(); - - // If patterns is null, continue to avoid an NPE - // See Bugzilla 30624 - if ( patterns == null) { - continue; - } - - boolean matched = false; - int length = -1; - for(int k=0; k < patterns.length; k++) { - String pattern = patterns[k]; - if(pattern.startsWith(""/"") && pattern.endsWith(""/*"") && - pattern.length() >= longest) { - - if(pattern.length() == 2) { - matched = true; - length = pattern.length(); - } else if(pattern.regionMatches(0,uri,0, - pattern.length()-1) || - (pattern.length()-2 == uri.length() && - pattern.regionMatches(0,uri,0, - pattern.length()-2))) { - matched = true; - length = pattern.length(); - } - } - } - if(matched) { - if(length > longest) { - found = false; - if(results != null) { - results.clear(); - } - longest = length; - } - if(collection[j].findMethod(method)) { - found = true; - if(results == null) { - results = new ArrayList<>(); - } - results.add(constraints[i]); - } - } - } - } - - if(found) { - return resultsToArray(results); - } - - for (i = 0; i < constraints.length; i++) { - SecurityCollection [] collection = constraints[i].findCollections(); - - // If collection is null, continue to avoid an NPE - // See Bugzilla 30624 - if ( collection == null) { - continue; - } - - if (log.isDebugEnabled()) { - log.debug("" Checking constraint '"" + constraints[i] + - ""' against "" + method + "" "" + uri + "" --> "" + - constraints[i].included(uri, method)); - } - - boolean matched = false; - int pos = -1; - for(int j=0; j < collection.length; j++){ - String [] patterns = collection[j].findPatterns(); - - // If patterns is null, continue to avoid an NPE - // See Bugzilla 30624 - if ( patterns == null) { - continue; - } - - for(int k=0; k < patterns.length && !matched; k++) { - String pattern = patterns[k]; - if(pattern.startsWith(""*."")){ - int slash = uri.lastIndexOf('/'); - int dot = uri.lastIndexOf('.'); - if(slash >= 0 && dot > slash && - dot != uri.length()-1 && - uri.length()-dot == pattern.length()-1) { - if(pattern.regionMatches(1,uri,dot,uri.length()-dot)) { - matched = true; - pos = j; - } - } - } - } - } - if(matched) { - found = true; - if(collection[pos].findMethod(method)) { - if(results == null) { - results = new ArrayList<>(); - } - results.add(constraints[i]); - } - } - } - - if(found) { - return resultsToArray(results); - } - - for (i = 0; i < constraints.length; i++) { - SecurityCollection [] collection = constraints[i].findCollections(); - - // If collection is null, continue to avoid an NPE - // See Bugzilla 30624 - if ( collection == null) { - continue; - } - - if (log.isDebugEnabled()) { - log.debug("" Checking constraint '"" + constraints[i] + - ""' against "" + method + "" "" + uri + "" --> "" + - constraints[i].included(uri, method)); - } - - for(int j=0; j < collection.length; j++){ - String [] patterns = collection[j].findPatterns(); - - // If patterns is null, continue to avoid an NPE - // See Bugzilla 30624 - if ( patterns == null) { - continue; - } - - boolean matched = false; - for(int k=0; k < patterns.length && !matched; k++) { - String pattern = patterns[k]; - if(pattern.equals(""/"")){ - matched = true; - } - } - if(matched) { - if(results == null) { - results = new ArrayList<>(); - } - results.add(constraints[i]); - } - } - } - - if(results == null) { - // No applicable security constraint was found - if (log.isDebugEnabled()) - log.debug("" No applicable constraint located""); - } - return resultsToArray(results); - } - - /** - * Convert an ArrayList to a SecurityConstraint []. - */ -" -512,1," private void writeSession(SessionInformations session, boolean displayUser) throws IOException { - final String nextColumnAlignRight = """"; - final String nextColumnAlignCenter = """"; - write(""""); - write(htmlEncodeButNotSpace(session.getId())); - write(""""); - write(nextColumnAlignRight); - write(durationFormat.format(session.getLastAccess())); - write(nextColumnAlignRight); - write(durationFormat.format(session.getAge())); - write(nextColumnAlignRight); - write(expiryFormat.format(session.getExpirationDate())); - - write(nextColumnAlignRight); - write(integerFormat.format(session.getAttributeCount())); - write(nextColumnAlignCenter); - if (session.isSerializable()) { - write(""#oui#""); - } else { - write(""#non#""); - } - write(nextColumnAlignRight); - write(integerFormat.format(session.getSerializedSize())); - final String nextColumn = """"; - write(nextColumn); - final String remoteAddr = session.getRemoteAddr(); - if (remoteAddr == null) { - write("" ""); - } else { - write(remoteAddr); - } - write(nextColumnAlignCenter); - writeCountry(session); - if (displayUser) { - write(nextColumn); - final String remoteUser = session.getRemoteUser(); - if (remoteUser == null) { - write("" ""); - } else { - writeDirectly(htmlEncodeButNotSpace(remoteUser)); - } - } - write(""""); - write(A_HREF_PART_SESSIONS); - write(""&action=invalidate_session&sessionId=""); - write(urlEncode(session.getId())); - write(""' onclick=\""javascript:return confirm('"" - + getStringForJavascript(""confirm_invalidate_session"") + ""');\"">""); - write(""#invalidate_session#""); - write(""""); - write(""""); - } - -" -513,1," public boolean isUseRouteBuilder() { - return false; - } - - @Test -" -514,1," private T run(PrivilegedAction action) { - return System.getSecurityManager() != null ? AccessController.doPrivileged( action ) : action.run(); - } - - // JAXB closes the underlying input stream -" -515,1," public void execute(FunctionContext context) { - RegionConfiguration configuration = (RegionConfiguration) context.getArguments(); - if (this.cache.getLogger().fineEnabled()) { - StringBuilder builder = new StringBuilder(); - builder.append(""Function "").append(ID).append("" received request: "").append(configuration); - this.cache.getLogger().fine(builder.toString()); - } - - // Create or retrieve region - RegionStatus status = createOrRetrieveRegion(configuration); - - // Dump XML - if (DUMP_SESSION_CACHE_XML) { - writeCacheXml(); - } - // Return status - context.getResultSender().lastResult(status); - } - -" -516,1," public static int methodUrl(String path, ByteChunk out, int readTimeout, - Map> reqHead, - Map> resHead, - String method) throws IOException { - - URL url = new URL(path); - HttpURLConnection connection = - (HttpURLConnection) url.openConnection(); - connection.setUseCaches(false); - connection.setReadTimeout(readTimeout); - connection.setRequestMethod(method); - if (reqHead != null) { - for (Map.Entry> entry : reqHead.entrySet()) { - StringBuilder valueList = new StringBuilder(); - for (String value : entry.getValue()) { - if (valueList.length() > 0) { - valueList.append(','); - } - valueList.append(value); - } - connection.setRequestProperty(entry.getKey(), - valueList.toString()); - } - } - connection.connect(); - int rc = connection.getResponseCode(); - if (resHead != null) { - Map> head = connection.getHeaderFields(); - resHead.putAll(head); - } - InputStream is; - if (rc < 400) { - is = connection.getInputStream(); - } else { - is = connection.getErrorStream(); - } - if (is != null) { - try (BufferedInputStream bis = new BufferedInputStream(is)) { - byte[] buf = new byte[2048]; - int rd = 0; - while((rd = bis.read(buf)) > 0) { - out.append(buf, 0, rd); - } - } - } - return rc; - } - -" -517,1," public void addRecipients(final ExtendedEmailPublisherContext context, final EnvVars env, - final Set to, final Set cc, final Set 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(); - - Set users = null; - - final Run currentRun = context.getRun(); - if (currentRun == null) { - debug.send(""currentRun was null""); - } else { - final AbstractTestResultAction testResultAction = currentRun.getAction(AbstractTestResultAction.class); - if (testResultAction == null) { - debug.send(""testResultAction was null""); - } else { - if (testResultAction.getFailCount() <= 0) { - debug.send(""getFailCount() returned <= 0""); - } else { - users = new HashSet<>(); - debug.send(""Collecting builds where a test started failing...""); - final HashSet> buildsWhereATestStartedFailing = new HashSet<>(); - for (final TestResult caseResult : testResultAction.getFailedTests()) { - final Run runWhereTestStartedFailing = caseResult.getFailedSinceRun(); - if (runWhereTestStartedFailing != null) { - debug.send("" runWhereTestStartedFailing: %d"", runWhereTestStartedFailing.getNumber()); - buildsWhereATestStartedFailing.add(runWhereTestStartedFailing); - } else { - context.getListener().error(""getFailedSinceRun returned null for %s"", caseResult.getFullDisplayName()); - } - } - // For each build where a test started failing, walk backward looking for build results worse than - // UNSTABLE. All of those builds will be used to find suspects. - debug.send(""Collecting builds with suspects...""); - final HashSet> buildsWithSuspects = new HashSet<>(); - for (final Run buildWhereATestStartedFailing : buildsWhereATestStartedFailing) { - debug.send("" buildWhereATestStartedFailing: %d"", buildWhereATestStartedFailing.getNumber()); - buildsWithSuspects.add(buildWhereATestStartedFailing); - Run previousBuildToCheck = buildWhereATestStartedFailing.getPreviousCompletedBuild(); - if (previousBuildToCheck != null) { - debug.send("" previousBuildToCheck: %d"", previousBuildToCheck.getNumber()); - } - while (previousBuildToCheck != null) { - if (buildsWithSuspects.contains(previousBuildToCheck)) { - // Short-circuit if the build to check has already been checked. - debug.send("" already contained in buildsWithSuspects; stopping search""); - break; - } - final Result previousResult = previousBuildToCheck.getResult(); - if (previousResult == null) { - debug.send("" previousResult was null""); - } else { - debug.send("" previousResult: %s"", previousResult.toString()); - if (previousResult.isBetterThan(Result.FAILURE)) { - debug.send("" previousResult was better than FAILURE; stopping search""); - break; - } else { - debug.send("" previousResult was not better than FAILURE; adding to buildsWithSuspects; continuing search""); - buildsWithSuspects.add(previousBuildToCheck); - previousBuildToCheck = previousBuildToCheck.getPreviousCompletedBuild(); - if (previousBuildToCheck != null) { - debug.send("" previousBuildToCheck: %d"", previousBuildToCheck.getNumber()); - } - } - } - } - } - debug.send(""Collecting suspects...""); - users.addAll(RecipientProviderUtilities.getChangeSetAuthors(buildsWithSuspects, debug)); - users.addAll(RecipientProviderUtilities.getUsersTriggeringTheBuilds(buildsWithSuspects, debug)); - } - } - } - - if (users != null) { - RecipientProviderUtilities.addUsers(users, context.getListener(), env, to, cc, bcc, debug); - } - } - - @Extension -" -518,1," public static DateTimeZone randomDateTimeZone() { - DateTimeZone timeZone; - - // It sounds like some Java Time Zones are unknown by JODA. For example: Asia/Riyadh88 - // We need to fallback in that case to a known time zone - try { - timeZone = DateTimeZone.forTimeZone(randomTimeZone()); - } catch (IllegalArgumentException e) { - timeZone = DateTimeZone.forOffsetHours(randomIntBetween(-12, 12)); - } - - return timeZone; - } - -" -519,1," public void testTriggerWithLockedDownInstance() throws Exception { - FreeStyleProject project = DuplicatesUtil.createGerritTriggeredJob(j, projectName); - - Setup.lockDown(j); - - GerritTrigger trigger = project.getTrigger(GerritTrigger.class); - trigger.setSilentStartMode(false); - - GerritServer gerritServer = new GerritServer(PluginImpl.DEFAULT_SERVER_NAME); - SshdServerMock.configureFor(sshd, gerritServer); - PluginImpl.getInstance().addServer(gerritServer); - gerritServer.getConfig().setNumberOfSendingWorkerThreads(NUMBEROFSENDERTHREADS); - ((Config)gerritServer.getConfig()).setGerritAuthKeyFile(sshKey.getPrivateKey()); - gerritServer.start(); - - gerritServer.triggerEvent(Setup.createPatchsetCreated()); - - TestUtils.waitForBuilds(project, 1); - //wait until command is registered - // CS IGNORE MagicNumber FOR NEXT 2 LINES. REASON: ConstantsNotNeeded - Thread.sleep(TimeUnit.SECONDS.toMillis(10)); - assertEquals(2, server.getNrCommandsHistory(""gerrit review.*"")); - - FreeStyleBuild buildOne = project.getLastCompletedBuild(); - assertSame(Result.SUCCESS, buildOne.getResult()); - assertEquals(1, project.getLastCompletedBuild().getNumber()); - assertSame(PluginImpl.DEFAULT_SERVER_NAME, - buildOne.getCause(GerritCause.class).getEvent().getProvider().getName()); - - } -" -520,1," public static Transformer cloneTransformer() { - return (Transformer) INSTANCE; - } - - /** - * Constructor. - */ -" -521,1," public void setEnabled(boolean enabled); - -" -522,1," public void testHttpSendStringAndReceiveJavaBody() throws Exception { - context.addRoutes(new RouteBuilder() { - @Override - public void configure() throws Exception { - from(""jetty:http://localhost:{{port}}/myapp/myservice"") - .process(new Processor() { - public void process(Exchange exchange) throws Exception { - String body = exchange.getIn().getBody(String.class); - assertNotNull(body); - assertEquals(""Hello World"", body); - - MyCoolBean reply = new MyCoolBean(456, ""Camel rocks""); - exchange.getOut().setBody(reply); - exchange.getOut().setHeader(Exchange.CONTENT_TYPE, HttpConstants.CONTENT_TYPE_JAVA_SERIALIZED_OBJECT); - } - }); - } - }); - context.start(); - - MyCoolBean reply = template.requestBody(""http://localhost:{{port}}/myapp/myservice"", ""Hello World"", MyCoolBean.class); - - assertEquals(456, reply.getId()); - assertEquals(""Camel rocks"", reply.getName()); - } - -" -523,1," private boolean evaluate(String text) { - try { - InputSource inputSource = new InputSource(new StringReader(text)); - return ((Boolean)expression.evaluate(inputSource, XPathConstants.BOOLEAN)).booleanValue(); - } catch (XPathExpressionException e) { - return false; - } - } - - @Override -" -524,1," protected boolean isAccepted(String paramName) { - if (!this.acceptParams.isEmpty()) { - for (Pattern pattern : acceptParams) { - Matcher matcher = pattern.matcher(paramName); - if (matcher.matches()) { - return true; - } - } - return false; - } else - return acceptedPattern.matcher(paramName).matches(); - } - -" -525,1," public void loadConfig(Class... configs) { - this.context = new AnnotationConfigWebApplicationContext(); - this.context.register(configs); - this.context.refresh(); - - this.context.getAutowireCapableBeanFactory().autowireBean(this); - } -" -526,1," private CoderResult decodeHasArray(ByteBuffer in, CharBuffer out) { - int outRemaining = out.remaining(); - int pos = in.position(); - int limit = in.limit(); - final byte[] bArr = in.array(); - final char[] cArr = out.array(); - final int inIndexLimit = limit + in.arrayOffset(); - int inIndex = pos + in.arrayOffset(); - int outIndex = out.position() + out.arrayOffset(); - // if someone would change the limit in process, - // he would face consequences - for (; inIndex < inIndexLimit && outRemaining > 0; inIndex++) { - int jchar = bArr[inIndex]; - if (jchar < 0) { - jchar = jchar & 0x7F; - int tail = remainingBytes[jchar]; - if (tail == -1) { - in.position(inIndex - in.arrayOffset()); - out.position(outIndex - out.arrayOffset()); - return CoderResult.malformedForLength(1); - } - if (inIndexLimit - inIndex < 1 + tail) { - // Apache Tomcat added test - detects invalid sequence as - // early as possible - if (jchar == 0x74 && inIndexLimit > inIndex + 1) { - if ((bArr[inIndex + 1] & 0xFF) > 0x8F) { - return CoderResult.unmappableForLength(4); - } - } - break; - } - for (int i = 0; i < tail; i++) { - int nextByte = bArr[inIndex + i + 1] & 0xFF; - if ((nextByte & 0xC0) != 0x80) { - in.position(inIndex - in.arrayOffset()); - out.position(outIndex - out.arrayOffset()); - return CoderResult.malformedForLength(1 + i); - } - jchar = (jchar << 6) + nextByte; - } - jchar -= remainingNumbers[tail]; - if (jchar < lowerEncodingLimit[tail]) { - // Should have been encoded in fewer octets - in.position(inIndex - in.arrayOffset()); - out.position(outIndex - out.arrayOffset()); - return CoderResult.malformedForLength(1); - } - inIndex += tail; - } - // Apache Tomcat added test - if (jchar >= 0xD800 && jchar <= 0xDFFF) { - return CoderResult.unmappableForLength(3); - } - // Apache Tomcat added test - if (jchar > 0x10FFFF) { - return CoderResult.unmappableForLength(4); - } - if (jchar <= 0xffff) { - cArr[outIndex++] = (char) jchar; - outRemaining--; - } else { - if (outRemaining < 2) { - return CoderResult.OVERFLOW; - } - cArr[outIndex++] = (char) ((jchar >> 0xA) + 0xD7C0); - cArr[outIndex++] = (char) ((jchar & 0x3FF) + 0xDC00); - outRemaining -= 2; - } - } - in.position(inIndex - in.arrayOffset()); - out.position(outIndex - out.arrayOffset()); - return (outRemaining == 0 && inIndex < inIndexLimit) ? CoderResult.OVERFLOW - : CoderResult.UNDERFLOW; - } -" -527,1," public void testBogusPathCheck() { - TesseractOCRConfig config = new TesseractOCRConfig(); - config.setTesseractPath(""blahdeblahblah""); - assertEquals(""blahdeblahblah"", config.getTesseractPath()); - } - - -" -528,1," public void setValues(PreparedStatement ps) throws SQLException { - Timestamp t = new Timestamp(new Date().getTime()); - ps.setTimestamp(1, t); - ps.setString(2, encNewPassword); - ps.setTimestamp(3, t); - ps.setString(4, id); - } - }); -" -529,1," public boolean isTransferException() { - return transferException; - } - - /** - * If enabled and an Exchange failed processing on the consumer side, and if the caused Exception was send back serialized - * in the response as a application/x-java-serialized-object content type. - */ -" -530,1," public void testSingletonPatternInSerialization() { - final Object[] singletones = new Object[] { - CloneTransformer.INSTANCE, - ExceptionTransformer.INSTANCE, - NOPTransformer.INSTANCE, - StringValueTransformer.stringValueTransformer(), - }; - - for (final Object original : singletones) { - TestUtils.assertSameAfterSerialization(""Singleton pattern broken for "" + original.getClass(), original); - } - } - -" -531,1," public static void main( - String[] args) - { - Security.addProvider(new BouncyCastleProvider()); - - runTest(new ECDSA5Test()); - } -" -532,1," public synchronized void afterTest() throws IOException { - wipeDataDirectories(); - randomlyResetClients(); /* reset all clients - each test gets its own client based on the Random instance created above. */ - } - - @Override -" -533,1," public void init(FilterConfig conf) throws ServletException { - if (conf != null && ""zookeeper"".equals(conf.getInitParameter(""signer.secret.provider""))) { - SolrZkClient zkClient = - (SolrZkClient)conf.getServletContext().getAttribute(DELEGATION_TOKEN_ZK_CLIENT); - conf.getServletContext().setAttribute(""signer.secret.provider.zookeeper.curator.client"", - getCuratorClient(zkClient)); - } - super.init(conf); - } - - @Override -" -534,1," protected void setAuthenticateHeader(HttpServletRequest request, - HttpServletResponse response, - LoginConfig config, - String nOnce) { - - // Get the realm name - String realmName = config.getRealmName(); - if (realmName == null) - realmName = REALM_NAME; - - byte[] buffer = null; - synchronized (md5Helper) { - buffer = md5Helper.digest(nOnce.getBytes()); - } - - String authenticateHeader = ""Digest realm=\"""" + realmName + ""\"", "" - + ""qop=\""auth\"", nonce=\"""" + nOnce + ""\"", "" + ""opaque=\"""" - + md5Encoder.encode(buffer) + ""\""""; - response.setHeader(AUTH_HEADER_NAME, authenticateHeader); - - } - - -" -535,1," public static Object deserialize(byte[] data) - throws IOException, ClassNotFoundException - { - ByteArrayInputStream in = new ByteArrayInputStream(data); - ObjectInputStream is = new ObjectInputStream(in); - return is.readObject(); - } - -" -536,1," public FormValidation doCheckCommand(@QueryParameter String value) { - if(Util.fixEmptyAndTrim(value)==null) - return FormValidation.error(Messages.CommandLauncher_NoLaunchCommand()); - else - return FormValidation.ok(); - } - } -} -" -537,1," private static void addUserTriggeringTheBuild(Run run, Set to, - Set cc, Set bcc, EnvVars env, TaskListener listener, RecipientProviderUtilities.IDebug debug) { - - final User user = RecipientProviderUtilities.getUserTriggeringTheBuild(run); - if (user != null) { - RecipientProviderUtilities.addUsers(Collections.singleton(user), listener, env, to, cc, bcc, debug); - } - } - - @SuppressWarnings(""unchecked"") - - - @Extension -" -538,1," protected void finish() throws IOException { - - if (!response.isCommitted()) { - // Validate and write response headers - try { - prepareResponse(); - } catch (IOException e) { - // Set error flag - error = true; - } - } - - if (finished) - return; - - finished = true; - - // Add the end message - if (error) { - output(endAndCloseMessageArray, 0, endAndCloseMessageArray.length); - } else { - output(endMessageArray, 0, endMessageArray.length); - } - } - - - // ------------------------------------- InputStreamInputBuffer Inner Class - - - /** - * This class is an input buffer which will read its data from an input - * stream. - */ -" -539,1," abstract protected JDBCTableReader getTableReader(Connection connection, String tableName, ParseContext parseContext); - -" -540,1," public void testEntityExpansionWReq() throws Exception { - String url = ""https://localhost:"" + getIdpHttpsPort() + ""/fediz-idp/federation?""; - url += ""wa=wsignin1.0""; - url += ""&whr=urn:org:apache:cxf:fediz:idp:realm-A""; - url += ""&wtrealm=urn:org:apache:cxf:fediz:fedizhelloworld""; - String wreply = ""https://localhost:"" + getRpHttpsPort() + ""/"" + getServletContextName() + ""/secure/fedservlet""; - url += ""&wreply="" + wreply; - - InputStream is = this.getClass().getClassLoader().getResource(""entity_wreq.xml"").openStream(); - String entity = IOUtils.toString(is, ""UTF-8""); - is.close(); - String validWreq = - """" - + ""&m;http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV2.0"" - + """"; - - url += ""&wreq="" + URLEncoder.encode(entity + validWreq, ""UTF-8""); - - String user = ""alice""; - String password = ""ecila""; - - final WebClient webClient = new WebClient(); - webClient.getOptions().setUseInsecureSSL(true); - webClient.getCredentialsProvider().setCredentials( - new AuthScope(""localhost"", Integer.parseInt(getIdpHttpsPort())), - new UsernamePasswordCredentials(user, password)); - - webClient.getOptions().setJavaScriptEnabled(false); - try { - webClient.getPage(url); - Assert.fail(""Failure expected on a bad wreq value""); - } catch (FailingHttpStatusCodeException ex) { - Assert.assertEquals(ex.getStatusCode(), 400); - } - - webClient.close(); - } - - // Send an malformed wreq value - @org.junit.Test -" -541,1," public static void checkSlip(File parentFile, File file) throws IllegalArgumentException { - String parentCanonicalPath; - String canonicalPath; - try { - parentCanonicalPath = parentFile.getCanonicalPath(); - canonicalPath = file.getCanonicalPath(); - } catch (IOException e) { - throw new IORuntimeException(e); - } - if (false == canonicalPath.startsWith(parentCanonicalPath)) { - throw new IllegalArgumentException(""New file is outside of the parent dir: "" + file.getName()); - } - } -" -542,1," public ExitCode runWithoutHelp(CommandRunnerParams params) - throws IOException, InterruptedException { - - if (saveFilename != null && loadFilename != null) { - params.getConsole().printErrorText(""Can't use both --load and --save""); - return ExitCode.COMMANDLINE_ERROR; - } - - if (saveFilename != null) { - invalidateChanges(params); - RemoteDaemonicParserState state = params.getParser().storeParserState(params.getCell()); - try (FileOutputStream fos = new FileOutputStream(saveFilename); - ZipOutputStream zipos = new ZipOutputStream(fos)) { - zipos.putNextEntry(new ZipEntry(""parser_data"")); - try (ObjectOutputStream oos = new ObjectOutputStream(zipos)) { - oos.writeObject(state); - } - } - } else if (loadFilename != null) { - try (FileInputStream fis = new FileInputStream(loadFilename); - ZipInputStream zipis = new ZipInputStream(fis)) { - ZipEntry entry = zipis.getNextEntry(); - Preconditions.checkState(entry.getName().equals(""parser_data"")); - try (ObjectInputStream ois = new ObjectInputStream(zipis)) { - RemoteDaemonicParserState state; - try { - state = (RemoteDaemonicParserState) ois.readObject(); - } catch (ClassNotFoundException e) { - params.getConsole().printErrorText(""Invalid file format""); - return ExitCode.COMMANDLINE_ERROR; - } - params.getParser().restoreParserState(state, params.getCell()); - } - } - invalidateChanges(params); - - ParserConfig configView = params.getBuckConfig().getView(ParserConfig.class); - if (configView.isParserCacheMutationWarningEnabled()) { - params - .getConsole() - .printErrorText( - params - .getConsole() - .getAnsi() - .asWarningText( - ""WARNING: Buck injected a parser state that may not match the local state."")); - } - } - - return ExitCode.SUCCESS; - } - -" -543,1," public BeanDefinition createMatcher(String path, String method) { - if ((""/**"".equals(path) || ""**"".equals(path)) && method == null) { - return new RootBeanDefinition(AnyRequestMatcher.class); - } - - BeanDefinitionBuilder matcherBldr = BeanDefinitionBuilder - .rootBeanDefinition(type); - - matcherBldr.addConstructorArgValue(path); - matcherBldr.addConstructorArgValue(method); - - if (this == ciRegex) { - matcherBldr.addConstructorArgValue(true); - } - - return matcherBldr.getBeanDefinition(); - } - -" -544,1," public Collection parse(final InputStream file, final String moduleName) - throws InvocationTargetException { - try { - Digester digester = new Digester(); - digester.setValidating(false); - digester.setClassLoader(LintParser.class.getClassLoader()); - - List issues = new ArrayList(); - digester.push(issues); - - String issueXPath = ""issues/issue""; - digester.addObjectCreate(issueXPath, LintIssue.class); - digester.addSetProperties(issueXPath); - digester.addSetNext(issueXPath, ""add""); - - String locationXPath = issueXPath + ""/location""; - digester.addObjectCreate(locationXPath, Location.class); - digester.addSetProperties(locationXPath); - digester.addSetNext(locationXPath, ""addLocation"", Location.class.getName()); - - digester.parse(file); - - return convert(issues, moduleName); - } catch (IOException exception) { - throw new InvocationTargetException(exception); - } catch (SAXException exception) { - throw new InvocationTargetException(exception); - } - } - - /** - * Converts the Lint object structure to that of the analysis-core API. - * - * @param issues The parsed Lint issues. - * @param moduleName Name of the maven module, if any. - * @return A collection of the discovered issues. - */ -" -545,1," public List removeServer(GerritServer s) { - servers.remove(s); - return servers; - } - - - /** - * Check whether the list of servers contains a GerritServer object of a specific name. - * - * @param serverName to check. - * @return whether the list contains a server with the given name. - */ -" -546,1," public void configure() throws Exception { - from(""direct:start"") - .to(""xslt:org/apache/camel/component/xslt/transform.xsl"") - .multicast() - .beanRef(""testBean"") - .to(""mock:result""); - } - }; - } - - @Override -" -547,1," public void removeUser(String username) { - - UserDatabase database = (UserDatabase) this.resource; - User user = database.findUser(username); - if (user == null) { - return; - } - try { - MBeanUtils.destroyMBean(user); - database.removeUser(user); - } catch (Exception e) { - IllegalArgumentException iae = new IllegalArgumentException - (""Exception destroying user "" + user + "" MBean""); - iae.initCause(e); - throw iae; - } - - } - - -" -548,1," public void execute(FunctionContext context) { - RegionFunctionContext rfc = (RegionFunctionContext) context; - context.getResultSender().lastResult(rfc.getDataSet().size()); - } - -" -549,1," public void execute(FunctionContext context) { - Object[] arguments = (Object[]) context.getArguments(); - String regionName = (String) arguments[0]; - Set keys = (Set) arguments[1]; - if (this.cache.getLogger().fineEnabled()) { - StringBuilder builder = new StringBuilder(); - builder.append(""Function "").append(ID).append("" received request to touch "") - .append(regionName).append(""->"").append(keys); - this.cache.getLogger().fine(builder.toString()); - } - - // Retrieve the appropriate Region and value to update the lastAccessedTime - Region region = this.cache.getRegion(regionName); - if (region != null) { - region.getAll(keys); - } - - // Return result to get around NPE in LocalResultCollectorImpl - context.getResultSender().lastResult(true); - } - -" -550,1," protected Object extractResponseBody(Exchange exchange, JettyContentExchange httpExchange) throws IOException { - Map headers = getSimpleMap(httpExchange.getResponseHeaders()); - String contentType = headers.get(Exchange.CONTENT_TYPE); - - // if content type is serialized java object, then de-serialize it to a Java object - if (contentType != null && HttpConstants.CONTENT_TYPE_JAVA_SERIALIZED_OBJECT.equals(contentType)) { - try { - InputStream is = exchange.getContext().getTypeConverter().mandatoryConvertTo(InputStream.class, httpExchange.getResponseContentBytes()); - return HttpHelper.deserializeJavaObjectFromStream(is, exchange.getContext()); - } catch (Exception e) { - throw new RuntimeCamelException(""Cannot deserialize body to Java object"", e); - } - } else { - // just grab the raw content body - return httpExchange.getBody(); - } - } - -" -551,1," public int doRead(ByteChunk chunk, Request req) throws IOException { - - if (endChunk) { - return -1; - } - - if(needCRLFParse) { - needCRLFParse = false; - parseCRLF(false); - } - - if (remaining <= 0) { - if (!parseChunkHeader()) { - throw new IOException(""Invalid chunk header""); - } - if (endChunk) { - parseEndChunk(); - return -1; - } - } - - int result = 0; - - if (pos >= lastValid) { - if (readBytes() < 0) { - throw new IOException( - ""Unexpected end of stream whilst reading request body""); - } - } - - if (remaining > (lastValid - pos)) { - result = lastValid - pos; - remaining = remaining - result; - chunk.setBytes(buf, pos, result); - pos = lastValid; - } else { - result = remaining; - chunk.setBytes(buf, pos, remaining); - pos = pos + remaining; - remaining = 0; - //we need a CRLF - if ((pos+1) >= lastValid) { - //if we call parseCRLF we overrun the buffer here - //so we defer it to the next call BZ 11117 - needCRLFParse = true; - } else { - parseCRLF(false); //parse the CRLF immediately - } - } - - return result; - } - - - // ---------------------------------------------------- InputFilter Methods - - /** - * Read the content length from the request. - */ - @Override -" -552,1," public FormValidation doNameFreeCheck( - @QueryParameter(""value"") - final String value) { - if (!value.equals(name)) { - if (PluginImpl.containsServer_(value)) { - return FormValidation.error(""The server name "" + value + "" is already in use!""); - } else if (ANY_SERVER.equals(value)) { - return FormValidation.error(""Illegal name "" + value + ""!""); - } else { - return FormValidation.warning(""The server "" + name + "" will be renamed""); - } - } else { - return FormValidation.ok(); - } - } - - /** - * Generates a list of helper objects for the jelly view. - * - * @return a list of helper objects. - */ -" -553,1," public void testPrivateKeyParsingSHA256() - throws IOException, ClassNotFoundException - { - XMSSMTParameters params = new XMSSMTParameters(20, 10, new SHA256Digest()); - XMSSMT mt = new XMSSMT(params, new SecureRandom()); - mt.generateKeys(); - byte[] privateKey = mt.exportPrivateKey(); - byte[] publicKey = mt.exportPublicKey(); - - mt.importState(privateKey, publicKey); - - assertTrue(Arrays.areEqual(privateKey, mt.exportPrivateKey())); - } -" -554,1," public void addOtherTesseractConfig(String key, String value) { - if (key == null) { - throw new IllegalArgumentException(""key must not be null""); - } - if (value == null) { - throw new IllegalArgumentException(""value must not be null""); - } - - Matcher m = ALLOWABLE_OTHER_PARAMS_PATTERN.matcher(key); - if (! m.find()) { - throw new IllegalArgumentException(""Value contains illegal characters: ""+key); - } - m.reset(value); - if (! m.find()) { - throw new IllegalArgumentException(""Value contains illegal characters: ""+value); - } - - otherTesseractConfig.put(key.trim(), value.trim()); - } - - /** - * Get property from the properties file passed in. - * - * @param properties properties file to read from. - * @param property the property to fetch. - * @param defaultMissing default parameter to use. - * @return the value. - */ -" -555,1," public void load(SolrQueryRequest req, SolrQueryResponse rsp, ContentStream stream, UpdateRequestProcessor processor) throws Exception { - final String charset = ContentStreamBase.getCharsetFromContentType(stream.getContentType()); - - InputStream is = null; - XMLStreamReader parser = null; - - String tr = req.getParams().get(CommonParams.TR,null); - if(tr!=null) { - Transformer t = getTransformer(tr,req); - final DOMResult result = new DOMResult(); - - // first step: read XML and build DOM using Transformer (this is no overhead, as XSL always produces - // an internal result DOM tree, we just access it directly as input for StAX): - try { - is = stream.getStream(); - final InputSource isrc = new InputSource(is); - isrc.setEncoding(charset); - final SAXSource source = new SAXSource(isrc); - t.transform(source, result); - } catch(TransformerException te) { - throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, te.getMessage(), te); - } finally { - IOUtils.closeQuietly(is); - } - // second step feed the intermediate DOM tree into StAX parser: - try { - parser = inputFactory.createXMLStreamReader(new DOMSource(result.getNode())); - this.processUpdate(req, processor, parser); - } catch (XMLStreamException e) { - throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, e.getMessage(), e); - } finally { - if (parser != null) parser.close(); - } - } - // Normal XML Loader - else { - try { - is = stream.getStream(); - if (UpdateRequestHandler.log.isTraceEnabled()) { - final byte[] body = IOUtils.toByteArray(is); - // TODO: The charset may be wrong, as the real charset is later - // determined by the XML parser, the content-type is only used as a hint! - UpdateRequestHandler.log.trace(""body"", new String(body, (charset == null) ? - ContentStreamBase.DEFAULT_CHARSET : charset)); - IOUtils.closeQuietly(is); - is = new ByteArrayInputStream(body); - } - parser = (charset == null) ? - inputFactory.createXMLStreamReader(is) : inputFactory.createXMLStreamReader(is, charset); - this.processUpdate(req, processor, parser); - } catch (XMLStreamException e) { - throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, e.getMessage(), e); - } finally { - if (parser != null) parser.close(); - IOUtils.closeQuietly(is); - } - } - } - - - /** Get Transformer from request context, or from TransformerProvider. - * This allows either getContentType(...) or write(...) to instantiate the Transformer, - * depending on which one is called first, then the other one reuses the same Transformer - */ -" -556,1," private SSLEngine createSSLEngine(Map userProperties) - throws DeploymentException { - - try { - // See if a custom SSLContext has been provided - SSLContext sslContext = - (SSLContext) userProperties.get(Constants.SSL_CONTEXT_PROPERTY); - - if (sslContext == null) { - // Create the SSL Context - sslContext = SSLContext.getInstance(""TLS""); - - // Trust store - String sslTrustStoreValue = - (String) userProperties.get(Constants.SSL_TRUSTSTORE_PROPERTY); - if (sslTrustStoreValue != null) { - String sslTrustStorePwdValue = (String) userProperties.get( - Constants.SSL_TRUSTSTORE_PWD_PROPERTY); - if (sslTrustStorePwdValue == null) { - sslTrustStorePwdValue = Constants.SSL_TRUSTSTORE_PWD_DEFAULT; - } - - File keyStoreFile = new File(sslTrustStoreValue); - KeyStore ks = KeyStore.getInstance(""JKS""); - try (InputStream is = new FileInputStream(keyStoreFile)) { - ks.load(is, sslTrustStorePwdValue.toCharArray()); - } - - TrustManagerFactory tmf = TrustManagerFactory.getInstance( - TrustManagerFactory.getDefaultAlgorithm()); - tmf.init(ks); - - sslContext.init(null, tmf.getTrustManagers(), null); - } else { - sslContext.init(null, null, null); - } - } - - SSLEngine engine = sslContext.createSSLEngine(); - - String sslProtocolsValue = - (String) userProperties.get(Constants.SSL_PROTOCOLS_PROPERTY); - if (sslProtocolsValue != null) { - engine.setEnabledProtocols(sslProtocolsValue.split("","")); - } - - engine.setUseClientMode(true); - - return engine; - } catch (Exception e) { - throw new DeploymentException(sm.getString( - ""wsWebSocketContainer.sslEngineFail""), e); - } - } - - - @Override -" -557,1," private AsymmetricCipherKeyPair genKeyPair() - { - if (!initialized) - { - initializeDefault(); - } - - // initialize authenticationPaths and treehash instances - byte[][][] currentAuthPaths = new byte[numLayer][][]; - byte[][][] nextAuthPaths = new byte[numLayer - 1][][]; - Treehash[][] currentTreehash = new Treehash[numLayer][]; - Treehash[][] nextTreehash = new Treehash[numLayer - 1][]; - - Vector[] currentStack = new Vector[numLayer]; - Vector[] nextStack = new Vector[numLayer - 1]; - - Vector[][] currentRetain = new Vector[numLayer][]; - Vector[][] nextRetain = new Vector[numLayer - 1][]; - - for (int i = 0; i < numLayer; i++) - { - currentAuthPaths[i] = new byte[heightOfTrees[i]][mdLength]; - currentTreehash[i] = new Treehash[heightOfTrees[i] - K[i]]; - - if (i > 0) - { - nextAuthPaths[i - 1] = new byte[heightOfTrees[i]][mdLength]; - nextTreehash[i - 1] = new Treehash[heightOfTrees[i] - K[i]]; - } - - currentStack[i] = new Vector(); - if (i > 0) - { - nextStack[i - 1] = new Vector(); - } - } - - // initialize roots - byte[][] currentRoots = new byte[numLayer][mdLength]; - byte[][] nextRoots = new byte[numLayer - 1][mdLength]; - // initialize seeds - byte[][] seeds = new byte[numLayer][mdLength]; - // initialize seeds[] by copying starting-seeds of first trees of each - // layer - for (int i = 0; i < numLayer; i++) - { - System.arraycopy(currentSeeds[i], 0, seeds[i], 0, mdLength); - } - - // initialize rootSigs - currentRootSigs = new byte[numLayer - 1][mdLength]; - - // ------------------------- - // ------------------------- - // --- calculation of current authpaths and current rootsigs (AUTHPATHS, - // SIG)------ - // from bottom up to the root - for (int h = numLayer - 1; h >= 0; h--) - { - GMSSRootCalc tree = new GMSSRootCalc(this.heightOfTrees[h], this.K[h], digestProvider); - try - { - // on lowest layer no lower root is available, so just call - // the method with null as first parameter - if (h == numLayer - 1) - { - tree = this.generateCurrentAuthpathAndRoot(null, currentStack[h], seeds[h], h); - } - else - // otherwise call the method with the former computed root - // value - { - tree = this.generateCurrentAuthpathAndRoot(currentRoots[h + 1], currentStack[h], seeds[h], h); - } - - } - catch (Exception e1) - { - e1.printStackTrace(); - } - - // set initial values needed for the private key construction - for (int i = 0; i < heightOfTrees[h]; i++) - { - System.arraycopy(tree.getAuthPath()[i], 0, currentAuthPaths[h][i], 0, mdLength); - } - currentRetain[h] = tree.getRetain(); - currentTreehash[h] = tree.getTreehash(); - System.arraycopy(tree.getRoot(), 0, currentRoots[h], 0, mdLength); - } - - // --- calculation of next authpaths and next roots (AUTHPATHS+, ROOTS+) - // ------ - for (int h = numLayer - 2; h >= 0; h--) - { - GMSSRootCalc tree = this.generateNextAuthpathAndRoot(nextStack[h], seeds[h + 1], h + 1); - - // set initial values needed for the private key construction - for (int i = 0; i < heightOfTrees[h + 1]; i++) - { - System.arraycopy(tree.getAuthPath()[i], 0, nextAuthPaths[h][i], 0, mdLength); - } - nextRetain[h] = tree.getRetain(); - nextTreehash[h] = tree.getTreehash(); - System.arraycopy(tree.getRoot(), 0, nextRoots[h], 0, mdLength); - - // create seed for the Merkle tree after next (nextNextSeeds) - // SEEDs++ - System.arraycopy(seeds[h + 1], 0, this.nextNextSeeds[h], 0, mdLength); - } - // ------------ - - // generate JDKGMSSPublicKey - GMSSPublicKeyParameters publicKey = new GMSSPublicKeyParameters(currentRoots[0], gmssPS); - - // generate the JDKGMSSPrivateKey - GMSSPrivateKeyParameters privateKey = new GMSSPrivateKeyParameters(currentSeeds, nextNextSeeds, currentAuthPaths, - nextAuthPaths, currentTreehash, nextTreehash, currentStack, nextStack, currentRetain, nextRetain, nextRoots, currentRootSigs, gmssPS, digestProvider); - - // return the KeyPair - return (new AsymmetricCipherKeyPair(publicKey, privateKey)); - } - - /** - * calculates the authpath for tree in layer h which starts with seed[h] - * additionally computes the rootSignature of underlaying root - * - * @param currentStack stack used for the treehash instance created by this method - * @param lowerRoot stores the root of the lower tree - * @param seed starting seeds - * @param h actual layer - */ -" -558,1," private void sendEntityMessage(Object message) throws Exception { - - MockEndpoint endpoint = getMockEndpoint(""mock:result""); - endpoint.reset(); - endpoint.expectedMessageCount(1); - - template.sendBody(""direct:start1"", message); - - assertMockEndpointsSatisfied(); - - List list = endpoint.getReceivedExchanges(); - Exchange exchange = list.get(0); - String xml = exchange.getIn().getBody(String.class); - assertTrue(""Get a wrong transformed message"", xml.indexOf("""") > 0); - - - - try { - template.sendBody(""direct:start2"", message); - fail(""Expect an exception here""); - } catch (Exception ex) { - // expect an exception here - assertTrue(""Get a wrong exception"", ex instanceof CamelExecutionException); - // the file could not be found - assertTrue(""Get a wrong exception cause"", ex.getCause() instanceof TransformerException); - } - - } - - - @Override -" -559,1," public static String getContextPath(HttpServletRequest request) { - String contextPath = (String) request.getAttribute(INCLUDE_CONTEXT_PATH_ATTRIBUTE); - if (contextPath == null) { - contextPath = request.getContextPath(); - } - if (""/"".equals(contextPath)) { - // Invalid case, but happens for includes on Jetty: silently adapt it. - contextPath = """"; - } - return decodeRequestString(request, contextPath); - } - - /** - * Find the Shiro {@link WebEnvironment} for this web application, which is typically loaded via the - * {@link org.apache.shiro.web.env.EnvironmentLoaderListener}. - *

- * This implementation rethrows an exception that happened on environment startup to differentiate between a failed - * environment startup and no environment at all. - * - * @param sc ServletContext to find the web application context for - * @return the root WebApplicationContext for this web app - * @throws IllegalStateException if the root WebApplicationContext could not be found - * @see org.apache.shiro.web.env.EnvironmentLoader#ENVIRONMENT_ATTRIBUTE_KEY - * @since 1.2 - */ -" -560,1," private void doTestRewrite(String config, String request, String expectedURI) throws Exception { - Tomcat tomcat = getTomcatInstance(); - - // No file system docBase required - Context ctx = tomcat.addContext("""", null); - - RewriteValve rewriteValve = new RewriteValve(); - ctx.getPipeline().addValve(rewriteValve); - - rewriteValve.setConfiguration(config); - - // Note: URLPatterns should be URL encoded - // (http://svn.apache.org/r285186) - Tomcat.addServlet(ctx, ""snoop"", new SnoopServlet()); - ctx.addServletMapping(""/a/%255A"", ""snoop""); - ctx.addServletMapping(""/c/*"", ""snoop""); - - tomcat.start(); - - ByteChunk res = getUrl(""http://localhost:"" + getPort() + request); - - String body = res.toString(); - RequestDescriptor requestDesc = SnoopResult.parse(body); - String requestURI = requestDesc.getRequestInfo(""REQUEST-URI""); - Assert.assertEquals(expectedURI, requestURI); - } -" -561,1," public Result isAllowed(String principalId) { - LockoutPolicy lockoutPolicy = lockoutPolicyRetriever.getLockoutPolicy(); - - if (!lockoutPolicy.isLockoutEnabled()) { - return new Result(true, 0); - } - - long eventsAfter = timeService.getCurrentTimeMillis() - lockoutPolicy.getCountFailuresWithin() * 1000; - List events = auditService.find(principalId, eventsAfter); - - final int failureCount = sequentialFailureCount(events); - - if (failureCount >= lockoutPolicy.getLockoutAfterFailures()) { - // Check whether time of most recent failure is within the lockout period - AuditEvent lastFailure = mostRecentFailure(events); - if (lastFailure != null && lastFailure.getTime() > timeService.getCurrentTimeMillis() - lockoutPolicy.getLockoutPeriodSeconds() * 1000) { - return new Result(false, failureCount); - } - } - return new Result(true, failureCount); - } - - /** - * Counts the number of failures that occurred without an intervening - * successful login. - */ -" -562,1," public void save() throws Exception { - - if (getReadonly()) { - log.error(sm.getString(""memoryUserDatabase.readOnly"")); - return; - } - - if (!isWriteable()) { - log.warn(sm.getString(""memoryUserDatabase.notPersistable"")); - return; - } - - // Write out contents to a temporary file - File fileNew = new File(pathnameNew); - if (!fileNew.isAbsolute()) { - fileNew = - new File(System.getProperty(Globals.CATALINA_BASE_PROP), pathnameNew); - } - PrintWriter writer = null; - try { - - // Configure our PrintWriter - FileOutputStream fos = new FileOutputStream(fileNew); - OutputStreamWriter osw = new OutputStreamWriter(fos, ""UTF8""); - writer = new PrintWriter(osw); - - // Print the file prolog - writer.println(""""); - writer.println(""""); - - // Print entries for each defined role, group, and user - Iterator values = null; - values = getRoles(); - while (values.hasNext()) { - writer.print("" ""); - writer.println(values.next()); - } - values = getGroups(); - while (values.hasNext()) { - writer.print("" ""); - writer.println(values.next()); - } - values = getUsers(); - while (values.hasNext()) { - writer.print("" ""); - writer.println(values.next()); - } - - // Print the file epilog - writer.println(""""); - - // Check for errors that occurred while printing - if (writer.checkError()) { - writer.close(); - fileNew.delete(); - throw new IOException - (sm.getString(""memoryUserDatabase.writeException"", - fileNew.getAbsolutePath())); - } - writer.close(); - } catch (IOException e) { - if (writer != null) { - writer.close(); - } - fileNew.delete(); - throw e; - } - - // Perform the required renames to permanently save this file - File fileOld = new File(pathnameOld); - if (!fileOld.isAbsolute()) { - fileOld = - new File(System.getProperty(Globals.CATALINA_BASE_PROP), pathnameOld); - } - fileOld.delete(); - File fileOrig = new File(pathname); - if (!fileOrig.isAbsolute()) { - fileOrig = - new File(System.getProperty(Globals.CATALINA_BASE_PROP), pathname); - } - if (fileOrig.exists()) { - fileOld.delete(); - if (!fileOrig.renameTo(fileOld)) { - throw new IOException - (sm.getString(""memoryUserDatabase.renameOld"", - fileOld.getAbsolutePath())); - } - } - if (!fileNew.renameTo(fileOrig)) { - if (fileOld.exists()) { - fileOld.renameTo(fileOrig); - } - throw new IOException - (sm.getString(""memoryUserDatabase.renameNew"", - fileOrig.getAbsolutePath())); - } - fileOld.delete(); - - } - - - /** - * Return a String representation of this UserDatabase. - */ - @Override -" -563,1," public static boolean configSuccess(HierarchicalConfiguration reply) { - if (reply != null) { - if (reply.containsKey(""ok"")) { - return true; - } - } - return false; - } -" -564,1," public void process(Exchange exchange) throws Exception { -" -565,1," public boolean createDB(String dbName, PortletRequest request) { - Connection conn = null; - try { - conn = DerbyConnectionUtil.getDerbyConnection(dbName, - DerbyConnectionUtil.CREATE_DB_PROP); - portlet.addInfoMessage(request, portlet.getLocalizedString(request, ""sysdb.infoMsg01"", dbName)); - return true; - } catch (Throwable e) { - portlet.addErrorMessage(request, portlet.getLocalizedString(request, ""sysdb.errorMsg01""), e.getMessage()); - return false; - } finally { - // close DB connection - try { - if (conn != null) { - conn.close(); - } - } catch (SQLException e) { - portlet.addErrorMessage(request, portlet.getLocalizedString(request, ""sysdb.errorMsg02""), e.getMessage()); - } - } - } - -" -566,1," public UnixUser authenticate(String username, String password) throws PAMException { - this.password = password; - try { - check(libpam.pam_set_item(pht,PAM_USER,username),""pam_set_item failed""); - check(libpam.pam_authenticate(pht,0),""pam_authenticate failed""); - check(libpam.pam_setcred(pht,0),""pam_setcred failed""); - // several different error code seem to be used to represent authentication failures -// check(libpam.pam_acct_mgmt(pht,0),""pam_acct_mgmt failed""); - - PointerByReference r = new PointerByReference(); - check(libpam.pam_get_item(pht,PAM_USER,r),""pam_get_item failed""); - String userName = r.getValue().getString(0); - passwd pwd = libc.getpwnam(userName); - if(pwd==null) - throw new PAMException(""Authentication succeeded but no user information is available""); - return new UnixUser(userName,pwd); - } finally { - this.password = null; - } - } - - /** - * Returns the groups a user belongs to - * @param username - * @return Set of group names - * @throws PAMException - * @deprecated - * Pointless and ugly convenience method. - */ -" -567,1," public void serveImage(ResourceRequest req, ResourceResponse resp) throws IOException { - String fn = req.getRenderParameters().getValue(""fn""); - String ct = req.getRenderParameters().getValue(""ct""); - - resp.setContentType(ct); - - String path = req.getPortletContext().getRealPath(fn); - File file = new File(path); - OutputStream os = resp.getPortletOutputStream(); - Files.copy(file.toPath(), os); - os.flush(); - } -" -568,1," public Http11NioProcessor createProcessor() { - Http11NioProcessor processor = new Http11NioProcessor( - proto.getMaxHttpHeaderSize(), (NioEndpoint)proto.endpoint, - proto.getMaxTrailerSize()); - processor.setAdapter(proto.getAdapter()); - processor.setMaxKeepAliveRequests(proto.getMaxKeepAliveRequests()); - processor.setKeepAliveTimeout(proto.getKeepAliveTimeout()); - processor.setConnectionUploadTimeout( - proto.getConnectionUploadTimeout()); - processor.setDisableUploadTimeout(proto.getDisableUploadTimeout()); - processor.setCompressionMinSize(proto.getCompressionMinSize()); - processor.setCompression(proto.getCompression()); - processor.setNoCompressionUserAgents(proto.getNoCompressionUserAgents()); - processor.setCompressableMimeTypes(proto.getCompressableMimeTypes()); - processor.setRestrictedUserAgents(proto.getRestrictedUserAgents()); - processor.setSocketBuffer(proto.getSocketBuffer()); - processor.setMaxSavePostSize(proto.getMaxSavePostSize()); - processor.setServer(proto.getServer()); - register(processor); - return processor; - } - - @Override -" -569,1," public Document getMetaData(Idp config, TrustedIdp serviceConfig) throws ProcessingException { - - try { - Crypto crypto = CertsUtils.createCrypto(config.getCertificate()); - - ByteArrayOutputStream bout = new ByteArrayOutputStream(4096); - Writer streamWriter = new OutputStreamWriter(bout, ""UTF-8""); - XMLStreamWriter writer = XML_OUTPUT_FACTORY.createXMLStreamWriter(streamWriter); - - writer.writeStartDocument(""UTF-8"", ""1.0""); - - String referenceID = IDGenerator.generateID(""_""); - writer.writeStartElement(""md"", ""EntityDescriptor"", SAML2_METADATA_NS); - writer.writeAttribute(""ID"", referenceID); - - String serviceURL = config.getIdpUrl().toString(); - 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 (""http://docs.oasis-open.org/wsfed/federation/200706"".equals(serviceConfig.getProtocol())) { - writeFederationMetadata(writer, serviceConfig, serviceURL); - } else if (""urn:oasis:names:tc:SAML:2.0:profiles:SSO:browser"".equals(serviceConfig.getProtocol())) { - writeSAMLMetadata(writer, serviceConfig, serviceURL, crypto); - } - - 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()); - - Document result = SignatureUtils.signMetaInfo(crypto, null, config.getCertificatePassword(), is, referenceID); - if (result != null) { - return result; - } else { - throw new RuntimeException(""Failed to sign the metadata document: result=null""); - } - } 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()); - } - - } - -" -570,1," public void send(final String format, final Object... args) { - descriptor.debug(logger, format, args); - } - } - final Debug debug = new Debug(); - - Set users = null; - - final Run currentRun = context.getRun(); - if (currentRun == null) { - debug.send(""currentRun was null""); - } else { - final AbstractTestResultAction testResultAction = currentRun.getAction(AbstractTestResultAction.class); - if (testResultAction == null) { - debug.send(""testResultAction was null""); - } else { - if (testResultAction.getFailCount() <= 0) { - debug.send(""getFailCount() returned <= 0""); - } else { - users = new HashSet<>(); - debug.send(""Collecting builds where a test started failing...""); - final HashSet> buildsWhereATestStartedFailing = new HashSet<>(); - for (final TestResult caseResult : testResultAction.getFailedTests()) { - final Run runWhereTestStartedFailing = caseResult.getFailedSinceRun(); - if (runWhereTestStartedFailing != null) { - debug.send("" runWhereTestStartedFailing: %d"", runWhereTestStartedFailing.getNumber()); - buildsWhereATestStartedFailing.add(runWhereTestStartedFailing); - } else { - context.getListener().error(""getFailedSinceRun returned null for %s"", caseResult.getFullDisplayName()); - } - } - // For each build where a test started failing, walk backward looking for build results worse than - // UNSTABLE. All of those builds will be used to find suspects. - debug.send(""Collecting builds with suspects...""); - final HashSet> buildsWithSuspects = new HashSet<>(); - for (final Run buildWhereATestStartedFailing : buildsWhereATestStartedFailing) { - debug.send("" buildWhereATestStartedFailing: %d"", buildWhereATestStartedFailing.getNumber()); - buildsWithSuspects.add(buildWhereATestStartedFailing); - Run previousBuildToCheck = buildWhereATestStartedFailing.getPreviousCompletedBuild(); - if (previousBuildToCheck != null) { - debug.send("" previousBuildToCheck: %d"", previousBuildToCheck.getNumber()); - } - while (previousBuildToCheck != null) { - if (buildsWithSuspects.contains(previousBuildToCheck)) { - // Short-circuit if the build to check has already been checked. - debug.send("" already contained in buildsWithSuspects; stopping search""); - break; - } - final Result previousResult = previousBuildToCheck.getResult(); - if (previousResult == null) { - debug.send("" previousResult was null""); - } else { - debug.send("" previousResult: %s"", previousResult.toString()); - if (previousResult.isBetterThan(Result.FAILURE)) { - debug.send("" previousResult was better than FAILURE; stopping search""); - break; - } else { - debug.send("" previousResult was not better than FAILURE; adding to buildsWithSuspects; continuing search""); - buildsWithSuspects.add(previousBuildToCheck); - previousBuildToCheck = previousBuildToCheck.getPreviousCompletedBuild(); - if (previousBuildToCheck != null) { - debug.send("" previousBuildToCheck: %d"", previousBuildToCheck.getNumber()); - } - } - } - } - } - debug.send(""Collecting suspects...""); - users.addAll(RecipientProviderUtilities.getChangeSetAuthors(buildsWithSuspects, debug)); - users.addAll(RecipientProviderUtilities.getUsersTriggeringTheBuilds(buildsWithSuspects, debug)); - } - } - } - - if (users != null) { - RecipientProviderUtilities.addUsers(users, context.getListener(), env, to, cc, bcc, debug); - } - } - - @Extension - public static final class DescriptorImpl extends RecipientProviderDescriptor { - @Override - public String getDisplayName() { - return ""Suspects Causing Unit Tests to Begin Failing""; - } - } - -} -" -571,1," public SocketState process(SocketWrapper socket) - throws IOException { - RequestInfo rp = request.getRequestProcessor(); - rp.setStage(org.apache.coyote.Constants.STAGE_PARSE); - - // Setting up the socket - this.socket = socket; - long socketRef = socket.getSocket().longValue(); - Socket.setrbb(socketRef, inputBuffer); - Socket.setsbb(socketRef, outputBuffer); - - // Error flag - error = false; - - boolean keptAlive = false; - - while (!error && !endpoint.isPaused()) { - - // Parsing the request header - try { - // Get first message of the request - if (!readMessage(requestHeaderMessage, true, keptAlive)) { - // This means that no data is available right now - // (long keepalive), so that the processor should be recycled - // and the method should return true - break; - } - // Check message type, process right away and break if - // not regular request processing - int type = requestHeaderMessage.getByte(); - if (type == Constants.JK_AJP13_CPING_REQUEST) { - if (Socket.send(socketRef, pongMessageArray, 0, - pongMessageArray.length) < 0) { - error = true; - } - continue; - } else if(type != Constants.JK_AJP13_FORWARD_REQUEST) { - // Usually the servlet didn't read the previous request body - if(log.isDebugEnabled()) { - log.debug(""Unexpected message: ""+type); - } - continue; - } - - keptAlive = true; - request.setStartTime(System.currentTimeMillis()); - } catch (IOException e) { - error = true; - break; - } catch (Throwable t) { - ExceptionUtils.handleThrowable(t); - log.debug(sm.getString(""ajpprocessor.header.error""), t); - // 400 - Bad Request - response.setStatus(400); - adapter.log(request, response, 0); - error = true; - } - - if (!error) { - // Setting up filters, and parse some request headers - rp.setStage(org.apache.coyote.Constants.STAGE_PREPARE); - try { - prepareRequest(); - } catch (Throwable t) { - ExceptionUtils.handleThrowable(t); - log.debug(sm.getString(""ajpprocessor.request.prepare""), t); - // 400 - Internal Server Error - response.setStatus(400); - adapter.log(request, response, 0); - error = true; - } - } - - // Process the request in the adapter - if (!error) { - try { - rp.setStage(org.apache.coyote.Constants.STAGE_SERVICE); - adapter.service(request, response); - } catch (InterruptedIOException e) { - error = true; - } catch (Throwable t) { - ExceptionUtils.handleThrowable(t); - log.error(sm.getString(""ajpprocessor.request.process""), t); - // 500 - Internal Server Error - response.setStatus(500); - adapter.log(request, response, 0); - error = true; - } - } - - if (isAsync() && !error) { - break; - } - - // Finish the response if not done yet - if (!finished) { - try { - finish(); - } catch (Throwable t) { - ExceptionUtils.handleThrowable(t); - error = true; - } - } - - // If there was an error, make sure the request is counted as - // and error, and update the statistics counter - if (error) { - response.setStatus(500); - } - request.updateCounters(); - - rp.setStage(org.apache.coyote.Constants.STAGE_KEEPALIVE); - recycle(false); - } - - rp.setStage(org.apache.coyote.Constants.STAGE_ENDED); - - if (error || endpoint.isPaused()) { - return SocketState.CLOSED; - } else if (isAsync()) { - return SocketState.LONG; - } else { - return SocketState.OPEN; - } - } - - - // ----------------------------------------------------- ActionHook Methods - - - /** - * Send an action to the connector. - * - * @param actionCode Type of the action - * @param param Action parameter - */ - @Override -" -572,1," public void testRedirectActionPrefixWithEmptyExtension() throws Exception { - Map parameterMap = new HashMap(); - parameterMap.put(DefaultActionMapper.REDIRECT_ACTION_PREFIX + ""myAction"", """"); - - StrutsMockHttpServletRequest request = new StrutsMockHttpServletRequest(); - request.setupGetServletPath(""/someServletPath""); - request.setParameterMap(parameterMap); - - DefaultActionMapper defaultActionMapper = new DefaultActionMapper(); - defaultActionMapper.setContainer(container); - defaultActionMapper.setExtensions("",,""); - ActionMapping actionMapping = defaultActionMapper.getMapping(request, configManager); - - - StrutsResultSupport result = (StrutsResultSupport) actionMapping.getResult(); - assertNotNull(result); - assertTrue(result instanceof ServletRedirectResult); - - assertEquals(""myAction"", result.getLocation()); - - // TODO: need to test location but there's noaccess to the property/method, unless we use reflection - } - -" -573,1," public static void assertSettings(Settings left, Settings right, boolean compareClusterName) { - ImmutableSet> entries0 = left.getAsMap().entrySet(); - Map entries1 = right.getAsMap(); - assertThat(entries0.size(), equalTo(entries1.size())); - for (Map.Entry entry : entries0) { - if(entry.getKey().equals(ClusterName.SETTING) && compareClusterName == false) { - continue; - } - assertThat(entries1, hasEntry(entry.getKey(), entry.getValue())); - } - } - -" -574,1," protected void service(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException { - log.trace(""Service: {}"", request); - - // is there a consumer registered for the request. - HttpConsumer consumer = getServletResolveConsumerStrategy().resolve(request, getConsumers()); - if (consumer == null) { - response.sendError(HttpServletResponse.SC_NOT_FOUND); - return; - } - - if (consumer.getEndpoint().getHttpMethodRestrict() != null) { - Iterator it = ObjectHelper.createIterable(consumer.getEndpoint().getHttpMethodRestrict()).iterator(); - boolean match = false; - while (it.hasNext()) { - String method = it.next().toString(); - if (method.equalsIgnoreCase(request.getMethod())) { - match = true; - break; - } - } - if (!match) { - response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED); - return; - } - } - - if (""TRACE"".equals(request.getMethod()) && !consumer.isTraceEnabled()) { - response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED); - return; - } - - final Exchange result = (Exchange) request.getAttribute(EXCHANGE_ATTRIBUTE_NAME); - if (result == null) { - // no asynchronous result so leverage continuation - final Continuation continuation = ContinuationSupport.getContinuation(request); - if (continuation.isInitial() && continuationTimeout != null) { - // set timeout on initial - continuation.setTimeout(continuationTimeout); - } - - // are we suspended and a request is dispatched initially? - if (consumer.isSuspended() && continuation.isInitial()) { - response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); - return; - } - - if (continuation.isExpired()) { - String id = (String) continuation.getAttribute(EXCHANGE_ATTRIBUTE_ID); - // remember this id as expired - expiredExchanges.put(id, id); - log.warn(""Continuation expired of exchangeId: {}"", id); - response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); - return; - } - - // a new request so create an exchange - final Exchange exchange = new DefaultExchange(consumer.getEndpoint(), ExchangePattern.InOut); - - if (consumer.getEndpoint().isBridgeEndpoint()) { - exchange.setProperty(Exchange.SKIP_GZIP_ENCODING, Boolean.TRUE); - exchange.setProperty(Exchange.SKIP_WWW_FORM_URLENCODED, Boolean.TRUE); - } - if (consumer.getEndpoint().isDisableStreamCache()) { - exchange.setProperty(Exchange.DISABLE_HTTP_STREAM_CACHE, Boolean.TRUE); - } - - HttpHelper.setCharsetFromContentType(request.getContentType(), exchange); - - exchange.setIn(new HttpMessage(exchange, request, response)); - // set context path as header - String contextPath = consumer.getEndpoint().getPath(); - exchange.getIn().setHeader(""CamelServletContextPath"", contextPath); - - String httpPath = (String)exchange.getIn().getHeader(Exchange.HTTP_PATH); - // here we just remove the CamelServletContextPath part from the HTTP_PATH - if (contextPath != null - && httpPath.startsWith(contextPath)) { - exchange.getIn().setHeader(Exchange.HTTP_PATH, - httpPath.substring(contextPath.length())); - } - - if (log.isTraceEnabled()) { - log.trace(""Suspending continuation of exchangeId: {}"", exchange.getExchangeId()); - } - continuation.setAttribute(EXCHANGE_ATTRIBUTE_ID, exchange.getExchangeId()); - - // we want to handle the UoW - try { - consumer.createUoW(exchange); - } catch (Exception e) { - log.error(""Error processing request"", e); - throw new ServletException(e); - } - - // must suspend before we process the exchange - continuation.suspend(); - - ClassLoader oldTccl = overrideTccl(exchange); - - if (log.isTraceEnabled()) { - log.trace(""Processing request for exchangeId: {}"", exchange.getExchangeId()); - } - // use the asynchronous API to process the exchange - - consumer.getAsyncProcessor().process(exchange, new AsyncCallback() { - public void done(boolean doneSync) { - // check if the exchange id is already expired - boolean expired = expiredExchanges.remove(exchange.getExchangeId()) != null; - if (!expired) { - if (log.isTraceEnabled()) { - log.trace(""Resuming continuation of exchangeId: {}"", exchange.getExchangeId()); - } - // resume processing after both, sync and async callbacks - continuation.setAttribute(EXCHANGE_ATTRIBUTE_NAME, exchange); - continuation.resume(); - } else { - log.warn(""Cannot resume expired continuation of exchangeId: {}"", exchange.getExchangeId()); - } - } - }); - - if (oldTccl != null) { - restoreTccl(exchange, oldTccl); - } - - // return to let Jetty continuation to work as it will resubmit and invoke the service - // method again when its resumed - return; - } - - try { - // now lets output to the response - if (log.isTraceEnabled()) { - log.trace(""Resumed continuation and writing response for exchangeId: {}"", result.getExchangeId()); - } - Integer bs = consumer.getEndpoint().getResponseBufferSize(); - if (bs != null) { - log.trace(""Using response buffer size: {}"", bs); - response.setBufferSize(bs); - } - consumer.getBinding().writeResponse(result, response); - } catch (IOException e) { - log.error(""Error processing request"", e); - throw e; - } catch (Exception e) { - log.error(""Error processing request"", e); - throw new ServletException(e); - } finally { - consumer.doneUoW(result); - } - } - -" -575,1," protected void submit(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException, FormException { - super.submit(req,rsp); - JSONObject json = req.getSubmittedForm(); - - makeDisabled(req.getParameter(""disable"")!=null); - - jdk = req.getParameter(""jdk""); - if(req.getParameter(""hasCustomQuietPeriod"")!=null) { - quietPeriod = Integer.parseInt(req.getParameter(""quiet_period"")); - } else { - quietPeriod = null; - } - if(req.getParameter(""hasCustomScmCheckoutRetryCount"")!=null) { - scmCheckoutRetryCount = Integer.parseInt(req.getParameter(""scmCheckoutRetryCount"")); - } else { - scmCheckoutRetryCount = null; - } - blockBuildWhenDownstreamBuilding = req.getParameter(""blockBuildWhenDownstreamBuilding"")!=null; - blockBuildWhenUpstreamBuilding = req.getParameter(""blockBuildWhenUpstreamBuilding"")!=null; - - if(req.hasParameter(""customWorkspace"")) { - customWorkspace = Util.fixEmptyAndTrim(req.getParameter(""customWorkspace.directory"")); - } else { - customWorkspace = null; - } - - if (json.has(""scmCheckoutStrategy"")) - scmCheckoutStrategy = req.bindJSON(SCMCheckoutStrategy.class, - json.getJSONObject(""scmCheckoutStrategy"")); - else - scmCheckoutStrategy = null; - - - if(req.getParameter(""hasSlaveAffinity"")!=null) { - assignedNode = Util.fixEmptyAndTrim(req.getParameter(""_.assignedLabelString"")); - } else { - assignedNode = null; - } - canRoam = assignedNode==null; - - concurrentBuild = req.getSubmittedForm().has(""concurrentBuild""); - - authToken = BuildAuthorizationToken.create(req); - - setScm(SCMS.parseSCM(req,this)); - - for (Trigger t : triggers()) - t.stop(); - triggers = buildDescribable(req, Trigger.for_(this)); - for (Trigger t : triggers) - t.start(this,true); - - for (Publisher _t : Descriptor.newInstancesFromHeteroList(req, json, ""publisher"", Jenkins.getInstance().getExtensionList(BuildTrigger.DescriptorImpl.class))) { - BuildTrigger t = (BuildTrigger) _t; - for (AbstractProject downstream : t.getChildProjects(this)) { - downstream.checkPermission(BUILD); - } - } - } - - /** - * @deprecated - * As of 1.261. Use {@link #buildDescribable(StaplerRequest, List)} instead. - */ -" -576,1," private JMXConnectorServer createServer(String serverName, - String bindAddress, int theRmiRegistryPort, int theRmiServerPort, - HashMap theEnv, - RMIClientSocketFactory registryCsf, RMIServerSocketFactory registrySsf, - RMIClientSocketFactory serverCsf, RMIServerSocketFactory serverSsf) { - - // Create the RMI registry - Registry registry; - try { - registry = LocateRegistry.createRegistry( - theRmiRegistryPort, registryCsf, registrySsf); - } catch (RemoteException e) { - log.error(sm.getString( - ""jmxRemoteLifecycleListener.createRegistryFailed"", - serverName, Integer.toString(theRmiRegistryPort)), e); - return null; - } - - if (bindAddress == null) { - bindAddress = ""localhost""; - } - - String url = ""service:jmx:rmi://"" + bindAddress; - JMXServiceURL serviceUrl; - try { - serviceUrl = new JMXServiceURL(url); - } catch (MalformedURLException e) { - log.error(sm.getString(""jmxRemoteLifecycleListener.invalidURL"", serverName, url), e); - return null; - } - - RMIConnectorServer cs = null; - try { - RMIJRMPServerImpl server = new RMIJRMPServerImpl( - rmiServerPortPlatform, serverCsf, serverSsf, theEnv); - cs = new RMIConnectorServer(serviceUrl, theEnv, server, - ManagementFactory.getPlatformMBeanServer()); - cs.start(); - registry.bind(""jmxrmi"", server); - log.info(sm.getString(""jmxRemoteLifecycleListener.start"", - Integer.toString(theRmiRegistryPort), - Integer.toString(theRmiServerPort), serverName)); - } catch (IOException | AlreadyBoundException e) { - log.error(sm.getString( - ""jmxRemoteLifecycleListener.createServerFailed"", - serverName), e); - } - return cs; - } - - -" -577,1," private void decodeTest() - { - EllipticCurve curve = new EllipticCurve( - new ECFieldFp(new BigInteger(""6277101735386680763835789423207666416083908700390324961279"")), // q - new BigInteger(""fffffffffffffffffffffffffffffffefffffffffffffffc"", 16), // a - new BigInteger(""64210519e59c80e70fa7e9ab72243049feb8deecc146b9b1"", 16)); // b - - ECPoint p = ECPointUtil.decodePoint(curve, Hex.decode(""03188da80eb03090f67cbf20eb43a18800f4ff0afd82ff1012"")); - - if (!p.getAffineX().equals(new BigInteger(""188da80eb03090f67cbf20eb43a18800f4ff0afd82ff1012"", 16))) - { - fail(""x uncompressed incorrectly""); - } - - if (!p.getAffineY().equals(new BigInteger(""7192b95ffc8da78631011ed6b24cdd573f977a11e794811"", 16))) - { - fail(""y uncompressed incorrectly""); - } - } - - /** - * X9.62 - 1998,
- * J.3.2, Page 155, ECDSA over the field Fp
- * an example with 239 bit prime - */ -" -578,1," private CipherText convertToCipherText(byte[] cipherTextSerializedBytes) - throws EncryptionException - { - try { - assert cipherTextSerializedBytes != null : ""cipherTextSerializedBytes cannot be null.""; - assert cipherTextSerializedBytes.length > 0 : ""cipherTextSerializedBytes must be > 0 in length.""; - ByteArrayInputStream bais = new ByteArrayInputStream(cipherTextSerializedBytes); - int kdfInfo = readInt(bais); - debug(""kdfInfo: "" + kdfInfo); - int kdfPrf = (kdfInfo >>> 28); - debug(""kdfPrf: "" + kdfPrf); - assert kdfPrf >= 0 && kdfPrf <= 15 : ""kdfPrf == "" + kdfPrf + "" must be between 0 and 15.""; - int kdfVers = ( kdfInfo & 0x07ffffff); - assert kdfVers > 0 && kdfVers <= 99991231 : ""KDF Version ("" + kdfVers + "") out of range.""; // Really should be >= 20110203 (earliest). - debug(""convertToCipherText: kdfPrf = "" + kdfPrf + "", kdfVers = "" + kdfVers); - if ( kdfVers != CipherText.cipherTextVersion ) { - // NOTE: In future, support backward compatibility via this mechanism. When we do this - // we will have to compare as longs and watch out for sign extension of kdfInfo - // since it may have the sign bit set. Then we will do different things depending - // on what KDF version we encounter. However, as for now, since this is - // is first ESAPI 2.0 GA version, there nothing to be backward compatible with. - // (We did not promise backward compatibility for earlier release candidates.) - // Thus any version mismatch at this point is an error. - throw new InvalidClassException(""This serialized byte stream not compatible "" + - ""with loaded CipherText class. Version read = "" + kdfInfo + - ""; version from loaded CipherText class = "" + CipherText.cipherTextVersion); - } - long timestamp = readLong(bais); - debug(""convertToCipherText: timestamp = "" + new Date(timestamp)); - short strSize = readShort(bais); - debug(""convertToCipherText: length of cipherXform = "" + strSize); - String cipherXform = readString(bais, strSize); - debug(""convertToCipherText: cipherXform = "" + cipherXform); - String[] parts = cipherXform.split(""/""); - assert parts.length == 3 : ""Malformed cipher transformation""; - String cipherMode = parts[1]; - if ( ! CryptoHelper.isAllowedCipherMode(cipherMode) ) { - String msg = ""Cipher mode "" + cipherMode + "" is not an allowed cipher mode""; - throw new EncryptionException(msg, msg); - } - short keySize = readShort(bais); - debug(""convertToCipherText: keySize = "" + keySize); - short blockSize = readShort(bais); - debug(""convertToCipherText: blockSize = "" + blockSize); - short ivLen = readShort(bais); - debug(""convertToCipherText: ivLen = "" + ivLen); - byte[] iv = null; - if ( ivLen > 0 ) { - iv = new byte[ivLen]; - bais.read(iv, 0, iv.length); - } - int ciphertextLen = readInt(bais); - debug(""convertToCipherText: ciphertextLen = "" + ciphertextLen); - assert ciphertextLen > 0 : ""convertToCipherText: Invalid cipher text length""; - byte[] rawCiphertext = new byte[ciphertextLen]; - bais.read(rawCiphertext, 0, rawCiphertext.length); - short macLen = readShort(bais); - debug(""convertToCipherText: macLen = "" + macLen); - byte[] mac = null; - if ( macLen > 0 ) { - mac = new byte[macLen]; - bais.read(mac, 0, mac.length); - } - - CipherSpec cipherSpec = new CipherSpec(cipherXform, keySize); - cipherSpec.setBlockSize(blockSize); - cipherSpec.setIV(iv); - debug(""convertToCipherText: CipherSpec: "" + cipherSpec); - CipherText ct = new CipherText(cipherSpec); - assert (ivLen > 0 && ct.requiresIV()) : - ""convertToCipherText: Mismatch between IV length and cipher mode.""; - ct.setCiphertext(rawCiphertext); - // Set this *AFTER* setting raw ciphertext because setCiphertext() - // method also sets encryption time. - ct.setEncryptionTimestamp(timestamp); - if ( macLen > 0 ) { - ct.storeSeparateMAC(mac); - } - return ct; - } catch(EncryptionException ex) { - throw new EncryptionException(""Cannot deserialize byte array into CipherText object"", - ""Cannot deserialize byte array into CipherText object"", - ex); - } catch (IOException e) { - throw new EncryptionException(""Cannot deserialize byte array into CipherText object"", - ""Cannot deserialize byte array into CipherText object"", e); - } - } - -" -579,1," public static void writeXml(Node n, OutputStream os) throws TransformerException { - TransformerFactory tf = TransformerFactory.newInstance(); - // identity - Transformer t = tf.newTransformer(); - t.setOutputProperty(OutputKeys.INDENT, ""yes""); - t.transform(new DOMSource(n), new StreamResult(os)); - } - -" -580,1," void setTransferException(boolean transferException); - - /** - * Gets the header filter strategy - * - * @return the strategy - */ -" -581,1," public List getAclForPath(String path) { - List acls = zkACLProvider.getACLsToAdd(path); - return acls; - } - }; - } - -" -582,1," protected void forwardToErrorPage(Request request, - HttpServletResponse response, LoginConfig config) - throws IOException { - - String errorPage = config.getErrorPage(); - if (errorPage == null || errorPage.length() == 0) { - String msg = sm.getString(""formAuthenticator.noErrorPage"", - context.getName()); - log.warn(msg); - response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, - msg); - return; - } - - RequestDispatcher disp = - context.getServletContext().getRequestDispatcher - (config.getErrorPage()); - try { - if (context.fireRequestInitEvent(request)) { - disp.forward(request.getRequest(), response); - context.fireRequestDestroyEvent(request); - } - } catch (Throwable t) { - ExceptionUtils.handleThrowable(t); - String msg = sm.getString(""formAuthenticator.forwardErrorFail""); - log.warn(msg, t); - request.setAttribute(RequestDispatcher.ERROR_EXCEPTION, t); - response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, - msg); - } - } - - - /** - * Does this request match the saved one (so that it must be the redirect - * we signaled after successful authentication? - * - * @param request The request to be verified - * @return true if the requests matched the saved one - */ -" -583,1," public void testSnapshotMoreThanOnce() throws ExecutionException, InterruptedException, IOException { - Client client = client(); - final File tempDir = newTempDir(LifecycleScope.SUITE).getAbsoluteFile(); - logger.info(""--> creating repository""); - assertAcked(client.admin().cluster().preparePutRepository(""test-repo"") - .setType(""fs"").setSettings(ImmutableSettings.settingsBuilder() - .put(""location"", tempDir) - .put(""compress"", randomBoolean()) - .put(""chunk_size"", randomIntBetween(100, 1000)))); - - // only one shard - assertAcked(prepareCreate(""test"").setSettings(ImmutableSettings.builder() - .put(IndexMetaData.SETTING_NUMBER_OF_SHARDS, 1) - .put(IndexMetaData.SETTING_NUMBER_OF_REPLICAS, 0) - )); - ensureYellow(); - logger.info(""--> indexing""); - - final int numDocs = randomIntBetween(10, 100); - IndexRequestBuilder[] builders = new IndexRequestBuilder[numDocs]; - for (int i = 0; i < builders.length; i++) { - builders[i] = client().prepareIndex(""test"", ""doc"", Integer.toString(i)).setSource(""foo"", ""bar"" + i); - } - indexRandom(true, builders); - flushAndRefresh(); - assertNoFailures(client().admin().indices().prepareOptimize(""test"").setFlush(true).setMaxNumSegments(1).get()); - - CreateSnapshotResponse createSnapshotResponseFirst = client.admin().cluster().prepareCreateSnapshot(""test-repo"", ""test"").setWaitForCompletion(true).setIndices(""test"").get(); - assertThat(createSnapshotResponseFirst.getSnapshotInfo().successfulShards(), greaterThan(0)); - assertThat(createSnapshotResponseFirst.getSnapshotInfo().successfulShards(), equalTo(createSnapshotResponseFirst.getSnapshotInfo().totalShards())); - assertThat(client.admin().cluster().prepareGetSnapshots(""test-repo"").setSnapshots(""test"").get().getSnapshots().get(0).state(), equalTo(SnapshotState.SUCCESS)); - { - SnapshotStatus snapshotStatus = client.admin().cluster().prepareSnapshotStatus(""test-repo"").setSnapshots(""test"").get().getSnapshots().get(0); - List shards = snapshotStatus.getShards(); - for (SnapshotIndexShardStatus status : shards) { - assertThat(status.getStats().getProcessedFiles(), greaterThan(1)); - } - } - if (frequently()) { - logger.info(""--> upgrade""); - client().admin().indices().prepareUpdateSettings(""test"").setSettings(ImmutableSettings.builder().put(EnableAllocationDecider.INDEX_ROUTING_ALLOCATION_ENABLE, ""none"")).get(); - backwardsCluster().allowOnAllNodes(""test""); - logClusterState(); - boolean upgraded; - do { - logClusterState(); - CountResponse countResponse = client().prepareCount().get(); - assertHitCount(countResponse, numDocs); - upgraded = backwardsCluster().upgradeOneNode(); - ensureYellow(); - countResponse = client().prepareCount().get(); - assertHitCount(countResponse, numDocs); - } while (upgraded); - client().admin().indices().prepareUpdateSettings(""test"").setSettings(ImmutableSettings.builder().put(EnableAllocationDecider.INDEX_ROUTING_ALLOCATION_ENABLE, ""all"")).get(); - } - if (cluster().numDataNodes() > 1 && randomBoolean()) { // only bump the replicas if we have enough nodes - logger.info(""--> move from 0 to 1 replica""); - client().admin().indices().prepareUpdateSettings(""test"").setSettings(ImmutableSettings.builder().put(IndexMetaData.SETTING_NUMBER_OF_REPLICAS, 1)).get(); - } - logger.debug(""---> repo exists: "" + new File(tempDir, ""indices/test/0"").exists() + "" files: "" + Arrays.toString(new File(tempDir, ""indices/test/0"").list())); // it's only one shard! - CreateSnapshotResponse createSnapshotResponseSecond = client.admin().cluster().prepareCreateSnapshot(""test-repo"", ""test-1"").setWaitForCompletion(true).setIndices(""test"").get(); - assertThat(createSnapshotResponseSecond.getSnapshotInfo().successfulShards(), greaterThan(0)); - assertThat(createSnapshotResponseSecond.getSnapshotInfo().successfulShards(), equalTo(createSnapshotResponseSecond.getSnapshotInfo().totalShards())); - assertThat(client.admin().cluster().prepareGetSnapshots(""test-repo"").setSnapshots(""test-1"").get().getSnapshots().get(0).state(), equalTo(SnapshotState.SUCCESS)); - { - SnapshotStatus snapshotStatus = client.admin().cluster().prepareSnapshotStatus(""test-repo"").setSnapshots(""test-1"").get().getSnapshots().get(0); - List shards = snapshotStatus.getShards(); - for (SnapshotIndexShardStatus status : shards) { - - assertThat(status.getStats().getProcessedFiles(), equalTo(1)); // we flush before the snapshot such that we have to process the segments_N files - } - } - - client().prepareDelete(""test"", ""doc"", ""1"").get(); - CreateSnapshotResponse createSnapshotResponseThird = client.admin().cluster().prepareCreateSnapshot(""test-repo"", ""test-2"").setWaitForCompletion(true).setIndices(""test"").get(); - assertThat(createSnapshotResponseThird.getSnapshotInfo().successfulShards(), greaterThan(0)); - assertThat(createSnapshotResponseThird.getSnapshotInfo().successfulShards(), equalTo(createSnapshotResponseThird.getSnapshotInfo().totalShards())); - assertThat(client.admin().cluster().prepareGetSnapshots(""test-repo"").setSnapshots(""test-2"").get().getSnapshots().get(0).state(), equalTo(SnapshotState.SUCCESS)); - { - SnapshotStatus snapshotStatus = client.admin().cluster().prepareSnapshotStatus(""test-repo"").setSnapshots(""test-2"").get().getSnapshots().get(0); - List shards = snapshotStatus.getShards(); - for (SnapshotIndexShardStatus status : shards) { - assertThat(status.getStats().getProcessedFiles(), equalTo(2)); // we flush before the snapshot such that we have to process the segments_N files plus the .del file - } - } - } -" -584,1," private boolean evaluate(String text) { - try { - InputSource inputSource = new InputSource(new StringReader(text)); - return ((Boolean)expression.evaluate(inputSource, XPathConstants.BOOLEAN)).booleanValue(); - } catch (XPathExpressionException e) { - return false; - } - } - - @Override -" -585,1," public void testTrailingHeadersSizeLimit() throws Exception { - // Setup Tomcat instance - Tomcat tomcat = getTomcatInstance(); - - // Must have a real docBase - just use temp - Context ctx = - tomcat.addContext("""", System.getProperty(""java.io.tmpdir"")); - - Tomcat.addServlet(ctx, ""servlet"", new EchoHeaderServlet()); - ctx.addServletMapping(""/"", ""servlet""); - - // Limit the size of the trailing header - tomcat.getConnector().setProperty(""maxTrailerSize"", ""10""); - tomcat.start(); - - String[] request = new String[]{ - ""POST /echo-params.jsp HTTP/1.1"" + SimpleHttpClient.CRLF + - ""Host: any"" + SimpleHttpClient.CRLF + - ""Transfer-encoding: chunked"" + SimpleHttpClient.CRLF + - ""Content-Type: application/x-www-form-urlencoded"" + - SimpleHttpClient.CRLF + - ""Connection: close"" + SimpleHttpClient.CRLF + - SimpleHttpClient.CRLF + - ""3"" + SimpleHttpClient.CRLF + - ""a=0"" + SimpleHttpClient.CRLF + - ""4"" + SimpleHttpClient.CRLF + - ""&b=1"" + SimpleHttpClient.CRLF + - ""0"" + SimpleHttpClient.CRLF + - ""x-trailer: Test"" + SimpleHttpClient.CRLF + - SimpleHttpClient.CRLF }; - - TrailerClient client = - new TrailerClient(tomcat.getConnector().getLocalPort()); - client.setRequest(request); - - client.connect(); - client.processRequest(); - // Expected to fail because the trailers are longer - // than the set limit of 10 bytes - assertTrue(client.isResponse500()); - } - - @Test -" -586,1," public void testIsExpressionIsFalse() throws Exception { - // given - String anExpression = ""foo""; - - // when - boolean actual = ComponentUtils.isExpression(anExpression); - - // then - assertFalse(actual); - } -} - -class MockConfigurationProvider implements ConfigurationProvider { - - public void destroy() { - } - - public void init(Configuration configuration) throws ConfigurationException { - } - - public boolean needsReload() { - return false; - } - - public void loadPackages() throws ConfigurationException { - } - - public void register(ContainerBuilder builder, LocatableProperties props) throws ConfigurationException { - builder.constant(StrutsConstants.STRUTS_TAG_ALTSYNTAX, ""false""); - } -" -587,1," @Test(timeout = 1000L) public void testLongMonths() throws Exception { - Calendar cal = Calendar.getInstance(); - cal.set(Calendar.MONTH, Calendar.JULY); - new CronTab(""0 0 31 7 *"").floor(cal); // would infinite loop - } - -" -588,1," public static File unzip(File zip, File toDir, Predicate filter) throws IOException { - if (!toDir.exists()) { - FileUtils.forceMkdir(toDir); - } - - ZipFile zipFile = new ZipFile(zip); - try { - Enumeration entries = zipFile.entries(); - while (entries.hasMoreElements()) { - ZipEntry entry = entries.nextElement(); - if (filter.test(entry)) { - File to = new File(toDir, entry.getName()); - if (entry.isDirectory()) { - throwExceptionIfDirectoryIsNotCreatable(to); - } else { - File parent = to.getParentFile(); - throwExceptionIfDirectoryIsNotCreatable(parent); - copy(zipFile, entry, to); - } - } - } - return toDir; - - } finally { - zipFile.close(); - } - } - -" -589,1," public Authentication authenticate(Authentication req) throws AuthenticationException { - logger.debug(""Processing authentication request for "" + req.getName()); - - if (req.getCredentials() == null) { - BadCredentialsException e = new BadCredentialsException(""No password supplied""); - publish(new AuthenticationFailureBadCredentialsEvent(req, e)); - throw e; - } - - UaaUser user; - boolean passwordMatches = false; - user = getUaaUser(req); - if (user!=null) { - passwordMatches = - ((CharSequence) req.getCredentials()).length() != 0 && encoder.matches((CharSequence) req.getCredentials(), user.getPassword()); - } else { - user = dummyUser; - } - - if (!accountLoginPolicy.isAllowed(user, req)) { - logger.warn(""Login policy rejected authentication for "" + user.getUsername() + "", "" + user.getId() - + "". Ignoring login request.""); - AuthenticationPolicyRejectionException e = new AuthenticationPolicyRejectionException(""Login policy rejected authentication""); - publish(new AuthenticationFailureLockedEvent(req, e)); - throw e; - } - - if (passwordMatches) { - logger.debug(""Password successfully matched for userId[""+user.getUsername()+""]:""+user.getId()); - - if (!allowUnverifiedUsers && !user.isVerified()) { - publish(new UnverifiedUserAuthenticationEvent(user, req)); - logger.debug(""Account not verified: "" + user.getId()); - throw new AccountNotVerifiedException(""Account not verified""); - } - - int expiringPassword = getPasswordExpiresInMonths(); - if (expiringPassword>0) { - Calendar cal = Calendar.getInstance(); - cal.setTimeInMillis(user.getPasswordLastModified().getTime()); - cal.add(Calendar.MONTH, expiringPassword); - if (cal.getTimeInMillis() < System.currentTimeMillis()) { - throw new PasswordExpiredException(""Your current password has expired. Please reset your password.""); - } - } - - Authentication success = new UaaAuthentication(new UaaPrincipal(user), - user.getAuthorities(), (UaaAuthenticationDetails) req.getDetails()); - publish(new UserAuthenticationSuccessEvent(user, success)); - - return success; - } - - if (user == dummyUser || user == null) { - logger.debug(""No user named '"" + req.getName() + ""' was found for origin:""+ origin); - publish(new UserNotFoundEvent(req)); - } else { - logger.debug(""Password did not match for user "" + req.getName()); - publish(new UserAuthenticationFailureEvent(user, req)); - } - BadCredentialsException e = new BadCredentialsException(""Bad credentials""); - publish(new AuthenticationFailureBadCredentialsEvent(req, e)); - throw e; - } - -" -590,1," public void setUp() throws Exception { - lc = new LoggerContext(); - lc.setName(""testContext""); - logger = lc.getLogger(LoggerSerializationTest.class); - // create the byte output stream - bos = new ByteArrayOutputStream(); - oos = new ObjectOutputStream(bos); - } - - @After -" -591,1," public void parseEmbedded( - InputStream stream, ContentHandler handler, Metadata metadata, boolean outputHtml) - throws SAXException, IOException { - if(outputHtml) { - AttributesImpl attributes = new AttributesImpl(); - attributes.addAttribute("""", ""class"", ""class"", ""CDATA"", ""package-entry""); - handler.startElement(XHTML, ""div"", ""div"", attributes); - } - - String name = metadata.get(Metadata.RESOURCE_NAME_KEY); - if (name != null && name.length() > 0 && outputHtml) { - handler.startElement(XHTML, ""h1"", ""h1"", new AttributesImpl()); - char[] chars = name.toCharArray(); - handler.characters(chars, 0, chars.length); - handler.endElement(XHTML, ""h1"", ""h1""); - } - - // Use the delegate parser to parse this entry - try (TemporaryResources tmp = new TemporaryResources()) { - final TikaInputStream newStream = TikaInputStream.get(new CloseShieldInputStream(stream), tmp); - if (stream instanceof TikaInputStream) { - final Object container = ((TikaInputStream) stream).getOpenContainer(); - if (container != null) { - newStream.setOpenContainer(container); - } - } - DELEGATING_PARSER.parse( - newStream, - new EmbeddedContentHandler(new BodyContentHandler(handler)), - metadata, context); - } catch (EncryptedDocumentException ede) { - // TODO: can we log a warning that we lack the password? - // For now, just skip the content - } catch (TikaException e) { - // TODO: can we log a warning somehow? - // Could not parse the entry, just skip the content - } - - if(outputHtml) { - handler.endElement(XHTML, ""div"", ""div""); - } - } - -" -592,1," private final void internalMapWrapper(ContextVersion contextVersion, - CharChunk path, - MappingData mappingData) throws IOException { - - int pathOffset = path.getOffset(); - int pathEnd = path.getEnd(); - int servletPath = pathOffset; - boolean noServletPath = false; - - int length = contextVersion.path.length(); - if (length != (pathEnd - pathOffset)) { - servletPath = pathOffset + length; - } else { - noServletPath = true; - path.append('/'); - pathOffset = path.getOffset(); - pathEnd = path.getEnd(); - servletPath = pathOffset+length; - } - - path.setOffset(servletPath); - - // Rule 1 -- Exact Match - MappedWrapper[] exactWrappers = contextVersion.exactWrappers; - internalMapExactWrapper(exactWrappers, path, mappingData); - - // Rule 2 -- Prefix Match - boolean checkJspWelcomeFiles = false; - MappedWrapper[] wildcardWrappers = contextVersion.wildcardWrappers; - if (mappingData.wrapper == null) { - internalMapWildcardWrapper(wildcardWrappers, contextVersion.nesting, - path, mappingData); - if (mappingData.wrapper != null && mappingData.jspWildCard) { - char[] buf = path.getBuffer(); - if (buf[pathEnd - 1] == '/') { - /* - * Path ending in '/' was mapped to JSP servlet based on - * wildcard match (e.g., as specified in url-pattern of a - * jsp-property-group. - * Force the context's welcome files, which are interpreted - * as JSP files (since they match the url-pattern), to be - * considered. See Bugzilla 27664. - */ - mappingData.wrapper = null; - checkJspWelcomeFiles = true; - } else { - // See Bugzilla 27704 - mappingData.wrapperPath.setChars(buf, path.getStart(), - path.getLength()); - mappingData.pathInfo.recycle(); - } - } - } - - if(mappingData.wrapper == null && noServletPath) { - // The path is empty, redirect to ""/"" - mappingData.redirectPath.setChars - (path.getBuffer(), pathOffset, pathEnd-pathOffset); - path.setEnd(pathEnd - 1); - return; - } - - // Rule 3 -- Extension Match - MappedWrapper[] extensionWrappers = contextVersion.extensionWrappers; - if (mappingData.wrapper == null && !checkJspWelcomeFiles) { - internalMapExtensionWrapper(extensionWrappers, path, mappingData, - true); - } - - // Rule 4 -- Welcome resources processing for servlets - if (mappingData.wrapper == null) { - boolean checkWelcomeFiles = checkJspWelcomeFiles; - if (!checkWelcomeFiles) { - char[] buf = path.getBuffer(); - checkWelcomeFiles = (buf[pathEnd - 1] == '/'); - } - if (checkWelcomeFiles) { - for (int i = 0; (i < contextVersion.welcomeResources.length) - && (mappingData.wrapper == null); i++) { - path.setOffset(pathOffset); - path.setEnd(pathEnd); - path.append(contextVersion.welcomeResources[i], 0, - contextVersion.welcomeResources[i].length()); - path.setOffset(servletPath); - - // Rule 4a -- Welcome resources processing for exact macth - internalMapExactWrapper(exactWrappers, path, mappingData); - - // Rule 4b -- Welcome resources processing for prefix match - if (mappingData.wrapper == null) { - internalMapWildcardWrapper - (wildcardWrappers, contextVersion.nesting, - path, mappingData); - } - - // Rule 4c -- Welcome resources processing - // for physical folder - if (mappingData.wrapper == null - && contextVersion.resources != null) { - String pathStr = path.toString(); - WebResource file = - contextVersion.resources.getResource(pathStr); - if (file != null && file.isFile()) { - internalMapExtensionWrapper(extensionWrappers, path, - mappingData, true); - if (mappingData.wrapper == null - && contextVersion.defaultWrapper != null) { - mappingData.wrapper = - contextVersion.defaultWrapper.object; - mappingData.requestPath.setChars - (path.getBuffer(), path.getStart(), - path.getLength()); - mappingData.wrapperPath.setChars - (path.getBuffer(), path.getStart(), - path.getLength()); - mappingData.requestPath.setString(pathStr); - mappingData.wrapperPath.setString(pathStr); - } - } - } - } - - path.setOffset(servletPath); - path.setEnd(pathEnd); - } - - } - - /* welcome file processing - take 2 - * Now that we have looked for welcome files with a physical - * backing, now look for an extension mapping listed - * but may not have a physical backing to it. This is for - * the case of index.jsf, index.do, etc. - * A watered down version of rule 4 - */ - if (mappingData.wrapper == null) { - boolean checkWelcomeFiles = checkJspWelcomeFiles; - if (!checkWelcomeFiles) { - char[] buf = path.getBuffer(); - checkWelcomeFiles = (buf[pathEnd - 1] == '/'); - } - if (checkWelcomeFiles) { - for (int i = 0; (i < contextVersion.welcomeResources.length) - && (mappingData.wrapper == null); i++) { - path.setOffset(pathOffset); - path.setEnd(pathEnd); - path.append(contextVersion.welcomeResources[i], 0, - contextVersion.welcomeResources[i].length()); - path.setOffset(servletPath); - internalMapExtensionWrapper(extensionWrappers, path, - mappingData, false); - } - - path.setOffset(servletPath); - path.setEnd(pathEnd); - } - } - - - // Rule 7 -- Default servlet - if (mappingData.wrapper == null && !checkJspWelcomeFiles) { - if (contextVersion.defaultWrapper != null) { - mappingData.wrapper = contextVersion.defaultWrapper.object; - mappingData.requestPath.setChars - (path.getBuffer(), path.getStart(), path.getLength()); - mappingData.wrapperPath.setChars - (path.getBuffer(), path.getStart(), path.getLength()); - } - // Redirection to a folder - char[] buf = path.getBuffer(); - if (contextVersion.resources != null && buf[pathEnd -1 ] != '/') { - String pathStr = path.toString(); - WebResource file = - contextVersion.resources.getResource(pathStr); - if (file != null && file.isDirectory()) { - // Note: this mutates the path: do not do any processing - // after this (since we set the redirectPath, there - // shouldn't be any) - path.setOffset(pathOffset); - path.append('/'); - mappingData.redirectPath.setChars - (path.getBuffer(), path.getStart(), path.getLength()); - } else { - mappingData.requestPath.setString(pathStr); - mappingData.wrapperPath.setString(pathStr); - } - } - } - - path.setOffset(pathOffset); - path.setEnd(pathEnd); - - } - - - /** - * Exact mapping. - */ -" -593,1," protected String buildErrorMessage(Throwable e, Object[] args) { - String errorKey = ""struts.messages.upload.error."" + e.getClass().getSimpleName(); - if (LOG.isDebugEnabled()) { - LOG.debug(""Preparing error message for key: [#0]"", errorKey); - } - return LocalizedTextUtil.findText(this.getClass(), errorKey, defaultLocale, e.getMessage(), args); - } - - /** - * Get an enumeration of the parameter names for uploaded files - * - * @return enumeration of parameter names for uploaded files - */ -" -594,1," public void testMultiValued() throws Exception { - Map entityAttrs = createMap(""name"", ""e"", ""url"", ""testdata.xml"", - XPathEntityProcessor.FOR_EACH, ""/root""); - List fields = new ArrayList(); - fields.add(createMap(""column"", ""a"", ""xpath"", ""/root/a"", DataImporter.MULTI_VALUED, ""true"")); - Context c = getContext(null, - new VariableResolverImpl(), getDataSource(testXml), Context.FULL_DUMP, fields, entityAttrs); - XPathEntityProcessor xPathEntityProcessor = new XPathEntityProcessor(); - xPathEntityProcessor.init(c); - List> result = new ArrayList>(); - while (true) { - Map row = xPathEntityProcessor.nextRow(); - if (row == null) - break; - result.add(row); - } - assertEquals(2, ((List)result.get(0).get(""a"")).size()); - } - - @Test -" -595,1," public String getInfo() { - - return (info); - - } - - - // --------------------------------------------------------- Public Methods - - - /** - * Authenticate the user making this request, based on the specified - * login configuration. Return true if any specified - * constraint has been satisfied, or false if we have - * created a response challenge already. - * - * @param request Request we are processing - * @param response Response we are creating - * @param config Login configuration describing how authentication - * should be performed - * - * @exception IOException if an input/output error occurs - */ - @Override -" -596,1," public final void invoke(Request request, Response response) - throws IOException, ServletException { - - // Select the Context to be used for this Request - Context context = request.getContext(); - if (context == null) { - response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, - sm.getString(""standardHost.noContext"")); - return; - } - - if (request.isAsyncSupported()) { - request.setAsyncSupported(context.getPipeline().isAsyncSupported()); - } - - boolean asyncAtStart = request.isAsync(); - boolean asyncDispatching = request.isAsyncDispatching(); - - try { - context.bind(Globals.IS_SECURITY_ENABLED, MY_CLASSLOADER); - - if (!asyncAtStart && !context.fireRequestInitEvent(request)) { - // Don't fire listeners during async processing (the listener - // fired for the request that called startAsync()). - // If a request init listener throws an exception, the request - // is aborted. - return; - } - - // Ask this Context to process this request. Requests that are in - // async mode and are not being dispatched to this resource must be - // in error and have been routed here to check for application - // defined error pages. - try { - if (!asyncAtStart || asyncDispatching) { - context.getPipeline().getFirst().invoke(request, response); - } else { - // Make sure this request/response is here because an error - // report is required. - if (!response.isErrorReportRequired()) { - throw new IllegalStateException(sm.getString(""standardHost.asyncStateError"")); - } - } - } catch (Throwable t) { - ExceptionUtils.handleThrowable(t); - container.getLogger().error(""Exception Processing "" + request.getRequestURI(), t); - // If a new error occurred while trying to report a previous - // error allow the original error to be reported. - if (!response.isErrorReportRequired()) { - request.setAttribute(RequestDispatcher.ERROR_EXCEPTION, t); - throwable(request, response, t); - } - } - - // Now that the request/response pair is back under container - // control lift the suspension so that the error handling can - // complete and/or the container can flush any remaining data - response.setSuspended(false); - - Throwable t = (Throwable) request.getAttribute(RequestDispatcher.ERROR_EXCEPTION); - - // Protect against NPEs if the context was destroyed during a - // long running request. - if (!context.getState().isAvailable()) { - return; - } - - // Look for (and render if found) an application level error page - if (response.isErrorReportRequired()) { - if (t != null) { - throwable(request, response, t); - } else { - status(request, response); - } - } - - if (!request.isAsync() && !asyncAtStart) { - context.fireRequestDestroyEvent(request); - } - } finally { - // Access a session (if present) to update last accessed time, based - // on a strict interpretation of the specification - if (ACCESS_SESSION) { - request.getSession(false); - } - - context.unbind(Globals.IS_SECURITY_ENABLED, MY_CLASSLOADER); - } - } - - - // -------------------------------------------------------- Private Methods - - /** - * Handle the HTTP status code (and corresponding message) generated - * while processing the specified Request to produce the specified - * Response. Any exceptions that occur during generation of the error - * report are logged and swallowed. - * - * @param request The request being processed - * @param response The response being generated - */ -" -597,1," private static void addHeadersToRequest(URLConnection connection, JSONObject headers) { - try { - for (Iterator iter = headers.keys(); iter.hasNext(); ) { - /* RFC 2616 says that non-ASCII characters and control - * characters are not allowed in header names or values. - * Additionally, spaces are not allowed in header names. - * RFC 2046 Quoted-printable encoding may be used to encode - * arbitrary characters, but we donon- not do that encoding here. - */ - String headerKey = iter.next().toString(); - headerKey = headerKey.replaceAll(""\\n"","""") - .replaceAll(""\\s+"","""") - .replaceAll(""[^\\x20-\\x7E]+"", """"); - - JSONArray headerValues = headers.optJSONArray(headerKey); - if (headerValues == null) { - headerValues = new JSONArray(); - - /* RFC 2616 also says that any amount of consecutive linear - * whitespace within a header value can be replaced with a - * single space character, without affecting the meaning of - * that value. - */ - - String headerValue = headers.getString(headerKey); - String finalValue = headerValue.replaceAll(""\\s+"", "" "").replaceAll(""\\n"","" "").replaceAll(""[^\\x20-\\x7E]+"", "" ""); - headerValues.put(finalValue); - } - - connection.setRequestProperty(headerKey, headerValues.getString(0)); - for (int i = 1; i < headerValues.length(); ++i) { - connection.addRequestProperty(headerKey, headerValues.getString(i)); - } - } - } catch (JSONException e1) { - // No headers to be manipulated! - } - } - -" -598,1," public HttpSecurity and() { - return HttpSecurity.this; - } - -" -599,1," void setExtensionsTable(StylesheetRoot sroot) - throws javax.xml.transform.TransformerException - { - try - { - if (sroot.getExtensions() != null) - m_extensionsTable = new ExtensionsTable(sroot); - } - catch (javax.xml.transform.TransformerException te) - {te.printStackTrace();} - } - - //== Implementation of the XPath ExtensionsProvider interface. - -" -600,1," public void testTrustedMethodPrevention() { - Response response = WebClient.create(endPoint + TIKA_PATH) - .type(""application/pdf"") - .accept(""text/plain"") - .header(TikaResource.X_TIKA_OCR_HEADER_PREFIX + - ""trustedPageSeparator"", - ""\u0010"") - .put(ClassLoader.getSystemResourceAsStream(""testOCR.pdf"")); - assertEquals(500, response.getStatus()); - - } -" -601,1," public void performTest() - throws Exception - { - testCompat(); - testNONEwithDSA(); - - testDSAsha3(NISTObjectIdentifiers.id_dsa_with_sha3_224, 224, new BigInteger(""613202af2a7f77e02b11b5c3a5311cf6b412192bc0032aac3ec127faebfc6bd0"", 16)); - testDSAsha3(NISTObjectIdentifiers.id_dsa_with_sha3_256, 256, new BigInteger(""2450755c5e15a691b121bc833b97864e34a61ee025ecec89289c949c1858091e"", 16)); - testDSAsha3(NISTObjectIdentifiers.id_dsa_with_sha3_384, 384, new BigInteger(""7aad97c0b71bb1e1a6483b6948a03bbe952e4780b0cee699a11731f90d84ddd1"", 16)); - testDSAsha3(NISTObjectIdentifiers.id_dsa_with_sha3_512, 512, new BigInteger(""725ad64d923c668e64e7c3898b5efde484cab49ce7f98c2885d2a13a9e355ad4"", 16)); - - testECDSA239bitPrime(); - testNONEwithECDSA239bitPrime(); - testECDSA239bitBinary(); - testECDSA239bitBinary(""RIPEMD160withECDSA"", TeleTrusTObjectIdentifiers.ecSignWithRipemd160); - testECDSA239bitBinary(""SHA1withECDSA"", TeleTrusTObjectIdentifiers.ecSignWithSha1); - testECDSA239bitBinary(""SHA224withECDSA"", X9ObjectIdentifiers.ecdsa_with_SHA224); - testECDSA239bitBinary(""SHA256withECDSA"", X9ObjectIdentifiers.ecdsa_with_SHA256); - testECDSA239bitBinary(""SHA384withECDSA"", X9ObjectIdentifiers.ecdsa_with_SHA384); - testECDSA239bitBinary(""SHA512withECDSA"", X9ObjectIdentifiers.ecdsa_with_SHA512); - testECDSA239bitBinary(""SHA1withCVC-ECDSA"", EACObjectIdentifiers.id_TA_ECDSA_SHA_1); - testECDSA239bitBinary(""SHA224withCVC-ECDSA"", EACObjectIdentifiers.id_TA_ECDSA_SHA_224); - testECDSA239bitBinary(""SHA256withCVC-ECDSA"", EACObjectIdentifiers.id_TA_ECDSA_SHA_256); - testECDSA239bitBinary(""SHA384withCVC-ECDSA"", EACObjectIdentifiers.id_TA_ECDSA_SHA_384); - testECDSA239bitBinary(""SHA512withCVC-ECDSA"", EACObjectIdentifiers.id_TA_ECDSA_SHA_512); - - testECDSAP256sha3(NISTObjectIdentifiers.id_ecdsa_with_sha3_224, 224, new BigInteger(""84d7d8e68e405064109cd9fc3e3026d74d278aada14ce6b7a9dd0380c154dc94"", 16)); - testECDSAP256sha3(NISTObjectIdentifiers.id_ecdsa_with_sha3_256, 256, new BigInteger(""99a43bdab4af989aaf2899079375642f2bae2dce05bcd8b72ec8c4a8d9a143f"", 16)); - testECDSAP256sha3(NISTObjectIdentifiers.id_ecdsa_with_sha3_384, 384, new BigInteger(""aa27726509c37aaf601de6f7e01e11c19add99530c9848381c23365dc505b11a"", 16)); - testECDSAP256sha3(NISTObjectIdentifiers.id_ecdsa_with_sha3_512, 512, new BigInteger(""f8306b57a1f5068bf12e53aabaae39e2658db39bc56747eaefb479995130ad16"", 16)); - - testGeneration(); - testParameters(); - testDSA2Parameters(); - testNullParameters(); - testValidate(); - testModified(); - } - -" -602,1," public void snapshotRecoveryTest() throws Exception { - logger.info(""--> start node A""); - String nodeA = internalCluster().startNode(settingsBuilder().put(""gateway.type"", ""local"")); - - logger.info(""--> create repository""); - assertAcked(client().admin().cluster().preparePutRepository(REPO_NAME) - .setType(""fs"").setSettings(ImmutableSettings.settingsBuilder() - .put(""location"", newTempDir(LifecycleScope.SUITE)) - .put(""compress"", false) - ).get()); - - ensureGreen(); - - logger.info(""--> create index on node: {}"", nodeA); - createAndPopulateIndex(INDEX_NAME, 1, SHARD_COUNT, REPLICA_COUNT); - - logger.info(""--> snapshot""); - CreateSnapshotResponse createSnapshotResponse = client().admin().cluster().prepareCreateSnapshot(REPO_NAME, SNAP_NAME) - .setWaitForCompletion(true).setIndices(INDEX_NAME).get(); - assertThat(createSnapshotResponse.getSnapshotInfo().successfulShards(), greaterThan(0)); - assertThat(createSnapshotResponse.getSnapshotInfo().successfulShards(), equalTo(createSnapshotResponse.getSnapshotInfo().totalShards())); - - assertThat(client().admin().cluster().prepareGetSnapshots(REPO_NAME).setSnapshots(SNAP_NAME).get() - .getSnapshots().get(0).state(), equalTo(SnapshotState.SUCCESS)); - - client().admin().indices().prepareClose(INDEX_NAME).execute().actionGet(); - - logger.info(""--> restore""); - RestoreSnapshotResponse restoreSnapshotResponse = client().admin().cluster() - .prepareRestoreSnapshot(REPO_NAME, SNAP_NAME).setWaitForCompletion(true).execute().actionGet(); - int totalShards = restoreSnapshotResponse.getRestoreInfo().totalShards(); - assertThat(totalShards, greaterThan(0)); - - ensureGreen(); - - logger.info(""--> request recoveries""); - RecoveryResponse response = client().admin().indices().prepareRecoveries(INDEX_NAME).execute().actionGet(); - - for (Map.Entry> shardRecoveryResponse : response.shardResponses().entrySet()) { - - assertThat(shardRecoveryResponse.getKey(), equalTo(INDEX_NAME)); - List shardRecoveryResponses = shardRecoveryResponse.getValue(); - assertThat(shardRecoveryResponses.size(), equalTo(totalShards)); - - for (ShardRecoveryResponse shardResponse : shardRecoveryResponses) { - assertRecoveryState(shardResponse.recoveryState(), 0, Type.SNAPSHOT, Stage.DONE, null, nodeA, true); - validateIndexRecoveryState(shardResponse.recoveryState().getIndex()); - } - } - } - -" -603,1," public synchronized Principal authenticate(Connection dbConnection, - String username, - String credentials) { - // No user or no credentials - // Can't possibly authenticate, don't bother the database then - if (username == null || credentials == null) { - if (containerLog.isTraceEnabled()) - containerLog.trace(sm.getString(""jdbcRealm.authenticateFailure"", - username)); - return null; - } - - // Look up the user's credentials - String dbCredentials = getPassword(username); - - if (dbCredentials == null) { - // User was not found in the database. - - if (containerLog.isTraceEnabled()) - containerLog.trace(sm.getString(""jdbcRealm.authenticateFailure"", - username)); - return null; - } - - // Validate the user's credentials - boolean validated = getCredentialHandler().matches(credentials, dbCredentials); - - if (validated) { - if (containerLog.isTraceEnabled()) - containerLog.trace(sm.getString(""jdbcRealm.authenticateSuccess"", - username)); - } else { - if (containerLog.isTraceEnabled()) - containerLog.trace(sm.getString(""jdbcRealm.authenticateFailure"", - username)); - return null; - } - - ArrayList roles = getRoles(username); - - // Create and return a suitable Principal for this user - return (new GenericPrincipal(username, credentials, roles)); - } - - - /** - * Close the specified database connection. - * - * @param dbConnection The connection to be closed - */ -" -604,1," public void performTest() - throws Exception - { - byte[] testIv = { 1, 2, 3, 4, 5, 6, 7, 8 }; - - ASN1Encodable[] values = { - new CAST5CBCParameters(testIv, 128), - new NetscapeCertType(NetscapeCertType.smime), - new VerisignCzagExtension(new DERIA5String(""hello"")), - new IDEACBCPar(testIv), - new NetscapeRevocationURL(new DERIA5String(""http://test"")) - }; - - byte[] data = Base64.decode(""MA4ECAECAwQFBgcIAgIAgAMCBSAWBWhlbGxvMAoECAECAwQFBgcIFgtodHRwOi8vdGVzdA==""); - - ByteArrayOutputStream bOut = new ByteArrayOutputStream(); - ASN1OutputStream aOut = new ASN1OutputStream(bOut); - - for (int i = 0; i != values.length; i++) - { - aOut.writeObject(values[i]); - } - - ASN1Primitive[] readValues = new ASN1Primitive[values.length]; - - if (!isSameAs(bOut.toByteArray(), data)) - { - fail(""Failed data check""); - } - - ByteArrayInputStream bIn = new ByteArrayInputStream(bOut.toByteArray()); - ASN1InputStream aIn = new ASN1InputStream(bIn); - - for (int i = 0; i != values.length; i++) - { - ASN1Primitive o = aIn.readObject(); - if (!values[i].equals(o)) - { - fail(""Failed equality test for "" + o); - } - - if (o.hashCode() != values[i].hashCode()) - { - fail(""Failed hashCode test for "" + o); - } - } - - shouldFailOnExtraData(); - } - -" -605,1," public void setEncoding( String enc ) { - if( !byteC.isNull() ) { - // if the encoding changes we need to reset the converion results - charC.recycle(); - hasStrValue=false; - } - byteC.setEncoding(enc); - } - - /** - * Sets the content to be a char[] - * - * @param c the bytes - * @param off the start offset of the bytes - * @param len the length of the bytes - */ -" -606,1," protected String buildErrorMessage(Throwable e, Object[] args) { - String errorKey = ""struts.messages.upload.error."" + e.getClass().getSimpleName(); - if (LOG.isDebugEnabled()) { - LOG.debug(""Preparing error message for key: [#0]"", errorKey); - } - return LocalizedTextUtil.findText(this.getClass(), errorKey, defaultLocale, e.getMessage(), args); - } - -" -607,1," private BigInteger[] derDecode( - byte[] encoding) - throws IOException - { - ASN1Sequence s = (ASN1Sequence)ASN1Primitive.fromByteArray(encoding); - if (s.size() != 2) - { - throw new IOException(""malformed signature""); - } - - return new BigInteger[]{ - ((ASN1Integer)s.getObjectAt(0)).getValue(), - ((ASN1Integer)s.getObjectAt(1)).getValue() - }; - } - -" -608,1," public String encodeCharacter( char[] immune, Character c ) - { - String cStr = String.valueOf(c.charValue()); - byte[] bytes; - StringBuilder sb; - - if(UNENCODED_SET.contains(c)) - return cStr; - - bytes = toUtf8Bytes(cStr); - sb = new StringBuilder(bytes.length * 3); - for(byte b : bytes) - appendTwoUpperHex(sb.append('%'), b); - return sb.toString(); - } - - /** - * {@inheritDoc} - * - * Formats all are legal both upper/lower case: - * %hh; - * - * @param input - * encoded character using percent characters (such as URL encoding) - */ -" -609,1," protected void setAuthenticateHeader(Request request, - Response response, - LoginConfig config, - String nOnce) { - - // Get the realm name - String realmName = config.getRealmName(); - if (realmName == null) - realmName = REALM_NAME; - - byte[] buffer = null; - synchronized (md5Helper) { - buffer = md5Helper.digest(nOnce.getBytes()); - } - - String authenticateHeader = ""Digest realm=\"""" + realmName + ""\"", "" - + ""qop=\""auth\"", nonce=\"""" + nOnce + ""\"", "" + ""opaque=\"""" - + md5Encoder.encode(buffer) + ""\""""; - response.setHeader(""WWW-Authenticate"", authenticateHeader); - - } - - -" -610,1," private Foo writeAndRead(Foo foo) throws IOException, ClassNotFoundException { - writeObject(oos, foo); - ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray()); - inputStream = new ObjectInputStream(bis); - Foo fooBack = readFooObject(inputStream); - inputStream.close(); - return fooBack; - } - -" -611,1," private static void processHeaderConfig(MultivaluedMap httpHeaders, Object object, String key, String prefix) { - - try { - String property = StringUtils.removeStart(key, prefix); - Field field = null; - try { - object.getClass().getDeclaredField(StringUtils.uncapitalize(property)); - } catch (NoSuchFieldException e) { - //swallow - } - String setter = property; - setter = ""set""+setter.substring(0,1).toUpperCase(Locale.US)+setter.substring(1); - //default assume string class - //if there's a more specific type, e.g. double, int, boolean - //try that. - Class clazz = String.class; - if (field != null) { - if (field.getType() == int.class) { - clazz = int.class; - } else if (field.getType() == double.class) { - clazz = double.class; - } else if (field.getType() == boolean.class) { - clazz = boolean.class; - } - } - - Method m = tryToGetMethod(object, setter, clazz); - //if you couldn't find more specific setter, back off - //to string setter and try that. - if (m == null && clazz != String.class) { - m = tryToGetMethod(object, setter, String.class); - } - - if (m != null) { - String val = httpHeaders.getFirst(key); - val = val.trim(); - if (clazz == String.class) { - checkTrustWorthy(setter, val); - m.invoke(object, val); - } else if (clazz == int.class) { - m.invoke(object, Integer.parseInt(val)); - } else if (clazz == double.class) { - m.invoke(object, Double.parseDouble(val)); - } else if (clazz == boolean.class) { - m.invoke(object, Boolean.parseBoolean(val)); - } else { - throw new IllegalArgumentException(""setter must be String, int, double or boolean...for now""); - } - } else { - throw new NoSuchMethodException(""Couldn't find: ""+setter); - } - - } catch (Throwable ex) { - throw new WebApplicationException(String.format(Locale.ROOT, - ""%s is an invalid %s header"", key, X_TIKA_OCR_HEADER_PREFIX)); - } - } - -" -612,1," public KeystoreInstance createKeystore(String name, char[] password, String keystoreType) throws KeystoreException { - File test = new File(directory, name); - if(test.exists()) { - throw new IllegalArgumentException(""Keystore already exists ""+test.getAbsolutePath()+""!""); - } - try { - KeyStore keystore = KeyStore.getInstance(keystoreType); - keystore.load(null, password); - OutputStream out = new BufferedOutputStream(new FileOutputStream(test)); - keystore.store(out, password); - out.flush(); - out.close(); - return getKeystore(name, keystoreType); - } catch (KeyStoreException e) { - throw new KeystoreException(""Unable to create keystore"", e); - } catch (IOException e) { - throw new KeystoreException(""Unable to create keystore"", e); - } catch (NoSuchAlgorithmException e) { - throw new KeystoreException(""Unable to create keystore"", e); - } catch (CertificateException e) { - throw new KeystoreException(""Unable to create keystore"", e); - } - } - -" -613,1," public void setDefaultLockoutPolicy(LockoutPolicy defaultLockoutPolicy) { - this.defaultLockoutPolicy = defaultLockoutPolicy; - } -" -614,1," protected void initializeFilters(int maxTrailerSize) { - // Create and add the identity filters. - getInputBuffer().addFilter(new IdentityInputFilter()); - getOutputBuffer().addFilter(new IdentityOutputFilter()); - - // Create and add the chunked filters. - getInputBuffer().addFilter(new ChunkedInputFilter(maxTrailerSize)); - getOutputBuffer().addFilter(new ChunkedOutputFilter()); - - // Create and add the void filters. - getInputBuffer().addFilter(new VoidInputFilter()); - getOutputBuffer().addFilter(new VoidOutputFilter()); - - // Create and add buffered input filter - getInputBuffer().addFilter(new BufferedInputFilter()); - - // Create and add the chunked filters. - //getInputBuffer().addFilter(new GzipInputFilter()); - getOutputBuffer().addFilter(new GzipOutputFilter()); - - pluggableFilterIndex = getInputBuffer().getFilters().length; - } - - - /** - * Add an input filter to the current request. - * - * @return false if the encoding was not found (which would mean it is - * unsupported) - */ -" -615,1," private BeanReference createSecurityFilterChainBean(Element element, - ParserContext pc, List filterChain) { - BeanMetadataElement filterChainMatcher; - - String requestMatcherRef = element.getAttribute(ATT_REQUEST_MATCHER_REF); - String filterChainPattern = element.getAttribute(ATT_PATH_PATTERN); - - if (StringUtils.hasText(requestMatcherRef)) { - if (StringUtils.hasText(filterChainPattern)) { - pc.getReaderContext().error( - ""You can't define a pattern and a request-matcher-ref for the "" - + ""same filter chain"", pc.extractSource(element)); - } - filterChainMatcher = new RuntimeBeanReference(requestMatcherRef); - - } - else if (StringUtils.hasText(filterChainPattern)) { - filterChainMatcher = MatcherType.fromElement(element).createMatcher( - filterChainPattern, null); - } - else { - filterChainMatcher = new RootBeanDefinition(AnyRequestMatcher.class); - } - - BeanDefinitionBuilder filterChainBldr = BeanDefinitionBuilder - .rootBeanDefinition(DefaultSecurityFilterChain.class); - filterChainBldr.addConstructorArgValue(filterChainMatcher); - filterChainBldr.addConstructorArgValue(filterChain); - - BeanDefinition filterChainBean = filterChainBldr.getBeanDefinition(); - - String id = element.getAttribute(""name""); - if (!StringUtils.hasText(id)) { - id = element.getAttribute(""id""); - if (!StringUtils.hasText(id)) { - id = pc.getReaderContext().generateBeanName(filterChainBean); - } - } - - pc.registerBeanComponent(new BeanComponentDefinition(filterChainBean, id)); - - return new RuntimeBeanReference(id); - } - -" -616,1," public boolean check(String path, Resource resource) - { - int slash = path.lastIndexOf('/'); - if (slash<0) - return false; - String suffix=path.substring(slash); - return resource.getAlias().toString().endsWith(suffix); - } - } -} -" -617,1," public Mapper getMapper() { - - return (mapper); - - } - - - /** - * Return the maximum size of a POST which will be automatically - * parsed by the container. - */ -" -618,1," public Object getValue(Object parent) { - return ( (Object[]) parent )[index]; - } - - @Override -" -619,1," public String createDB(String dbName) { - String result = DB_CREATED_MSG + "": "" + dbName; - - Connection conn = null; - try { - conn = DerbyConnectionUtil.getDerbyConnection(dbName, - DerbyConnectionUtil.CREATE_DB_PROP); - } catch (Throwable e) { - if (e instanceof SQLException) { - result = getSQLError((SQLException) e); - } else { - result = e.getMessage(); - } - } finally { - // close DB connection - try { - if (conn != null) { - conn.close(); - } - } catch (SQLException e) { - result = ""Problem closing DB connection""; - } - } - - return result; - } - -" -620,1," public URL resolveConfig(String path) throws FailedToResolveConfigException { - String origPath = path; - // first, try it as a path on the file system - File f1 = new File(path); - if (f1.exists()) { - try { - return f1.toURI().toURL(); - } catch (MalformedURLException e) { - throw new FailedToResolveConfigException(""Failed to resolve path ["" + f1 + ""]"", e); - } - } - if (path.startsWith(""/"")) { - path = path.substring(1); - } - // next, try it relative to the config location - File f2 = new File(configFile, path); - if (f2.exists()) { - try { - return f2.toURI().toURL(); - } catch (MalformedURLException e) { - throw new FailedToResolveConfigException(""Failed to resolve path ["" + f2 + ""]"", e); - } - } - // try and load it from the classpath directly - URL resource = settings.getClassLoader().getResource(path); - if (resource != null) { - return resource; - } - // try and load it from the classpath with config/ prefix - if (!path.startsWith(""config/"")) { - resource = settings.getClassLoader().getResource(""config/"" + path); - if (resource != null) { - return resource; - } - } - throw new FailedToResolveConfigException(""Failed to resolve config path ["" + origPath + ""], tried file path ["" + f1 + ""], path file ["" + f2 + ""], and classpath""); - } -" -621,1," public static boolean normalize(MessageBytes uriMB) { - - ByteChunk uriBC = uriMB.getByteChunk(); - byte[] b = uriBC.getBytes(); - int start = uriBC.getStart(); - int end = uriBC.getEnd(); - - // URL * is acceptable - if ((end - start == 1) && b[start] == (byte) '*') - return true; - - int pos = 0; - int index = 0; - - // Replace '\' with '/' - // Check for null byte - for (pos = start; pos < end; pos++) { - if (b[pos] == (byte) '\\') - b[pos] = (byte) '/'; - if (b[pos] == (byte) 0) - return false; - } - - // The URL must start with '/' - if (b[start] != (byte) '/') { - return false; - } - - // Replace ""//"" with ""/"" - for (pos = start; pos < (end - 1); pos++) { - if (b[pos] == (byte) '/') { - while ((pos + 1 < end) && (b[pos + 1] == (byte) '/')) { - copyBytes(b, pos, pos + 1, end - pos - 1); - end--; - } - } - } - - // If the URI ends with ""/."" or ""/.."", then we append an extra ""/"" - // Note: It is possible to extend the URI by 1 without any side effect - // as the next character is a non-significant WS. - if (((end - start) >= 2) && (b[end - 1] == (byte) '.')) { - if ((b[end - 2] == (byte) '/') - || ((b[end - 2] == (byte) '.') - && (b[end - 3] == (byte) '/'))) { - b[end] = (byte) '/'; - end++; - } - } - - uriBC.setEnd(end); - - index = 0; - - // Resolve occurrences of ""/./"" in the normalized path - while (true) { - index = uriBC.indexOf(""/./"", 0, 3, index); - if (index < 0) - break; - copyBytes(b, start + index, start + index + 2, - end - start - index - 2); - end = end - 2; - uriBC.setEnd(end); - } - - index = 0; - - // Resolve occurrences of ""/../"" in the normalized path - while (true) { - index = uriBC.indexOf(""/../"", 0, 4, index); - if (index < 0) - break; - // Prevent from going outside our context - if (index == 0) - return false; - int index2 = -1; - for (pos = start + index - 1; (pos >= 0) && (index2 < 0); pos --) { - if (b[pos] == (byte) '/') { - index2 = pos; - } - } - copyBytes(b, start + index2, start + index + 3, - end - start - index - 3); - end = end + index2 - index - 3; - uriBC.setEnd(end); - index = index2; - } - - uriBC.setBytes(b, start, end); - - return true; - - } - - - // ------------------------------------------------------ Protected Methods - - - /** - * Copy an array of bytes to a different position. Used during - * normalization. - */ -" -622,1," protected void handShake() throws IOException { - ssl.setNeedClientAuth(true); - ssl.startHandshake(); - } - /** - * Copied from org.apache.catalina.valves.CertificateValve - */ -" -623,1," public void testIssue1599() throws Exception - { - final String JSON = aposToQuotes( - ""{'id': 124,\n"" -+"" 'obj':[ 'com.sun.org.apache.xalan.internal.xsltc.trax.TemplatesImpl',\n"" -+"" {\n"" -+"" 'transletBytecodes' : [ 'AAIAZQ==' ],\n"" -+"" 'transletName' : 'a.b',\n"" -+"" 'outputProperties' : { }\n"" -+"" }\n"" -+"" ]\n"" -+""}"" - ); - ObjectMapper mapper = new ObjectMapper(); - mapper.enableDefaultTyping(); - try { - mapper.readValue(JSON, Bean1599.class); - fail(""Should not pass""); - } catch (JsonMappingException e) { - verifyException(e, ""Illegal type""); - verifyException(e, ""to deserialize""); - verifyException(e, ""prevented for security reasons""); - } - } -" -624,1," public void testWildcardBehaviour_snapshotRestore() throws Exception { - createIndex(""foobar""); - ensureGreen(""foobar""); - waitForRelocation(); - - PutRepositoryResponse putRepositoryResponse = client().admin().cluster().preparePutRepository(""dummy-repo"") - .setType(""fs"").setSettings(ImmutableSettings.settingsBuilder().put(""location"", newTempDir())).get(); - assertThat(putRepositoryResponse.isAcknowledged(), equalTo(true)); - client().admin().cluster().prepareCreateSnapshot(""dummy-repo"", ""snap1"").setWaitForCompletion(true).get(); - - IndicesOptions options = IndicesOptions.fromOptions(false, false, true, false); - verify(snapshot(""snap2"", ""foo*"", ""bar*"").setIndicesOptions(options), true); - verify(restore(""snap1"", ""foo*"", ""bar*"").setIndicesOptions(options), true); - - options = IndicesOptions.strictExpandOpen(); - verify(snapshot(""snap2"", ""foo*"", ""bar*"").setIndicesOptions(options), false); - verify(restore(""snap2"", ""foo*"", ""bar*"").setIndicesOptions(options), false); - - assertAcked(prepareCreate(""barbaz"")); - //TODO: temporary work-around for #5531 - ensureGreen(""barbaz""); - waitForRelocation(); - options = IndicesOptions.fromOptions(false, false, true, false); - verify(snapshot(""snap3"", ""foo*"", ""bar*"").setIndicesOptions(options), false); - verify(restore(""snap3"", ""foo*"", ""bar*"").setIndicesOptions(options), false); - - options = IndicesOptions.fromOptions(false, false, true, false); - verify(snapshot(""snap4"", ""foo*"", ""baz*"").setIndicesOptions(options), true); - verify(restore(""snap3"", ""foo*"", ""baz*"").setIndicesOptions(options), true); - } - - @Test -" -625,1," public synchronized JettyHttpBinding getJettyBinding(HttpClient httpClient) { - if (jettyBinding == null) { - jettyBinding = new DefaultJettyHttpBinding(); - jettyBinding.setHeaderFilterStrategy(getHeaderFilterStrategy()); - jettyBinding.setThrowExceptionOnFailure(isThrowExceptionOnFailure()); - jettyBinding.setTransferException(isTransferException()); - jettyBinding.setOkStatusCodeRange(getOkStatusCodeRange()); - } - return jettyBinding; - } - -" -626,1," protected final String getWindowOpenJavaScript() - { - AppendingStringBuffer buffer = new AppendingStringBuffer(500); - - if (isCustomComponent() == true) - { - buffer.append(""var element = document.getElementById(\""""); - buffer.append(getContentMarkupId()); - buffer.append(""\"");\n""); - } - - buffer.append(""var settings = new Object();\n""); - - appendAssignment(buffer, ""settings.minWidth"", getMinimalWidth()); - appendAssignment(buffer, ""settings.minHeight"", getMinimalHeight()); - appendAssignment(buffer, ""settings.className"", getCssClassName()); - appendAssignment(buffer, ""settings.width"", getInitialWidth()); - - if ((isUseInitialHeight() == true) || (isCustomComponent() == false)) - { - appendAssignment(buffer, ""settings.height"", getInitialHeight()); - } - else - { - buffer.append(""settings.height=null;\n""); - } - - appendAssignment(buffer, ""settings.resizable"", isResizable()); - - if (isResizable() == false) - { - appendAssignment(buffer, ""settings.widthUnit"", getWidthUnit()); - appendAssignment(buffer, ""settings.heightUnit"", getHeightUnit()); - } - - if (isCustomComponent() == false) - { - Page page = createPage(); - if (page == null) - { - throw new WicketRuntimeException(""Error creating page for modal dialog.""); - } - CharSequence pageUrl; - RequestCycle requestCycle = RequestCycle.get(); - - page.getSession().getPageManager().touchPage(page); - if (page.isPageStateless()) - { - pageUrl = requestCycle.urlFor(page.getClass(), page.getPageParameters()); - } - else - { - IRequestHandler handler = new RenderPageRequestHandler(new PageProvider(page)); - pageUrl = requestCycle.urlFor(handler); - } - - appendAssignment(buffer, ""settings.src"", pageUrl); - } - else - { - buffer.append(""settings.element=element;\n""); - } - - if (getCookieName() != null) - { - appendAssignment(buffer, ""settings.cookieId"", getCookieName()); - } - - Object title = getTitle() != null ? getTitle().getObject() : null; - if (title != null) - { - appendAssignment(buffer, ""settings.title"", escapeQuotes(title.toString())); - } - - if (getMaskType() == MaskType.TRANSPARENT) - { - buffer.append(""settings.mask=\""transparent\"";\n""); - } - else if (getMaskType() == MaskType.SEMI_TRANSPARENT) - { - buffer.append(""settings.mask=\""semi-transparent\"";\n""); - } - - appendAssignment(buffer, ""settings.autoSize"", autoSize); - - appendAssignment(buffer, ""settings.unloadConfirmation"", showUnloadConfirmation()); - - // set true if we set a windowclosedcallback - boolean haveCloseCallback = false; - - // in case user is interested in window close callback or we have a pagemap to clean attach - // notification request - if (windowClosedCallback != null) - { - WindowClosedBehavior behavior = getBehaviors(WindowClosedBehavior.class).get(0); - buffer.append(""settings.onClose = function() { ""); - buffer.append(behavior.getCallbackScript()); - buffer.append("" };\n""); - - haveCloseCallback = true; - } - - // in case we didn't set windowclosecallback, we need at least callback on close button, to - // close window property (thus cleaning the shown flag) - if ((closeButtonCallback != null) || (haveCloseCallback == false)) - { - CloseButtonBehavior behavior = getBehaviors(CloseButtonBehavior.class).get(0); - buffer.append(""settings.onCloseButton = function() { ""); - buffer.append(behavior.getCallbackScript()); - buffer.append("";return false;};\n""); - } - - postProcessSettings(buffer); - - buffer.append(getShowJavaScript()); - return buffer.toString(); - } - - /** - * - * @param buffer - * @param key - * @param value - */ -" -627,1," private void addUserFromChangeSet(ChangeLogSet.Entry change, Set to, Set cc, Set bcc, EnvVars env, TaskListener listener, RecipientProviderUtilities.IDebug debug) { - User user = change.getAuthor(); - RecipientProviderUtilities.addUsers(Collections.singleton(user), listener, env, to, cc, bcc, debug); - } - - @Extension -" -628,1," public final void parse(Set mappingStreams) { - try { - JAXBContext jc = JAXBContext.newInstance( ConstraintMappingsType.class ); - - Set alreadyProcessedConstraintDefinitions = newHashSet(); - for ( InputStream in : mappingStreams ) { - String schemaVersion = xmlParserHelper.getSchemaVersion( ""constraint mapping file"", in ); - String schemaResourceName = getSchemaResourceName( schemaVersion ); - Schema schema = xmlParserHelper.getSchema( schemaResourceName ); - - Unmarshaller unmarshaller = jc.createUnmarshaller(); - unmarshaller.setSchema( schema ); - - ConstraintMappingsType mapping = getValidationConfig( in, unmarshaller ); - String defaultPackage = mapping.getDefaultPackage(); - - parseConstraintDefinitions( - mapping.getConstraintDefinition(), - defaultPackage, - alreadyProcessedConstraintDefinitions - ); - - for ( BeanType bean : mapping.getBean() ) { - Class beanClass = ClassLoadingHelper.loadClass( bean.getClazz(), defaultPackage ); - checkClassHasNotBeenProcessed( processedClasses, beanClass ); - - // update annotation ignores - annotationProcessingOptions.ignoreAnnotationConstraintForClass( - beanClass, - bean.getIgnoreAnnotations() - ); - - ConstrainedType constrainedType = ConstrainedTypeBuilder.buildConstrainedType( - bean.getClassType(), - beanClass, - defaultPackage, - constraintHelper, - annotationProcessingOptions, - defaultSequences - ); - if ( constrainedType != null ) { - addConstrainedElement( beanClass, constrainedType ); - } - - Set constrainedFields = ConstrainedFieldBuilder.buildConstrainedFields( - bean.getField(), - beanClass, - defaultPackage, - constraintHelper, - annotationProcessingOptions - ); - addConstrainedElements( beanClass, constrainedFields ); - - Set constrainedGetters = ConstrainedGetterBuilder.buildConstrainedGetters( - bean.getGetter(), - beanClass, - defaultPackage, - constraintHelper, - annotationProcessingOptions - ); - addConstrainedElements( beanClass, constrainedGetters ); - - Set constrainedConstructors = ConstrainedExecutableBuilder.buildConstructorConstrainedExecutable( - bean.getConstructor(), - beanClass, - defaultPackage, - parameterNameProvider, - constraintHelper, - annotationProcessingOptions - ); - addConstrainedElements( beanClass, constrainedConstructors ); - - Set constrainedMethods = ConstrainedExecutableBuilder.buildMethodConstrainedExecutable( - bean.getMethod(), - beanClass, - defaultPackage, - parameterNameProvider, - constraintHelper, - annotationProcessingOptions - ); - addConstrainedElements( beanClass, constrainedMethods ); - - processedClasses.add( beanClass ); - } - } - } - catch ( JAXBException e ) { - throw log.getErrorParsingMappingFileException( e ); - } - } - -" -629,1," public void addRecipients(final ExtendedEmailPublisherContext context, EnvVars env, Set to, Set cc, Set 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(); - Set users = RecipientProviderUtilities.getChangeSetAuthors(Collections.>singleton(context.getRun()), debug); - RecipientProviderUtilities.addUsers(users, context.getListener(), env, to, cc, bcc, debug); - } - - @Extension -" -630,1," private boolean evaluate(String text) { - try { - InputSource inputSource = new InputSource(new StringReader(text)); - return ((Boolean)expression.evaluate(inputSource, XPathConstants.BOOLEAN)).booleanValue(); - } catch (XPathExpressionException e) { - return false; - } - } - - @Override -" -631,1," public void basicWorkFlowTest() throws Exception { - Client client = client(); - - logger.info(""--> creating repository""); - assertAcked(client.admin().cluster().preparePutRepository(""test-repo"") - .setType(""fs"").setSettings(ImmutableSettings.settingsBuilder() - .put(""location"", newTempDir()) - .put(""compress"", randomBoolean()) - .put(""chunk_size"", randomIntBetween(100, 1000)))); - - createIndex(""test-idx-1"", ""test-idx-2"", ""test-idx-3""); - ensureGreen(); - - logger.info(""--> indexing some data""); - for (int i = 0; i < 100; i++) { - index(""test-idx-1"", ""doc"", Integer.toString(i), ""foo"", ""bar"" + i); - index(""test-idx-2"", ""doc"", Integer.toString(i), ""foo"", ""baz"" + i); - index(""test-idx-3"", ""doc"", Integer.toString(i), ""foo"", ""baz"" + i); - } - refresh(); - assertHitCount(client.prepareCount(""test-idx-1"").get(), 100L); - assertHitCount(client.prepareCount(""test-idx-2"").get(), 100L); - assertHitCount(client.prepareCount(""test-idx-3"").get(), 100L); - - ListenableActionFuture flushResponseFuture = null; - if (randomBoolean()) { - ArrayList indicesToFlush = newArrayList(); - for (int i = 1; i < 4; i++) { - if (randomBoolean()) { - indicesToFlush.add(""test-idx-"" + i); - } - } - if (!indicesToFlush.isEmpty()) { - String[] indices = indicesToFlush.toArray(new String[indicesToFlush.size()]); - logger.info(""--> starting asynchronous flush for indices {}"", Arrays.toString(indices)); - flushResponseFuture = client.admin().indices().prepareFlush(indices).execute(); - } - } - logger.info(""--> snapshot""); - CreateSnapshotResponse createSnapshotResponse = client.admin().cluster().prepareCreateSnapshot(""test-repo"", ""test-snap"").setWaitForCompletion(true).setIndices(""test-idx-*"", ""-test-idx-3"").get(); - assertThat(createSnapshotResponse.getSnapshotInfo().successfulShards(), greaterThan(0)); - assertThat(createSnapshotResponse.getSnapshotInfo().successfulShards(), equalTo(createSnapshotResponse.getSnapshotInfo().totalShards())); - - assertThat(client.admin().cluster().prepareGetSnapshots(""test-repo"").setSnapshots(""test-snap"").get().getSnapshots().get(0).state(), equalTo(SnapshotState.SUCCESS)); - - logger.info(""--> delete some data""); - for (int i = 0; i < 50; i++) { - client.prepareDelete(""test-idx-1"", ""doc"", Integer.toString(i)).get(); - } - for (int i = 50; i < 100; i++) { - client.prepareDelete(""test-idx-2"", ""doc"", Integer.toString(i)).get(); - } - for (int i = 0; i < 100; i += 2) { - client.prepareDelete(""test-idx-3"", ""doc"", Integer.toString(i)).get(); - } - refresh(); - assertHitCount(client.prepareCount(""test-idx-1"").get(), 50L); - assertHitCount(client.prepareCount(""test-idx-2"").get(), 50L); - assertHitCount(client.prepareCount(""test-idx-3"").get(), 50L); - - logger.info(""--> close indices""); - client.admin().indices().prepareClose(""test-idx-1"", ""test-idx-2"").get(); - - logger.info(""--> restore all indices from the snapshot""); - RestoreSnapshotResponse restoreSnapshotResponse = client.admin().cluster().prepareRestoreSnapshot(""test-repo"", ""test-snap"").setWaitForCompletion(true).execute().actionGet(); - assertThat(restoreSnapshotResponse.getRestoreInfo().totalShards(), greaterThan(0)); - - ensureGreen(); - for (int i=0; i<5; i++) { - assertHitCount(client.prepareCount(""test-idx-1"").get(), 100L); - assertHitCount(client.prepareCount(""test-idx-2"").get(), 100L); - assertHitCount(client.prepareCount(""test-idx-3"").get(), 50L); - } - - // Test restore after index deletion - logger.info(""--> delete indices""); - cluster().wipeIndices(""test-idx-1"", ""test-idx-2""); - logger.info(""--> restore one index after deletion""); - restoreSnapshotResponse = client.admin().cluster().prepareRestoreSnapshot(""test-repo"", ""test-snap"").setWaitForCompletion(true).setIndices(""test-idx-*"", ""-test-idx-2"").execute().actionGet(); - assertThat(restoreSnapshotResponse.getRestoreInfo().totalShards(), greaterThan(0)); - - ensureGreen(); - for (int i=0; i<5; i++) { - assertHitCount(client.prepareCount(""test-idx-1"").get(), 100L); - } - ClusterState clusterState = client.admin().cluster().prepareState().get().getState(); - assertThat(clusterState.getMetaData().hasIndex(""test-idx-1""), equalTo(true)); - assertThat(clusterState.getMetaData().hasIndex(""test-idx-2""), equalTo(false)); - - if (flushResponseFuture != null) { - // Finish flush - flushResponseFuture.actionGet(); - } - } - - - @Test -" -632,1," public Object getValue(Object parent) { - return parent; - } - - @Override -" -633,1," public void handshake(Socket sock) throws IOException { - ((SSLSocket)sock).startHandshake(); - } - - /* - * Determines the SSL cipher suites to be enabled. - * - * @param requestedCiphers Comma-separated list of requested ciphers - * @param supportedCiphers Array of supported ciphers - * - * @return Array of SSL cipher suites to be enabled, or null if none of the - * requested ciphers are supported - */ -" -634,1," ValidationException getErrorParsingMappingFileException(@Cause JAXBException e); - - @Message(id = 116, value = ""%s"") -" -635,1," private static ManagedMap parseInterceptUrlsForFilterInvocationRequestMap( - MatcherType matcherType, List urlElts, boolean useExpressions, - boolean addAuthenticatedAll, ParserContext parserContext) { - - ManagedMap filterInvocationDefinitionMap = new ManagedMap(); - - for (Element urlElt : urlElts) { - String access = urlElt.getAttribute(ATT_ACCESS); - if (!StringUtils.hasText(access)) { - continue; - } - - String path = urlElt.getAttribute(ATT_PATTERN); - - if (!StringUtils.hasText(path)) { - parserContext.getReaderContext().error( - ""path attribute cannot be empty or null"", urlElt); - } - - String method = urlElt.getAttribute(ATT_HTTP_METHOD); - if (!StringUtils.hasText(method)) { - method = null; - } - - BeanDefinition matcher = matcherType.createMatcher(path, method); - BeanDefinitionBuilder attributeBuilder = BeanDefinitionBuilder - .rootBeanDefinition(SecurityConfig.class); - - if (useExpressions) { - logger.info(""Creating access control expression attribute '"" + access - + ""' for "" + path); - // The single expression will be parsed later by the - // ExpressionFilterInvocationSecurityMetadataSource - attributeBuilder.addConstructorArgValue(new String[] { access }); - attributeBuilder.setFactoryMethod(""createList""); - - } - else { - attributeBuilder.addConstructorArgValue(access); - attributeBuilder.setFactoryMethod(""createListFromCommaDelimitedString""); - } - - if (filterInvocationDefinitionMap.containsKey(matcher)) { - logger.warn(""Duplicate URL defined: "" + path - + "". The original attribute values will be overwritten""); - } - - filterInvocationDefinitionMap.put(matcher, - attributeBuilder.getBeanDefinition()); - } - - if (addAuthenticatedAll && filterInvocationDefinitionMap.isEmpty()) { - - BeanDefinition matcher = matcherType.createMatcher(""/**"", null); - BeanDefinitionBuilder attributeBuilder = BeanDefinitionBuilder - .rootBeanDefinition(SecurityConfig.class); - attributeBuilder.addConstructorArgValue(new String[] { ""authenticated"" }); - attributeBuilder.setFactoryMethod(""createList""); - filterInvocationDefinitionMap.put(matcher, - attributeBuilder.getBeanDefinition()); - } - - return filterInvocationDefinitionMap; - } - -" -636,1," public void setApplicationContext(ApplicationContext applicationContext) - throws BeansException { - defaultWebSecurityExpressionHandler.setApplicationContext(applicationContext); - } -" -637,1," public void testDoEnable() throws Exception{ - FreeStyleProject project = j.createFreeStyleProject(""project""); - GlobalMatrixAuthorizationStrategy auth = new GlobalMatrixAuthorizationStrategy(); - j.jenkins.setAuthorizationStrategy(auth); - j.jenkins.setCrumbIssuer(null); - HudsonPrivateSecurityRealm realm = new HudsonPrivateSecurityRealm(false); - j.jenkins.setSecurityRealm(realm); - User user = realm.createAccount(""John Smith"", ""password""); - SecurityContextHolder.getContext().setAuthentication(user.impersonate()); - project.disable(); - try{ - project.doEnable(); - fail(""User should not have permission to build project""); - } - catch(Exception e){ - if(!(e.getClass().isAssignableFrom(AccessDeniedException2.class))){ - fail(""AccessDeniedException should be thrown.""); - } - } - auth.add(Job.READ, user.getId()); - auth.add(Job.CONFIGURE, user.getId()); - auth.add(Jenkins.READ, user.getId()); - List forms = j.createWebClient().login(user.getId(), ""password"").goTo(project.getUrl()).getForms(); - for(HtmlForm form:forms){ - if(""enable"".equals(form.getAttribute(""action""))){ - j.submit(form); - } - } - assertFalse(""Project should be enabled."", project.isDisabled()); - } - - /** - * Job is un-restricted (no nabel), this is submitted to queue, which spawns an on demand slave - * @throws Exception - */ - @Test -" diff --git a/validation.csv b/validation.csv deleted file mode 100644 index 99c2c2d13c7b4b9b4d17db3bfb69586a73aa417e..0000000000000000000000000000000000000000 --- a/validation.csv +++ /dev/null @@ -1,11455 +0,0 @@ -,label,code -0,0," private static void initKeyPair(SecureRandom prng) throws NoSuchAlgorithmException { - String sigAlg = signatureAlgorithm.toLowerCase(); - if ( sigAlg.endsWith(""withdsa"") ) { - // - // Admittedly, this is a kludge. However for Sun JCE, even though - // ""SHA1withDSA"" is a valid signature algorithm name, if one calls - // KeyPairGenerator kpg = KeyPairGenerator.getInstance(""SHA1withDSA""); - // that will throw a NoSuchAlgorithmException with an exception - // message of ""SHA1withDSA KeyPairGenerator not available"". Since - // SHA1withDSA and DSA keys should be identical, we use ""DSA"" - // in the case that SHA1withDSA or SHAwithDSA was specified. This is - // all just to make these 2 work as expected. Sigh. (Note: - // this was tested with JDK 1.6.0_21, but likely fails with earlier - // versions of the JDK as well.) - // - sigAlg = ""DSA""; - } else if ( sigAlg.endsWith(""withrsa"") ) { - // Ditto for RSA. - sigAlg = ""RSA""; - } - KeyPairGenerator keyGen = KeyPairGenerator.getInstance(sigAlg); - keyGen.initialize(signatureKeyLength, prng); - KeyPair pair = keyGen.generateKeyPair(); - privateKey = pair.getPrivate(); - publicKey = pair.getPublic(); - } -" -1,0," public ZipArchiveEntry getNextZipEntry() throws IOException { - uncompressedCount = 0; - - boolean firstEntry = true; - if (closed || hitCentralDirectory) { - return null; - } - if (current != null) { - closeEntry(); - firstEntry = false; - } - - long currentHeaderOffset = getBytesRead(); - try { - if (firstEntry) { - // split archives have a special signature before the - // first local file header - look for it and fail with - // the appropriate error message if this is a split - // archive. - readFirstLocalFileHeader(lfhBuf); - } else { - readFully(lfhBuf); - } - } catch (final EOFException e) { - return null; - } - - final ZipLong sig = new ZipLong(lfhBuf); - if (!sig.equals(ZipLong.LFH_SIG)) { - if (sig.equals(ZipLong.CFH_SIG) || sig.equals(ZipLong.AED_SIG) || isApkSigningBlock(lfhBuf)) { - hitCentralDirectory = true; - skipRemainderOfArchive(); - return null; - } - throw new ZipException(String.format(""Unexpected record signature: 0X%X"", sig.getValue())); - } - - int off = WORD; - current = new CurrentEntry(); - - final int versionMadeBy = ZipShort.getValue(lfhBuf, off); - off += SHORT; - current.entry.setPlatform((versionMadeBy >> ZipFile.BYTE_SHIFT) & ZipFile.NIBLET_MASK); - - final GeneralPurposeBit gpFlag = GeneralPurposeBit.parse(lfhBuf, off); - final boolean hasUTF8Flag = gpFlag.usesUTF8ForNames(); - final ZipEncoding entryEncoding = hasUTF8Flag ? ZipEncodingHelper.UTF8_ZIP_ENCODING : zipEncoding; - current.hasDataDescriptor = gpFlag.usesDataDescriptor(); - current.entry.setGeneralPurposeBit(gpFlag); - - off += SHORT; - - current.entry.setMethod(ZipShort.getValue(lfhBuf, off)); - off += SHORT; - - final long time = ZipUtil.dosToJavaTime(ZipLong.getValue(lfhBuf, off)); - current.entry.setTime(time); - off += WORD; - - ZipLong size = null, cSize = null; - if (!current.hasDataDescriptor) { - current.entry.setCrc(ZipLong.getValue(lfhBuf, off)); - off += WORD; - - cSize = new ZipLong(lfhBuf, off); - off += WORD; - - size = new ZipLong(lfhBuf, off); - off += WORD; - } else { - off += 3 * WORD; - } - - final int fileNameLen = ZipShort.getValue(lfhBuf, off); - - off += SHORT; - - final int extraLen = ZipShort.getValue(lfhBuf, off); - off += SHORT; // NOSONAR - assignment as documentation - - final byte[] fileName = new byte[fileNameLen]; - readFully(fileName); - current.entry.setName(entryEncoding.decode(fileName), fileName); - if (hasUTF8Flag) { - current.entry.setNameSource(ZipArchiveEntry.NameSource.NAME_WITH_EFS_FLAG); - } - - final byte[] extraData = new byte[extraLen]; - readFully(extraData); - current.entry.setExtra(extraData); - - if (!hasUTF8Flag && useUnicodeExtraFields) { - ZipUtil.setNameAndCommentFromExtraFields(current.entry, fileName, null); - } - - processZip64Extra(size, cSize); - - current.entry.setLocalHeaderOffset(currentHeaderOffset); - current.entry.setDataOffset(getBytesRead()); - current.entry.setStreamContiguous(true); - - ZipMethod m = ZipMethod.getMethodByCode(current.entry.getMethod()); - if (current.entry.getCompressedSize() != ArchiveEntry.SIZE_UNKNOWN) { - if (ZipUtil.canHandleEntryData(current.entry) && m != ZipMethod.STORED && m != ZipMethod.DEFLATED) { - InputStream bis = new BoundedInputStream(in, current.entry.getCompressedSize()); - switch (m) { - case UNSHRINKING: - current.in = new UnshrinkingInputStream(bis); - break; - case IMPLODING: - current.in = new ExplodingInputStream( - current.entry.getGeneralPurposeBit().getSlidingDictionarySize(), - current.entry.getGeneralPurposeBit().getNumberOfShannonFanoTrees(), - bis); - break; - case BZIP2: - current.in = new BZip2CompressorInputStream(bis); - break; - case ENHANCED_DEFLATED: - current.in = new Deflate64CompressorInputStream(bis); - break; - default: - // we should never get here as all supported methods have been covered - // will cause an error when read is invoked, don't throw an exception here so people can - // skip unsupported entries - break; - } - } - } else if (m == ZipMethod.ENHANCED_DEFLATED) { - current.in = new Deflate64CompressorInputStream(in); - } - - entriesRead++; - return current.entry; - } - - /** - * Fills the given array with the first local file header and - * deals with splitting/spanning markers that may prefix the first - * LFH. - */ -" -2,0," private static void assertCorrectConfig(User user, String unixPath) { - assertThat(user.getConfigFile().getFile().getPath(), endsWith(unixPath.replace('/', File.separatorChar))); - } - -" -3,0," public void testRepositoryCreation() throws Exception { - Client client = client(); - - File location = randomRepoPath(); - - logger.info(""--> creating repository""); - PutRepositoryResponse putRepositoryResponse = client.admin().cluster().preparePutRepository(""test-repo-1"") - .setType(""fs"").setSettings(ImmutableSettings.settingsBuilder() - .put(""location"", location) - ).get(); - assertThat(putRepositoryResponse.isAcknowledged(), equalTo(true)); - - logger.info(""--> verify the repository""); - int numberOfFiles = location.listFiles().length; - VerifyRepositoryResponse verifyRepositoryResponse = client.admin().cluster().prepareVerifyRepository(""test-repo-1"").get(); - assertThat(verifyRepositoryResponse.getNodes().length, equalTo(cluster().numDataAndMasterNodes())); - - logger.info(""--> verify that we didn't leave any files as a result of verification""); - assertThat(location.listFiles().length, equalTo(numberOfFiles)); - - logger.info(""--> check that repository is really there""); - ClusterStateResponse clusterStateResponse = client.admin().cluster().prepareState().clear().setMetaData(true).get(); - MetaData metaData = clusterStateResponse.getState().getMetaData(); - RepositoriesMetaData repositoriesMetaData = metaData.custom(RepositoriesMetaData.TYPE); - assertThat(repositoriesMetaData, notNullValue()); - assertThat(repositoriesMetaData.repository(""test-repo-1""), notNullValue()); - assertThat(repositoriesMetaData.repository(""test-repo-1"").type(), equalTo(""fs"")); - - logger.info(""--> creating another repository""); - putRepositoryResponse = client.admin().cluster().preparePutRepository(""test-repo-2"") - .setType(""fs"").setSettings(ImmutableSettings.settingsBuilder() - .put(""location"", randomRepoPath()) - ).get(); - assertThat(putRepositoryResponse.isAcknowledged(), equalTo(true)); - - logger.info(""--> check that both repositories are in cluster state""); - clusterStateResponse = client.admin().cluster().prepareState().clear().setMetaData(true).get(); - metaData = clusterStateResponse.getState().getMetaData(); - repositoriesMetaData = metaData.custom(RepositoriesMetaData.TYPE); - assertThat(repositoriesMetaData, notNullValue()); - assertThat(repositoriesMetaData.repositories().size(), equalTo(2)); - assertThat(repositoriesMetaData.repository(""test-repo-1""), notNullValue()); - assertThat(repositoriesMetaData.repository(""test-repo-1"").type(), equalTo(""fs"")); - assertThat(repositoriesMetaData.repository(""test-repo-2""), notNullValue()); - assertThat(repositoriesMetaData.repository(""test-repo-2"").type(), equalTo(""fs"")); - - logger.info(""--> check that both repositories can be retrieved by getRepositories query""); - GetRepositoriesResponse repositoriesResponse = client.admin().cluster().prepareGetRepositories().get(); - assertThat(repositoriesResponse.repositories().size(), equalTo(2)); - assertThat(findRepository(repositoriesResponse.repositories(), ""test-repo-1""), notNullValue()); - assertThat(findRepository(repositoriesResponse.repositories(), ""test-repo-2""), notNullValue()); - - logger.info(""--> delete repository test-repo-1""); - client.admin().cluster().prepareDeleteRepository(""test-repo-1"").get(); - repositoriesResponse = client.admin().cluster().prepareGetRepositories().get(); - assertThat(repositoriesResponse.repositories().size(), equalTo(1)); - assertThat(findRepository(repositoriesResponse.repositories(), ""test-repo-2""), notNullValue()); - - logger.info(""--> delete repository test-repo-2""); - client.admin().cluster().prepareDeleteRepository(""test-repo-2"").get(); - repositoriesResponse = client.admin().cluster().prepareGetRepositories().get(); - assertThat(repositoriesResponse.repositories().size(), equalTo(0)); - } - -" -4,0," protected Blob getBlob(ResultSet resultSet, int columnIndex, Metadata m) throws SQLException { - byte[] bytes = resultSet.getBytes(columnIndex); - if (!resultSet.wasNull()) { - return new SerialBlob(bytes); - } - return null; - } -" -5,0," private T run(PrivilegedAction action) { - return System.getSecurityManager() != null ? AccessController.doPrivileged( action ) : action.run(); - } -" -6,0," protected boolean statusDropsConnection(int status) { - return status == 400 /* SC_BAD_REQUEST */ || - status == 408 /* SC_REQUEST_TIMEOUT */ || - status == 411 /* SC_LENGTH_REQUIRED */ || - status == 413 /* SC_REQUEST_ENTITY_TOO_LARGE */ || - status == 414 /* SC_REQUEST_URI_TOO_LARGE */ || - status == 500 /* SC_INTERNAL_SERVER_ERROR */ || - status == 503 /* SC_SERVICE_UNAVAILABLE */ || - status == 501 /* SC_NOT_IMPLEMENTED */; - } - -" -7,0," private ControllerInfo getControllerInfo(Annotations annotation, String s) { - String[] data = s.split("":""); - if (data.length != 3) { - print(""Wrong format of the controller %s, should be in the format ::"", s); - return null; - } - String type = data[0]; - IpAddress ip = IpAddress.valueOf(data[1]); - int port = Integer.parseInt(data[2]); - if (annotation != null) { - return new ControllerInfo(ip, port, type, annotation); - } - return new ControllerInfo(ip, port, type); - } -" -8,0," public Authentication authenticate(Authentication authentication) throws AuthenticationException { - Assert.isInstanceOf(UsernamePasswordAuthenticationToken.class, authentication, - messages.getMessage(""LdapAuthenticationProvider.onlySupports"", - ""Only UsernamePasswordAuthenticationToken is supported"")); - - final UsernamePasswordAuthenticationToken userToken = (UsernamePasswordAuthenticationToken)authentication; - - String username = userToken.getName(); - String password = (String) authentication.getCredentials(); - - if (logger.isDebugEnabled()) { - logger.debug(""Processing authentication request for user: "" + username); - } - - if (!StringUtils.hasLength(username)) { - throw new BadCredentialsException(messages.getMessage(""LdapAuthenticationProvider.emptyUsername"", - ""Empty Username"")); - } - - if (!StringUtils.hasLength(password)) { - throw new BadCredentialsException(messages.getMessage(""AbstractLdapAuthenticationProvider.emptyPassword"", - ""Empty Password"")); - } - - Assert.notNull(password, ""Null password was supplied in authentication token""); - - DirContextOperations userData = doAuthentication(userToken); - - UserDetails user = userDetailsContextMapper.mapUserFromContext(userData, authentication.getName(), - loadUserAuthorities(userData, authentication.getName(), (String)authentication.getCredentials())); - - return createSuccessfulAuthentication(userToken, user); - } - -" -9,0," protected IgnoreCsrfProtectionRegistry chainRequestMatchers( - List requestMatchers) { - CsrfConfigurer.this.ignoredCsrfProtectionMatchers.addAll(requestMatchers); - return this; - } - } -}" -10,0," private String[] getParts(String encodedJWT) { - String[] parts = encodedJWT.split(""\\.""); - // Secured JWT XXXXX.YYYYY.ZZZZZ, Unsecured JWT XXXXX.YYYYY. - if (parts.length == 3 || (parts.length == 2 && encodedJWT.endsWith("".""))) { - return parts; - } - - throw new InvalidJWTException(""The encoded JWT is not properly formatted. Expected a three part dot separated string.""); - } -" -11,0," public String getAlgorithm() { - - return (this.algorithm); - - } - - - /** - * Set the message digest algorithm for this Manager. - * - * @param algorithm The new message digest algorithm - */ -" -12,0," public ChannelRequestMatcherRegistry getRegistry() { - return REGISTRY; - } - - @Override -" -13,0," public String getDefaultWebXml() { - if( defaultWebXml == null ) { - defaultWebXml=Constants.DefaultWebXml; - } - - return (this.defaultWebXml); - - } - - - /** - * Set the location of the default deployment descriptor - * - * @param path Absolute/relative path to the default web.xml - */ -" -14,0," public Collection getRequiredPermissions(String regionName) { - return Collections.singletonList(ResourcePermissions.DATA_MANAGE); - } - -" -15,0," private void enableAllocation(String index) { - client().admin().indices().prepareUpdateSettings(index).setSettings(ImmutableSettings.builder().put( - ""index.routing.allocation.enable"", ""all"" - )).get(); - } -" -16,0," public void parse(InputStream stream, ContentHandler ignore, - Metadata metadata, ParseContext context) throws IOException, - SAXException, TikaException { - //Test to see if we should avoid parsing - if (parserState.recursiveParserWrapperHandler.hasHitMaximumEmbeddedResources()) { - return; - } - // Work out what this thing is - String objectName = getResourceName(metadata, parserState); - String objectLocation = this.location + objectName; - - metadata.add(AbstractRecursiveParserWrapperHandler.EMBEDDED_RESOURCE_PATH, objectLocation); - - - //get a fresh handler - ContentHandler localHandler = parserState.recursiveParserWrapperHandler.getNewContentHandler(); - parserState.recursiveParserWrapperHandler.startEmbeddedDocument(localHandler, metadata); - - Parser preContextParser = context.get(Parser.class); - context.set(Parser.class, new EmbeddedParserDecorator(getWrappedParser(), objectLocation, parserState)); - long started = System.currentTimeMillis(); - try { - super.parse(stream, localHandler, metadata, context); - } catch (SAXException e) { - boolean wlr = isWriteLimitReached(e); - if (wlr == true) { - metadata.add(WRITE_LIMIT_REACHED, ""true""); - } else { - if (catchEmbeddedExceptions) { - ParserUtils.recordParserFailure(this, e, metadata); - } else { - throw e; - } - } - } catch(CorruptedFileException e) { - throw e; - } catch (TikaException e) { - if (catchEmbeddedExceptions) { - ParserUtils.recordParserFailure(this, e, metadata); - } else { - throw e; - } - } finally { - context.set(Parser.class, preContextParser); - long elapsedMillis = System.currentTimeMillis() - started; - metadata.set(RecursiveParserWrapperHandler.PARSE_TIME_MILLIS, Long.toString(elapsedMillis)); - parserState.recursiveParserWrapperHandler.endEmbeddedDocument(localHandler, metadata); - } - } - } - - /** - * This tracks the state of the parse of a single document. - * In future versions, this will allow the RecursiveParserWrapper to be thread safe. - */ - private class ParserState { - private int unknownCount = 0; - private final AbstractRecursiveParserWrapperHandler recursiveParserWrapperHandler; - private ParserState(AbstractRecursiveParserWrapperHandler handler) { - this.recursiveParserWrapperHandler = handler; - } - - - } -} -" -17,0," public static void beforeTests() throws Exception { - initCore(""solrconfig.xml"",""schema.xml""); - handler = new UpdateRequestHandler(); - } - - @Test -" -18,0," public void setUp() throws Exception { - interceptor = new I18nInterceptor(); - interceptor.init(); - params = new HashMap(); - session = new HashMap(); - - Map ctx = new HashMap(); - ctx.put(ActionContext.PARAMETERS, params); - ctx.put(ActionContext.SESSION, session); - ac = new ActionContext(ctx); - - Action action = new Action() { - public String execute() throws Exception { - return SUCCESS; - } - }; - mai = new MockActionInvocation(); - ((MockActionInvocation) mai).setAction(action); - ((MockActionInvocation) mai).setInvocationContext(ac); - } - - @After -" -19,0," private MockHttpServletRequestBuilder createChangePasswordRequest(ScimUser user, String code, boolean useCSRF, String password, String passwordConfirmation) throws Exception { - MockHttpServletRequestBuilder post = post(""/reset_password.do""); - if (useCSRF) { - post.with(csrf()); - } - post.param(""code"", code) - .param(""email"", user.getPrimaryEmail()) - .param(""password"", password) - .param(""password_confirmation"", passwordConfirmation); - return post; - } -" -20,0," protected Log getLog() { - return log; - } - - // ----------------------------------------------------------- Constructors - - -" -21,0," public int getCount() { - return iCount; - } - -" -22,0," public BeanDefinitionHolder decorate(Node node, BeanDefinitionHolder holder, - ParserContext parserContext) { - BeanDefinition filterChainProxy = holder.getBeanDefinition(); - - ManagedList securityFilterChains = new ManagedList(); - Element elt = (Element) node; - - MatcherType matcherType = MatcherType.fromElement(elt); - - List filterChainElts = DomUtils.getChildElementsByTagName(elt, - Elements.FILTER_CHAIN); - - for (Element chain : filterChainElts) { - String path = chain - .getAttribute(HttpSecurityBeanDefinitionParser.ATT_PATH_PATTERN); - String filters = chain - .getAttribute(HttpSecurityBeanDefinitionParser.ATT_FILTERS); - - if (!StringUtils.hasText(path)) { - parserContext.getReaderContext().error( - ""The attribute '"" - + HttpSecurityBeanDefinitionParser.ATT_PATH_PATTERN - + ""' must not be empty"", elt); - } - - if (!StringUtils.hasText(filters)) { - parserContext.getReaderContext().error( - ""The attribute '"" + HttpSecurityBeanDefinitionParser.ATT_FILTERS - + ""'must not be empty"", elt); - } - - BeanDefinition matcher = matcherType.createMatcher(parserContext, path, null); - - if (filters.equals(HttpSecurityBeanDefinitionParser.OPT_FILTERS_NONE)) { - securityFilterChains.add(createSecurityFilterChain(matcher, - new ManagedList(0))); - } - else { - String[] filterBeanNames = StringUtils - .tokenizeToStringArray(filters, "",""); - ManagedList filterChain = new ManagedList(filterBeanNames.length); - - for (String name : filterBeanNames) { - filterChain.add(new RuntimeBeanReference(name)); - } - - securityFilterChains.add(createSecurityFilterChain(matcher, filterChain)); - } - } - - filterChainProxy.getConstructorArgumentValues().addGenericArgumentValue( - securityFilterChains); - - return holder; - } - -" -23,0," public XObject execute(XPathContext xctxt) throws javax.xml.transform.TransformerException - { - - String fullName = m_arg0.execute(xctxt).str(); - int indexOfNSSep = fullName.indexOf(':'); - String result = null; - String propName = """"; - - // List of properties where the name of the - // property argument is to be looked for. - Properties xsltInfo = new Properties(); - - loadPropertyFile(XSLT_PROPERTIES, xsltInfo); - - if (indexOfNSSep > 0) - { - String prefix = (indexOfNSSep >= 0) - ? fullName.substring(0, indexOfNSSep) : """"; - String namespace; - - namespace = xctxt.getNamespaceContext().getNamespaceForPrefix(prefix); - propName = (indexOfNSSep < 0) - ? fullName : fullName.substring(indexOfNSSep + 1); - - if (namespace.startsWith(""http://www.w3.org/XSL/Transform"") - || namespace.equals(""http://www.w3.org/1999/XSL/Transform"")) - { - result = xsltInfo.getProperty(propName); - - if (null == result) - { - warn(xctxt, XPATHErrorResources.WG_PROPERTY_NOT_SUPPORTED, - new Object[]{ fullName }); //""XSL Property not supported: ""+fullName); - - return XString.EMPTYSTRING; - } - } - else - { - warn(xctxt, XPATHErrorResources.WG_DONT_DO_ANYTHING_WITH_NS, - new Object[]{ namespace, - fullName }); //""Don't currently do anything with namespace ""+namespace+"" in property: ""+fullName); - - try - { - //if secure procession is enabled only handle required properties do not not map any valid system property - if(!xctxt.isSecureProcessing()) - { - result = System.getProperty(fullName); - } - else - { - warn(xctxt, XPATHErrorResources.WG_SECURITY_EXCEPTION, - new Object[]{ fullName }); //""SecurityException when trying to access XSL system property: ""+fullName); - result = xsltInfo.getProperty(propName); - } - if (null == result) - { - return XString.EMPTYSTRING; - } - } - catch (SecurityException se) - { - warn(xctxt, XPATHErrorResources.WG_SECURITY_EXCEPTION, - new Object[]{ fullName }); //""SecurityException when trying to access XSL system property: ""+fullName); - - return XString.EMPTYSTRING; - } - } - } - else - { - try - { - //if secure procession is enabled only handle required properties do not not map any valid system property - if(!xctxt.isSecureProcessing()) - { - result = System.getProperty(fullName); - } - else - { - warn(xctxt, XPATHErrorResources.WG_SECURITY_EXCEPTION, - new Object[]{ fullName }); //""SecurityException when trying to access XSL system property: ""+fullName); - result = xsltInfo.getProperty(propName); - } - if (null == result) - { - return XString.EMPTYSTRING; - } - } - catch (SecurityException se) - { - warn(xctxt, XPATHErrorResources.WG_SECURITY_EXCEPTION, - new Object[]{ fullName }); //""SecurityException when trying to access XSL system property: ""+fullName); - - return XString.EMPTYSTRING; - } - } - - if (propName.equals(""version"") && result.length() > 0) - { - try - { - // Needs to return the version number of the spec we conform to. - return new XString(""1.0""); - } - catch (Exception ex) - { - return new XString(result); - } - } - else - return new XString(result); - } - - /** - * Retrieve a propery bundle from a specified file - * - * @param file The string name of the property file. The name - * should already be fully qualified as path/filename - * @param target The target property bag the file will be placed into. - */ -" -24,0," public boolean equals(Object obj) { - if ( this == obj ) { - return true; - } - if ( !super.equals( obj ) ) { - return false; - } - if ( getClass() != obj.getClass() ) { - return false; - } - ConstrainedExecutable other = (ConstrainedExecutable) obj; - if ( executable == null ) { - if ( other.executable != null ) { - return false; - } - } - else if ( !executable.equals( other.executable ) ) { - return false; - } - return true; - } -" -25,0," public static HierarchicalConfiguration loadXml(InputStream xmlStream) { - try { - XMLConfiguration cfg = new XMLConfiguration(); - DocumentBuilderFactory dbfactory = DocumentBuilderFactory.newInstance(); - //Disabling DTDs in order to avoid XXE xml-based attacks. - disableFeature(dbfactory, DISALLOW_DTD_FEATURE); - disableFeature(dbfactory, DISALLOW_EXTERNAL_DTD); - dbfactory.setXIncludeAware(false); - dbfactory.setExpandEntityReferences(false); - cfg.setDocumentBuilder(dbfactory.newDocumentBuilder()); - cfg.load(xmlStream); - return cfg; - } catch (ConfigurationException | ParserConfigurationException e) { - throw new IllegalArgumentException(""Cannot load xml from Stream"", e); - } - } - -" -26,0," void noteBytesRead(int pBytes) { - /* Indicates, that the given number of bytes have been read from - * the input stream. - */ - bytesRead += pBytes; - notifyListener(); - } - - /** - * Called to indicate, that a new file item has been detected. - */ -" -27,0," private static DocumentBuilder getBuilder() throws ParserConfigurationException { - ClassLoader loader = Thread.currentThread().getContextClassLoader(); - if (loader == null) { - loader = DOMUtils.class.getClassLoader(); - } - if (loader == null) { - DocumentBuilderFactory dbf = createDocumentBuilderFactory(); - return dbf.newDocumentBuilder(); - } - DocumentBuilder builder = DOCUMENT_BUILDERS.get(loader); - if (builder == null) { - DocumentBuilderFactory dbf = createDocumentBuilderFactory(); - builder = dbf.newDocumentBuilder(); - DOCUMENT_BUILDERS.put(loader, builder); - } - return builder; - } - - /** - * This function is much like getAttribute, but returns null, not """", for a nonexistent attribute. - * - * @param e - * @param attributeName - */ -" -28,0," public StandardInterceptUrlRegistry getRegistry() { - return REGISTRY; - } - - /** - * Adds an {@link ObjectPostProcessor} for this class. - * - * @param objectPostProcessor - * @return the {@link UrlAuthorizationConfigurer} for further customizations - */ -" -29,0," public synchronized XPathRecordReader addField(String name, String xpath, boolean multiValued, int flags) { - addField0(xpath, name, multiValued, false, flags); - return this; - } - - /** - * Splits the XPATH into a List of xpath segments and calls build() to - * construct a tree of Nodes representing xpath segments. The resulting - * tree structure ends up describing all the Xpaths we are interested in. - * - * @param xpath The xpath expression for this field - * @param name The name for this field in the emitted record - * @param multiValued If 'true' then the emitted record will have values in - * a List<String> - * @param isRecord Flags that this XPATH is from a forEach statement - * @param flags The only supported flag is 'FLATTEN' - */ -" -30,0," public void setConstants(ContainerBuilder builder) { - for (Object keyobj : keySet()) { - String key = (String)keyobj; - builder.factory(String.class, key, - new LocatableConstantFactory(getProperty(key), getPropertyLocation(key))); - } - } - } -} -" -31,0," public CommandLauncher launch(String host, TaskListener listener) throws IOException, InterruptedException { - return new CommandLauncher(command,new EnvVars(""SLAVE"",host)); - } - - @Extension @Symbol(""command"") -" -32,0," private void parseCSSStyleSheet(String sheet) throws SVGParseException - { - CSSParser cssp = new CSSParser(MediaType.screen); - svgDocument.addCSSRules(cssp.parse(sheet)); - } - -" -33,0," public void test_unsecuredJWT_validation() throws Exception { - JWT jwt = new JWT().setSubject(""123456789""); - Signer signer = new UnsecuredSigner(); - Verifier hmacVerifier = HMACVerifier.newVerifier(""too many secrets""); - - String encodedUnsecuredJWT = JWTEncoder.getInstance().encode(jwt, signer); - - // Ensure that attempting to decode an un-secured JWT fails when we provide a verifier - expectException(MissingVerifierException.class, () -> JWT.getDecoder().decode(encodedUnsecuredJWT, hmacVerifier)); - - String encodedUnsecuredJWT_withKid = JWTEncoder.getInstance().encode(jwt, signer, (header) -> header.set(""kid"", ""abc"")); - String encodedUnsecuredJWT_withoutKid = JWTEncoder.getInstance().encode(jwt, signer); - - Map verifierMap = new HashMap<>(); - verifierMap.put(null, hmacVerifier); - verifierMap.put(""abc"", hmacVerifier); - - // Ensure that attempting to decode an un-secured JWT fails when we provide a verifier with or without using a kid - expectException(MissingVerifierException.class, () -> JWT.getDecoder().decode(encodedUnsecuredJWT_withKid, verifierMap)); - expectException(MissingVerifierException.class, () -> JWT.getDecoder().decode(encodedUnsecuredJWT_withoutKid, verifierMap)); - } - - @Test -" -34,0," public String getConnectionName() { - return connectionName; - } - - /** - * Set the username to use to connect to the database. - * - * @param connectionName Username - */ -" -35,0," protected Log getLog() { - return log; - } - - @Override -" -36,0," public BigInteger[] decode( - byte[] encoding) - throws IOException - { - BigInteger[] sig = new BigInteger[2]; - - byte[] first = new byte[encoding.length / 2]; - byte[] second = new byte[encoding.length / 2]; - - System.arraycopy(encoding, 0, first, 0, first.length); - System.arraycopy(encoding, first.length, second, 0, second.length); - - sig[0] = new BigInteger(1, first); - sig[1] = new BigInteger(1, second); - - return sig; - } - } -}" -37,0," public ScimGroup mapRow(ResultSet rs, int rowNum) throws SQLException { - int pos = 1; - String id = rs.getString(pos++); - String name = rs.getString(pos++); - String description = rs.getString(pos++); - Date created = rs.getTimestamp(pos++); - Date modified = rs.getTimestamp(pos++); - int version = rs.getInt(pos++); - String zoneId = rs.getString(pos++); - ScimGroup group = new ScimGroup(id, name, zoneId); - group.setDescription(description); - ScimMeta meta = new ScimMeta(created, modified, version); - group.setMeta(meta); - return group; - } - } -} -" -38,0," public void testSendStringMessage() throws Exception { - sendMessageAndHaveItTransformed(""HeyHello world!""); - } - -" -39,0," public void testSingletonPatternInSerialization() { - final Object[] singletones = new Object[] { - ExceptionFactory.INSTANCE, - }; - - for (final Object original : singletones) { - TestUtils.assertSameAfterSerialization( - ""Singletone patern broken for "" + original.getClass(), - original - ); - } - } - -" -40,0," private void doTestParameterNameLengthRestriction( ParametersInterceptor parametersInterceptor, - int paramNameMaxLength ) { - StringBuilder sb = new StringBuilder(); - for (int i = 0; i < paramNameMaxLength + 1; i++) { - sb.append(""x""); - } - - Map actual = new LinkedHashMap(); - parametersInterceptor.setValueStackFactory(createValueStackFactory(actual)); - ValueStack stack = createStubValueStack(actual); - - Map parameters = new HashMap(); - parameters.put(sb.toString(), """"); - parameters.put(""huuhaa"", """"); - - Action action = new SimpleAction(); - parametersInterceptor.setParameters(action, stack, parameters); - assertEquals(1, actual.size()); - } - -" -41,0," public boolean equals(Object obj) { - if (obj instanceof CharEntry) { - return value.equals(((CharEntry) obj).value); - } - return false; - } - - } - - -} -" -42,0," protected boolean readMessage(AjpMessage message) - throws IOException { - - byte[] buf = message.getBuffer(); - int headerLength = message.getHeaderLength(); - - read(buf, 0, headerLength); - - int messageLength = message.processHeader(true); - if (messageLength < 0) { - // Invalid AJP header signature - // TODO: Throw some exception and close the connection to frontend. - return false; - } - else if (messageLength == 0) { - // Zero length message. - return true; - } - else { - if (messageLength > buf.length) { - // Message too long for the buffer - // Need to trigger a 400 response - throw new IllegalArgumentException(sm.getString( - ""ajpprocessor.header.tooLong"", - Integer.valueOf(messageLength), - Integer.valueOf(buf.length))); - } - read(buf, headerLength, messageLength); - return true; - } - } -" -43,0," public boolean allPresentAndPositive() { - return lockoutPeriodSeconds >= 0 && lockoutAfterFailures >= 0 && countFailuresWithin >= 0; - } -" -44,0," public boolean event(org.apache.coyote.Request req, - org.apache.coyote.Response res, SocketStatus status) { - - Request request = (Request) req.getNote(ADAPTER_NOTES); - Response response = (Response) res.getNote(ADAPTER_NOTES); - - if (request.getWrapper() != null) { - - boolean error = false; - try { - if (status == SocketStatus.OPEN) { - request.getEvent().setEventType(CometEvent.EventType.READ); - request.getEvent().setEventSubType(null); - } else if (status == SocketStatus.DISCONNECT) { - request.getEvent().setEventType(CometEvent.EventType.ERROR); - request.getEvent().setEventSubType(CometEvent.EventSubType.CLIENT_DISCONNECT); - error = true; - } else if (status == SocketStatus.ERROR) { - request.getEvent().setEventType(CometEvent.EventType.ERROR); - request.getEvent().setEventSubType(CometEvent.EventSubType.IOEXCEPTION); - error = true; - } else if (status == SocketStatus.STOP) { - request.getEvent().setEventType(CometEvent.EventType.END); - request.getEvent().setEventSubType(CometEvent.EventSubType.SERVER_SHUTDOWN); - } else if (status == SocketStatus.TIMEOUT) { - request.getEvent().setEventType(CometEvent.EventType.ERROR); - request.getEvent().setEventSubType(CometEvent.EventSubType.TIMEOUT); - } - - // Calling the container - connector.getContainer().getPipeline().getFirst().event(request, response, request.getEvent()); - - if (response.isClosed() || !request.isComet()) { - res.action(ActionCode.ACTION_COMET_END, null); - } - return (!error); - } catch (Throwable t) { - if (!(t instanceof IOException)) { - log.error(sm.getString(""coyoteAdapter.service""), t); - } - error = true; - // FIXME: Since there's likely some structures kept in the servlet or elsewhere, - // a cleanup event of some sort could be needed ? - return false; - } finally { - // Recycle the wrapper request and response - if (error || response.isClosed() || !request.isComet()) { - request.recycle(); - request.setFilterChain(null); - response.recycle(); - } - } - - } else { - return false; - } - } - - - /** - * Service method. - */ -" -45,0," public void testSnapshotAndRestore() throws ExecutionException, InterruptedException, IOException { - logger.info(""--> creating repository""); - assertAcked(client().admin().cluster().preparePutRepository(""test-repo"") - .setType(""fs"").setSettings(ImmutableSettings.settingsBuilder() - .put(""location"", randomRepoPath().getAbsolutePath()) - .put(""compress"", randomBoolean()) - .put(""chunk_size"", randomIntBetween(100, 1000)))); - String[] indicesBefore = new String[randomIntBetween(2,5)]; - String[] indicesAfter = new String[randomIntBetween(2,5)]; - for (int i = 0; i < indicesBefore.length; i++) { - indicesBefore[i] = ""index_before_"" + i; - createIndex(indicesBefore[i]); - } - for (int i = 0; i < indicesAfter.length; i++) { - indicesAfter[i] = ""index_after_"" + i; - createIndex(indicesAfter[i]); - } - String[] indices = new String[indicesBefore.length + indicesAfter.length]; - System.arraycopy(indicesBefore, 0, indices, 0, indicesBefore.length); - System.arraycopy(indicesAfter, 0, indices, indicesBefore.length, indicesAfter.length); - ensureYellow(); - logger.info(""--> indexing some data""); - IndexRequestBuilder[] buildersBefore = new IndexRequestBuilder[randomIntBetween(10, 200)]; - for (int i = 0; i < buildersBefore.length; i++) { - buildersBefore[i] = client().prepareIndex(RandomPicks.randomFrom(getRandom(), indicesBefore), ""foo"", Integer.toString(i)).setSource(""{ \""foo\"" : \""bar\"" } ""); - } - IndexRequestBuilder[] buildersAfter = new IndexRequestBuilder[randomIntBetween(10, 200)]; - for (int i = 0; i < buildersAfter.length; i++) { - buildersAfter[i] = client().prepareIndex(RandomPicks.randomFrom(getRandom(), indicesBefore), ""bar"", Integer.toString(i)).setSource(""{ \""foo\"" : \""bar\"" } ""); - } - indexRandom(true, buildersBefore); - indexRandom(true, buildersAfter); - assertThat(client().prepareCount(indices).get().getCount(), equalTo((long) (buildersBefore.length + buildersAfter.length))); - long[] counts = new long[indices.length]; - for (int i = 0; i < indices.length; i++) { - counts[i] = client().prepareCount(indices[i]).get().getCount(); - } - - logger.info(""--> snapshot subset of indices before upgrage""); - CreateSnapshotResponse createSnapshotResponse = client().admin().cluster().prepareCreateSnapshot(""test-repo"", ""test-snap-1"").setWaitForCompletion(true).setIndices(""index_before_*"").get(); - assertThat(createSnapshotResponse.getSnapshotInfo().successfulShards(), greaterThan(0)); - assertThat(createSnapshotResponse.getSnapshotInfo().successfulShards(), equalTo(createSnapshotResponse.getSnapshotInfo().totalShards())); - - assertThat(client().admin().cluster().prepareGetSnapshots(""test-repo"").setSnapshots(""test-snap-1"").get().getSnapshots().get(0).state(), equalTo(SnapshotState.SUCCESS)); - - logger.info(""--> delete some data from indices that were already snapshotted""); - int howMany = randomIntBetween(1, buildersBefore.length); - - for (int i = 0; i < howMany; i++) { - IndexRequestBuilder indexRequestBuilder = RandomPicks.randomFrom(getRandom(), buildersBefore); - IndexRequest request = indexRequestBuilder.request(); - client().prepareDelete(request.index(), request.type(), request.id()).get(); - } - refresh(); - final long numDocs = client().prepareCount(indices).get().getCount(); - assertThat(client().prepareCount(indices).get().getCount(), lessThan((long) (buildersBefore.length + buildersAfter.length))); - - - client().admin().indices().prepareUpdateSettings(indices).setSettings(ImmutableSettings.builder().put(EnableAllocationDecider.INDEX_ROUTING_ALLOCATION_ENABLE, ""none"")).get(); - backwardsCluster().allowOnAllNodes(indices); - logClusterState(); - boolean upgraded; - do { - logClusterState(); - CountResponse countResponse = client().prepareCount().get(); - assertHitCount(countResponse, numDocs); - upgraded = backwardsCluster().upgradeOneNode(); - ensureYellow(); - countResponse = client().prepareCount().get(); - assertHitCount(countResponse, numDocs); - } while (upgraded); - client().admin().indices().prepareUpdateSettings(indices).setSettings(ImmutableSettings.builder().put(EnableAllocationDecider.INDEX_ROUTING_ALLOCATION_ENABLE, ""all"")).get(); - - logger.info(""--> close indices""); - client().admin().indices().prepareClose(""index_before_*"").get(); - - logger.info(""--> verify repository""); - client().admin().cluster().prepareVerifyRepository(""test-repo"").get(); - - logger.info(""--> restore all indices from the snapshot""); - RestoreSnapshotResponse restoreSnapshotResponse = client().admin().cluster().prepareRestoreSnapshot(""test-repo"", ""test-snap-1"").setWaitForCompletion(true).execute().actionGet(); - assertThat(restoreSnapshotResponse.getRestoreInfo().totalShards(), greaterThan(0)); - - ensureYellow(); - assertThat(client().prepareCount(indices).get().getCount(), equalTo((long) (buildersBefore.length + buildersAfter.length))); - for (int i = 0; i < indices.length; i++) { - assertThat(counts[i], equalTo(client().prepareCount(indices[i]).get().getCount())); - } - - logger.info(""--> snapshot subset of indices after upgrade""); - createSnapshotResponse = client().admin().cluster().prepareCreateSnapshot(""test-repo"", ""test-snap-2"").setWaitForCompletion(true).setIndices(""index_*"").get(); - assertThat(createSnapshotResponse.getSnapshotInfo().successfulShards(), greaterThan(0)); - assertThat(createSnapshotResponse.getSnapshotInfo().successfulShards(), equalTo(createSnapshotResponse.getSnapshotInfo().totalShards())); - - // Test restore after index deletion - logger.info(""--> delete indices""); - String index = RandomPicks.randomFrom(getRandom(), indices); - cluster().wipeIndices(index); - logger.info(""--> restore one index after deletion""); - restoreSnapshotResponse = client().admin().cluster().prepareRestoreSnapshot(""test-repo"", ""test-snap-2"").setWaitForCompletion(true).setIndices(index).execute().actionGet(); - assertThat(restoreSnapshotResponse.getRestoreInfo().totalShards(), greaterThan(0)); - ensureYellow(); - assertThat(client().prepareCount(indices).get().getCount(), equalTo((long) (buildersBefore.length + buildersAfter.length))); - for (int i = 0; i < indices.length; i++) { - assertThat(counts[i], equalTo(client().prepareCount(indices[i]).get().getCount())); - } - } - -" -46,0," public XMSSPrivateKeyParameters getNextKey() - { - /* prepare authentication path for next leaf */ - int treeHeight = this.params.getHeight(); - if (this.getIndex() < ((1 << treeHeight) - 1)) - { - return new XMSSPrivateKeyParameters.Builder(params) - .withSecretKeySeed(secretKeySeed).withSecretKeyPRF(secretKeyPRF) - .withPublicSeed(publicSeed).withRoot(root) - .withBDSState(bdsState.getNextState(publicSeed, secretKeySeed, (OTSHashAddress)new OTSHashAddress.Builder().build())).build(); - } - else - { - return new XMSSPrivateKeyParameters.Builder(params) - .withSecretKeySeed(secretKeySeed).withSecretKeyPRF(secretKeyPRF) - .withPublicSeed(publicSeed).withRoot(root) - .withBDSState(new BDS(params, getIndex() + 1)).build(); // no more nodes left. - } - } - -" -47,0," public void addRecipients(final ExtendedEmailPublisherContext context, EnvVars env, Set to, Set cc, Set 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(); - // looking for Upstream build. - Run cur = context.getRun(); - Cause.UpstreamCause upc = cur.getCause(Cause.UpstreamCause.class); - while (upc != null) { - // UpstreamCause.getUpStreamProject() returns the full name, so use getItemByFullName - 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); - } - addUserTriggeringTheBuild(cur, to, cc, bcc, env, context, debug); - } - -" -48,0," public void setSslSupport(SSLSupport sslSupport) { - this.sslSupport = sslSupport; - } -" -49,0," public void loadPropertyFile(String file, Properties target) - { - try - { - // Use SecuritySupport class to provide privileged access to property file - InputStream is = SecuritySupport.getResourceAsStream(ObjectFactory.findClassLoader(), - file); - - // get a buffered version - BufferedInputStream bis = new BufferedInputStream(is); - - target.load(bis); // and load up the property bag from this - bis.close(); // close out after reading - } - catch (Exception ex) - { - // ex.printStackTrace(); - throw new org.apache.xml.utils.WrappedRuntimeException(ex); - } - } -" -50,0," protected MimeTypes getMimeTypes() { - return embeddedDocumentUtil.getMimeTypes(); - } - -" -51,0," public int getKDFInfo() { - final int unusedBit28 = 0x8000000; // 1000000000000000000000000000 - - // kdf version is bits 1-27, bit 28 (reserved) should be 0, and - // bits 29-32 are the MAC algorithm indicating which PRF to use for the KDF. - int kdfVers = getKDFVersion(); - assert kdfVers > 0 && kdfVers <= 99991231 : ""KDF version (YYYYMMDD, max 99991231) out of range: "" + kdfVers; - int kdfInfo = kdfVers; - int macAlg = kdfPRFAsInt(); - assert macAlg >= 0 && macAlg <= 15 : ""MAC algorithm indicator must be between 0 to 15 inclusion; value is: "" + macAlg; - - // Make sure bit28 is cleared. (Reserved for future use.) - kdfInfo &= ~unusedBit28; - - // Set MAC algorithm bits in high (MSB) nibble. - kdfInfo |= (macAlg << 28); - - return kdfInfo; - } -" -52,0," private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { - stream.defaultReadObject(); - EVIL_BIT = 1; - } - - } - -} -" -53,0," public void onStartup(Set> c, ServletContext ctx) - throws ServletException { - Servlet s; - - if (createServlet) { - s = ctx.createServlet(servlet.getClass()); - } else { - s = servlet; - } - ServletRegistration.Dynamic r = ctx.addServlet(""servlet"", s); - r.addMapping(""/""); - } - } -} -" -54,0," public ResetPasswordResponse resetPassword(String code, String newPassword) throws InvalidPasswordException { - try { - passwordValidator.validate(newPassword); - return changePasswordCodeAuthenticated(code, newPassword); - } catch (RestClientException e) { - throw new UaaException(e.getMessage()); - } - } - -" -55,0," public Api getApi() { - return new Api(this); - } - - /** - * Returns the instance of this class. - * If {@link jenkins.model.Jenkins#getInstance()} isn't available - * or the plugin class isn't registered null will be returned. - * - * @return the instance. - */ - @CheckForNull -" -56,0," protected int readMessage(AjpMessage message, boolean blockFirstRead) - throws IOException { - - byte[] buf = message.getBuffer(); - int headerLength = message.getHeaderLength(); - - int bytesRead = read(buf, 0, headerLength, blockFirstRead); - - if (bytesRead == 0) { - return 0; - } - - int messageLength = message.processHeader(true); - if (messageLength < 0) { - // Invalid AJP header signature - throw new IOException(sm.getString(""ajpmessage.invalidLength"", - Integer.valueOf(messageLength))); - } - else if (messageLength == 0) { - // Zero length message. - return bytesRead; - } - else { - if (messageLength > buf.length) { - // Message too long for the buffer - // Need to trigger a 400 response - throw new IllegalArgumentException(sm.getString( - ""ajpprocessor.header.tooLong"", - Integer.valueOf(messageLength), - Integer.valueOf(buf.length))); - } - bytesRead += read(buf, headerLength, messageLength, true); - return bytesRead; - } - } - - -" -57,0," public boolean isHA() { - return false; - } - - @Override -" -58,0," public XMSSMTPrivateKeyParameters getNextKey() - { - BDSStateMap newState = new BDSStateMap(bdsState, params, this.getIndex(), publicSeed, secretKeySeed); - - return new XMSSMTPrivateKeyParameters.Builder(params).withIndex(index + 1) - .withSecretKeySeed(secretKeySeed).withSecretKeyPRF(secretKeyPRF) - .withPublicSeed(publicSeed).withRoot(root) - .withBDSState(newState).build(); - } -" -59,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; - } - -" -60,0," long getTimeStamp(); - -" -61,0," public void init(KeyGenerationParameters param) - { - this.param = (RSAKeyGenerationParameters)param; - } - -" -62,0," public Document getMetaData(Idp config) throws RuntimeException { - try { - //Return as text/xml - Crypto crypto = CertsUtils.createCrypto(config.getCertificate()); - - W3CDOMStreamWriter writer = new W3CDOMStreamWriter(); - - writer.writeStartDocument(""UTF-8"", ""1.0""); - - String referenceID = IDGenerator.generateID(""_""); - writer.writeStartElement(""md"", ""EntityDescriptor"", SAML2_METADATA_NS); - writer.writeAttribute(""ID"", referenceID); - - writer.writeAttribute(""entityID"", config.getIdpUrl().toString()); - - 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); - - writeFederationMetadata(writer, config, crypto); - - writer.writeEndElement(); // EntityDescriptor - - writer.writeEndDocument(); - - writer.close(); - - if (LOG.isDebugEnabled()) { - String out = DOM2Writer.nodeToString(writer.getDocument()); - LOG.debug(""***************** unsigned ****************""); - LOG.debug(out); - LOG.debug(""***************** unsigned ****************""); - } - - Document result = SignatureUtils.signMetaInfo(crypto, null, config.getCertificatePassword(), - writer.getDocument(), referenceID); - if (result != null) { - return result; - } else { - throw new RuntimeException(""Failed to sign the metadata document: result=null""); - } - } catch (Exception e) { - LOG.error(""Error creating service metadata information "", e); - throw new RuntimeException(""Error creating service metadata information: "" + e.getMessage()); - } - - } - -" -63,0," protected void publish(ApplicationEvent event) { - if (publisher!=null) { - publisher.publishEvent(event); - } - } -" -64,0," private static File getUnsanitizedLegacyConfigFileFor(String id) { - return new File(getRootDir(), idStrategy().legacyFilenameOf(id) + ""/config.xml""); - } - - /** - * Gets the directory where Hudson stores user information. - */ -" -65,0," protected void _initFactories(XMLInputFactory xmlIn, XMLOutputFactory xmlOut) - { - // Better ensure namespaces get built properly, so: - xmlOut.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, Boolean.TRUE); - // and for parser, force coalescing as well (much simpler to use) - xmlIn.setProperty(XMLInputFactory.IS_COALESCING, Boolean.TRUE); - } - - /** - * Note: compared to base implementation by {@link JsonFactory}, - * here the copy will actually share underlying XML input and - * output factories, as there is no way to make copies of those. - * - * @since 2.1 - */ - @Override -" -66,0," public ScimUser retrieve(String id) { - try { - ScimUser u = jdbcTemplate.queryForObject(USER_BY_ID_QUERY, mapper, id); - return u; - } catch (EmptyResultDataAccessException e) { - throw new ScimResourceNotFoundException(""User "" + id + "" does not exist""); - } - } - - @Override -" -67,0," private T run(PrivilegedAction action) { - return System.getSecurityManager() != null ? AccessController.doPrivileged( action ) : action.run(); - } -" -68,0," public boolean getMapperDirectoryRedirectEnabled() { return false; } -" -69,0," protected void setUpResources(JAXRSServerFactoryBean sf) { - sf.setResourceClasses(TikaResource.class); - sf.setResourceProvider(TikaResource.class, - new SingletonResourceProvider(new TikaResource())); - } - - @Override -" -70,0," public HttpBinding getBinding() { - if (this.binding == null) { - this.binding = new AttachmentHttpBinding(); - this.binding.setTransferException(isTransferException()); - if (getComponent() != null) { - this.binding.setAllowJavaSerializedObject(getComponent().isAllowJavaSerializedObject()); - } - this.binding.setHeaderFilterStrategy(getHeaderFilterStrategy()); - } - return this.binding; - } - - @Override -" -71,0," public void testNamedEntity() throws Exception { - assertU(""\n""+ - ""\n]>""+ - """"+ - ""1""+ - ""&wacky;"" + - """"); - - assertU(""""); - assertQ(req(""foo_s:zzz""), - ""//*[@numFound='1']"" - ); - } - - @Test -" -72,0," private FreeStyleProject createDownstreamProject() throws Exception { - FreeStyleProject dp = createFreeStyleProject(""downstream""); - - // Hm, no setQuietPeriod, have to submit form.. - WebClient webClient = new WebClient(); - HtmlPage page = webClient.getPage(dp,""configure""); - HtmlForm form = page.getFormByName(""config""); - form.getInputByName(""hasCustomQuietPeriod"").click(); - form.getInputByName(""quiet_period"").setValueAttribute(""0""); - submit(form); - assertEquals(""set quiet period"", 0, dp.getQuietPeriod()); - - return dp; - } - -" -73,0," public void setOkStatusCodeRange(String okStatusCodeRange) { - this.okStatusCodeRange = okStatusCodeRange; - } -" -74,0," public boolean shouldParseEmbedded(Metadata metadata) { - DocumentSelector selector = context.get(DocumentSelector.class); - if (selector != null) { - return selector.select(metadata); - } - - FilenameFilter filter = context.get(FilenameFilter.class); - if (filter != null) { - String name = metadata.get(Metadata.RESOURCE_NAME_KEY); - if (name != null) { - return filter.accept(ABSTRACT_PATH, name); - } - } - - return true; - } - -" -75,0," public void testLockTryingToDelete() throws Exception { - String lockType = ""native""; // test does not work with simple locks - Settings nodeSettings = ImmutableSettings.builder() - .put(""gateway.type"", ""local"") // don't delete things! - .put(""index.store.fs.fs_lock"", lockType) - .build(); - String IDX = ""test""; - logger.info(""--> lock type: {}"", lockType); - - internalCluster().startNode(nodeSettings); - Settings idxSettings = ImmutableSettings.builder() - .put(IndexMetaData.SETTING_NUMBER_OF_SHARDS, 1) - .put(IndexMetaData.SETTING_NUMBER_OF_REPLICAS, 0) - .put(""index.store.fs.fs_lock"", lockType) - .build(); - - // only one node, so all primaries will end up on node1 - prepareCreate(IDX).setSettings(idxSettings).addMapping(""doc"", ""foo"", ""type=string,index=not_analyzed"").get(); - ensureGreen(IDX); - client().prepareIndex(IDX, ""doc"").setSource(""foo"", ""bar"").get(); - flushAndRefresh(IDX); - NodeEnvironment env = internalCluster().getDataNodeInstance(NodeEnvironment.class); - logger.info(""--> data paths: [{}]"", env.nodeDataPaths()); - Path[] shardPaths = env.shardDataPaths(new ShardId(""test"", 0), ImmutableSettings.builder().build()); - logger.info(""--> paths: [{}]"", shardPaths); - // Should not be able to acquire the lock because it's already open - try { - NodeEnvironment.acquireFSLockForPaths(ImmutableSettings.EMPTY, shardPaths); - fail(""should not have been able to acquire the lock""); - } catch (ElasticsearchException e) { - assertTrue(""msg: "" + e.getMessage(), e.getMessage().contains(""unable to acquire write.lock"")); - } - // Test without the regular shard lock to assume we can acquire it - // (worst case, meaning that the shard lock could be acquired and - // we're green to delete the shard's directory) - ShardLock sLock = new DummyShardLock(new ShardId(""test"", 0)); - try { - env.deleteShardDirectoryUnderLock(sLock, ImmutableSettings.builder().build()); - fail(""should not have been able to delete the directory""); - } catch (ElasticsearchException e) { - assertTrue(""msg: "" + e.getMessage(), e.getMessage().contains(""unable to acquire write.lock"")); - } - } -" -76,0," public KeyPair generateKeyPair() - { - if (!initialised) - { - Integer paramStrength = Integers.valueOf(strength); - - if (params.containsKey(paramStrength)) - { - param = (DSAKeyGenerationParameters)params.get(paramStrength); - } - else - { - synchronized (lock) - { - // we do the check again in case we were blocked by a generator for - // our key size. - if (params.containsKey(paramStrength)) - { - param = (DSAKeyGenerationParameters)params.get(paramStrength); - } - else - { - DSAParametersGenerator pGen; - DSAParameterGenerationParameters dsaParams; - - // Typical combination of keysize and size of q. - // keysize = 1024, q's size = 160 - // keysize = 2048, q's size = 224 - // keysize = 2048, q's size = 256 - // keysize = 3072, q's size = 256 - // For simplicity if keysize is greater than 1024 then we choose q's size to be 256. - // For legacy keysize that is less than 1024-bit, we just use the 186-2 style parameters - if (strength == 1024) - { - pGen = new DSAParametersGenerator(); - if (Properties.isOverrideSet(""org.bouncycastle.dsa.FIPS186-2for1024bits"")) - { - pGen.init(strength, certainty, random); - } - else - { - dsaParams = new DSAParameterGenerationParameters(1024, 160, certainty, random); - pGen.init(dsaParams); - } - } - else if (strength > 1024) - { - dsaParams = new DSAParameterGenerationParameters(strength, 256, certainty, random); - pGen = new DSAParametersGenerator(new SHA256Digest()); - pGen.init(dsaParams); - } - else - { - pGen = new DSAParametersGenerator(); - pGen.init(strength, certainty, random); - } - param = new DSAKeyGenerationParameters(random, pGen.generateParameters()); - - params.put(paramStrength, param); - } - } - } - - engine.init(param); - initialised = true; - } - - AsymmetricCipherKeyPair pair = engine.generateKeyPair(); - DSAPublicKeyParameters pub = (DSAPublicKeyParameters)pair.getPublic(); - DSAPrivateKeyParameters priv = (DSAPrivateKeyParameters)pair.getPrivate(); - - return new KeyPair(new BCDSAPublicKey(pub), new BCDSAPrivateKey(priv)); - } -" -77,0," Attributes setPropertiesFromAttributes( - StylesheetHandler handler, String rawName, Attributes attributes, - ElemTemplateElement target, boolean throwError) - throws org.xml.sax.SAXException - { - - XSLTElementDef def = getElemDef(); - AttributesImpl undefines = null; - boolean isCompatibleMode = ((null != handler.getStylesheet() - && handler.getStylesheet().getCompatibleMode()) - || !throwError); - if (isCompatibleMode) - undefines = new AttributesImpl(); - - - // Keep track of which XSLTAttributeDefs have been processed, so - // I can see which default values need to be set. - List processedDefs = new ArrayList(); - - // Keep track of XSLTAttributeDefs that were invalid - List errorDefs = new ArrayList(); - int nAttrs = attributes.getLength(); - - for (int i = 0; i < nAttrs; i++) - { - String attrUri = attributes.getURI(i); - // Hack for Crimson. -sb - if((null != attrUri) && (attrUri.length() == 0) - && (attributes.getQName(i).startsWith(""xmlns:"") || - attributes.getQName(i).equals(""xmlns""))) - { - attrUri = org.apache.xalan.templates.Constants.S_XMLNAMESPACEURI; - } - String attrLocalName = attributes.getLocalName(i); - XSLTAttributeDef attrDef = def.getAttributeDef(attrUri, attrLocalName); - - if (null == attrDef) - { - if (!isCompatibleMode) - { - - // Then barf, because this element does not allow this attribute. - handler.error(XSLTErrorResources.ER_ATTR_NOT_ALLOWED, new Object[]{attributes.getQName(i), rawName}, null);//""\""""+attributes.getQName(i)+""\"""" - //+ "" attribute is not allowed on the "" + rawName - // + "" element!"", null); - } - else - { - undefines.addAttribute(attrUri, attrLocalName, - attributes.getQName(i), - attributes.getType(i), - attributes.getValue(i)); - } - } - else - { - //handle secure processing - if(handler.getStylesheetProcessor()==null) - System.out.println(""stylesheet processor null""); - if(attrDef.getName().compareTo(""*"")==0 && handler.getStylesheetProcessor().isSecureProcessing()) - { - //foreign attributes are not allowed in secure processing mode - // Then barf, because this element does not allow this attribute. - handler.error(XSLTErrorResources.ER_ATTR_NOT_ALLOWED, new Object[]{attributes.getQName(i), rawName}, null);//""\""""+attributes.getQName(i)+""\"""" - //+ "" attribute is not allowed on the "" + rawName - // + "" element!"", null); - } - else - { - - - boolean success = attrDef.setAttrValue(handler, attrUri, attrLocalName, - attributes.getQName(i), attributes.getValue(i), - target); - - // Now we only add the element if it passed a validation check - if (success) - processedDefs.add(attrDef); - else - errorDefs.add(attrDef); - } - } - } - - XSLTAttributeDef[] attrDefs = def.getAttributes(); - int nAttrDefs = attrDefs.length; - - for (int i = 0; i < nAttrDefs; i++) - { - XSLTAttributeDef attrDef = attrDefs[i]; - String defVal = attrDef.getDefault(); - - if (null != defVal) - { - if (!processedDefs.contains(attrDef)) - { - attrDef.setDefAttrValue(handler, target); - } - } - - if (attrDef.getRequired()) - { - if ((!processedDefs.contains(attrDef)) && (!errorDefs.contains(attrDef))) - handler.error( - XSLMessages.createMessage( - XSLTErrorResources.ER_REQUIRES_ATTRIB, new Object[]{ rawName, - attrDef.getName() }), null); - } - } - - return undefines; - } -" -78,0," public static void beforeClass() throws Exception { - SUITE_SEED = randomLong(); - initializeSuiteScope(); - } - -" -79,0," public void connect(HttpConsumer consumer) throws Exception { - } - - /** - * Disconnects the URL specified on the endpoint from the specified processor. - * - * @param consumer the consumer - * @throws Exception can be thrown - */ -" -80,0," private void writeAttribute(SessionAttribute sessionAttribute) throws IOException { - write(""""); - writeDirectly(htmlEncodeButNotSpace(sessionAttribute.getName())); - write(""""); - write(String.valueOf(sessionAttribute.getType())); - write(""""); - if (sessionAttribute.isSerializable()) { - write(""#oui#""); - } else { - write(""#non#""); - } - write(""""); - write(integerFormat.format(sessionAttribute.getSerializedSize())); - write(""""); - writeDirectly(htmlEncodeButNotSpace(String.valueOf(sessionAttribute.getContent()))); - write(""""); - } -" -81,0," public boolean isUseRouteBuilder() { - return false; - } - - @Test - @Ignore -" -82,0," public String getDisplayName() { - return ""Developers""; - } - } -} -" -83,0," private T run(PrivilegedExceptionAction action) throws JAXBException { - try { - return System.getSecurityManager() != null ? AccessController.doPrivileged( action ) : action.run(); - } - catch ( JAXBException e ) { - throw e; - } - catch ( Exception e ) { - throw log.getErrorParsingMappingFileException( e ); - } - } - - // JAXB closes the underlying input stream -" -84,0," protected void checkIllegalTypes(DeserializationContext ctxt, JavaType type, - BeanDescription beanDesc) - throws JsonMappingException - { - // There are certain nasty classes that could cause problems, mostly - // via default typing -- catch them here. - String full = type.getRawClass().getName(); - - if (_cfgIllegalClassNames.contains(full)) { - throw JsonMappingException.from(ctxt, - String.format(""Illegal type (%s) to deserialize: prevented for security reasons"", full)); - } - } -" -85,0," public FileVisitResult postVisitDirectory(Path dir, IOException ioe) - throws IOException { - // NO-OP - return FileVisitResult.CONTINUE; - }}); - } -} -" -86,0," public JettyHttpEndpoint getEndpoint() { - return (JettyHttpEndpoint) super.getEndpoint(); - } - -" -87,0," public static File randomRepoPath(Settings settings) { - Environment environment = new Environment(settings); - File[] repoFiles = environment.repoFiles(); - assert repoFiles.length > 0; - File path; - do { - path = new File(repoFiles[0], randomAsciiOfLength(10)); - } while (path.exists()); - return path; - } - -" -88,0," public void setup() { - this.request = new MockHttpServletRequest(); - this.request.setMethod(""GET""); - this.response = new MockHttpServletResponse(); - this.chain = new MockFilterChain(); - } - - @After -" -89,0," public static Context getCurrentContext() - { - return __context.get(); - } - -" -90,0," protected Log getLog() { - return log; - } - - // ----------------------------------------------------------- Constructors - - -" -91,0," protected void checkIllegalTypes(DeserializationContext ctxt, JavaType type, - BeanDescription beanDesc) - throws JsonMappingException - { - // There are certain nasty classes that could cause problems, mostly - // via default typing -- catch them here. - String full = type.getRawClass().getName(); - - if (_cfgIllegalClassNames.contains(full)) { - ctxt.reportBadTypeDefinition(beanDesc, - ""Illegal type (%s) to deserialize: prevented for security reasons"", full); - } - } -" -92,0," public String toString() { - return xpathExpression; - } -" -93,0," protected void setLocale(HttpServletRequest request) { - if (defaultLocale == null) { - defaultLocale = request.getLocale(); - } - } - -" -94,0," protected boolean isWithinLengthLimit( String name ) { - return name.length() <= paramNameMaxLength; - } - -" -95,0," private CoderResult decodeHasArray(ByteBuffer in, CharBuffer out) { - int outRemaining = out.remaining(); - int pos = in.position(); - int limit = in.limit(); - final byte[] bArr = in.array(); - final char[] cArr = out.array(); - final int inIndexLimit = limit + in.arrayOffset(); - int inIndex = pos + in.arrayOffset(); - int outIndex = out.position() + out.arrayOffset(); - // if someone would change the limit in process, - // he would face consequences - for (; inIndex < inIndexLimit && outRemaining > 0; inIndex++) { - int jchar = bArr[inIndex]; - if (jchar < 0) { - jchar = jchar & 0x7F; - int tail = remainingBytes[jchar]; - if (tail == -1) { - in.position(inIndex - in.arrayOffset()); - out.position(outIndex - out.arrayOffset()); - return CoderResult.malformedForLength(1); - } - if (inIndexLimit - inIndex < 1 + tail) { - // Apache Tomcat added tests - detect invalid sequences as - // early as possible - if (jchar == 0x74 && inIndexLimit > inIndex + 1) { - if ((bArr[inIndex + 1] & 0xFF) > 0x8F) { - // 11110100 1yyyxxxx xxxxxxxx xxxxxxxx - // Any non-zero y is > max code point - return CoderResult.unmappableForLength(4); - } - } - if (jchar == 0x60 && inIndexLimit > inIndex +1) { - if ((bArr[inIndex + 1] & 0x7F) == 0) { - // 11100000 10000000 10xxxxxx - // should have been - // 00xxxxxx - return CoderResult.malformedForLength(3); - } - } - if (jchar == 0x70 && inIndexLimit > inIndex +1) { - if ((bArr[inIndex + 1] & 0x7F) < 0x10) { - // 11110000 1000zzzz 1oyyyyyy 1oxxxxxx - // should have been - // 111ozzzz 1oyyyyyy 1oxxxxxx - return CoderResult.malformedForLength(4); - } - } - break; - } - for (int i = 0; i < tail; i++) { - int nextByte = bArr[inIndex + i + 1] & 0xFF; - if ((nextByte & 0xC0) != 0x80) { - in.position(inIndex - in.arrayOffset()); - out.position(outIndex - out.arrayOffset()); - return CoderResult.malformedForLength(1 + i); - } - jchar = (jchar << 6) + nextByte; - } - jchar -= remainingNumbers[tail]; - if (jchar < lowerEncodingLimit[tail]) { - // Should have been encoded in fewer octets - in.position(inIndex - in.arrayOffset()); - out.position(outIndex - out.arrayOffset()); - return CoderResult.malformedForLength(1); - } - inIndex += tail; - } - // Apache Tomcat added test - if (jchar >= 0xD800 && jchar <= 0xDFFF) { - return CoderResult.unmappableForLength(3); - } - // Apache Tomcat added test - if (jchar > 0x10FFFF) { - return CoderResult.unmappableForLength(4); - } - if (jchar <= 0xffff) { - cArr[outIndex++] = (char) jchar; - outRemaining--; - } else { - if (outRemaining < 2) { - return CoderResult.OVERFLOW; - } - cArr[outIndex++] = (char) ((jchar >> 0xA) + 0xD7C0); - cArr[outIndex++] = (char) ((jchar & 0x3FF) + 0xDC00); - outRemaining -= 2; - } - } - in.position(inIndex - in.arrayOffset()); - out.position(outIndex - out.arrayOffset()); - return (outRemaining == 0 && inIndex < inIndexLimit) ? CoderResult.OVERFLOW - : CoderResult.UNDERFLOW; - } -" -96,0," public static CipherText fromPortableSerializedBytes(byte[] bytes) - throws EncryptionException - { - CipherTextSerializer cts = new CipherTextSerializer(bytes); - return cts.asCipherText(); - } - - ///////////////////////// P U B L I C M E T H O D S //////////////////// - - /** - * Obtain the String representing the cipher transformation used to encrypt - * the plaintext. The cipher transformation represents the cipher algorithm, - * the cipher mode, and the padding scheme used to do the encryption. An - * example would be ""AES/CBC/PKCS5Padding"". See Appendix A in the - * - * Java Cryptography Architecture Reference Guide - * for information about standard supported cipher transformation names. - *

- * The cipher transformation name is usually sufficient to be passed to - * {@link javax.crypto.Cipher#getInstance(String)} to create a - * Cipher object to decrypt the ciphertext. - * - * @return The cipher transformation name used to encrypt the plaintext - * resulting in this ciphertext. - */ -" -97,0," protected void _verifyException(Throwable t, Class expExcType, - String... patterns) throws Exception - { - Class actExc = t.getClass(); - if (!expExcType.isAssignableFrom(actExc)) { - fail(""Expected Exception of type '""+expExcType.getName()+""', got '"" - +actExc.getName()+""', message: ""+t.getMessage()); - } - for (String pattern : patterns) { - verifyException(t, pattern); - } - } -" -98,0," public String getCompression() { - switch (compressionLevel) { - case 0: - return ""off""; - case 1: - return ""on""; - case 2: - return ""force""; - } - return ""off""; - } - - - /** - * Set compression level. - */ -" -99,0," public void close() throws IOException { - if (authFilter != null) { - authFilter.destroy(); - } - } -" -100,0," public void destroy() { - } - }; - -" -101,0," public O getOrBuild() { - if (isUnbuilt()) { - try { - return build(); - } - catch (Exception e) { - logger.debug(""Failed to perform build. Returning null"", e); - return null; - } - } - else { - return getObject(); - } - } - - /** - * Applies a {@link SecurityConfigurerAdapter} to this {@link SecurityBuilder} and - * invokes {@link SecurityConfigurerAdapter#setBuilder(SecurityBuilder)}. - * - * @param configurer - * @return - * @throws Exception - */ - @SuppressWarnings(""unchecked"") -" -102,0," private void testModified() - throws Exception - { - ECNamedCurveParameterSpec namedCurve = ECNamedCurveTable.getParameterSpec(""P-256""); - org.bouncycastle.jce.spec.ECPublicKeySpec pubSpec = new org.bouncycastle.jce.spec.ECPublicKeySpec(namedCurve.getCurve().createPoint(PubX, PubY), namedCurve); - KeyFactory kFact = KeyFactory.getInstance(""EC"", ""BC""); - PublicKey pubKey = kFact.generatePublic(pubSpec); - Signature sig = Signature.getInstance(""SHA256WithECDSA"", ""BC""); - - for (int i = 0; i != MODIFIED_SIGNATURES.length; i++) - { - sig.initVerify(pubKey); - - sig.update(Strings.toByteArray(""Hello"")); - - boolean failed; - - try - { - failed = !sig.verify(Hex.decode(MODIFIED_SIGNATURES[i])); - System.err.println(ASN1Dump.dumpAsString(ASN1Primitive.fromByteArray(Hex.decode(MODIFIED_SIGNATURES[i])))); - } - catch (SignatureException e) - { - failed = true; - } - - isTrue(""sig verified when shouldn't: "" + i, failed); - } - } - -" -103,0," protected void populateParams() { - super.populateParams(); - - UIBean uiBean = (UIBean) component; - uiBean.setCssClass(cssClass); - uiBean.setCssStyle(cssStyle); - uiBean.setCssErrorClass(cssErrorClass); - uiBean.setCssErrorStyle(cssErrorStyle); - uiBean.setTitle(title); - uiBean.setDisabled(disabled); - uiBean.setLabel(label); - uiBean.setLabelSeparator(labelSeparator); - uiBean.setLabelposition(labelposition); - uiBean.setRequiredPosition(requiredPosition); - uiBean.setErrorPosition(errorPosition); - uiBean.setName(name); - uiBean.setRequiredLabel(requiredLabel); - uiBean.setTabindex(tabindex); - uiBean.setValue(value); - uiBean.setTemplate(template); - uiBean.setTheme(theme); - uiBean.setTemplateDir(templateDir); - uiBean.setOnclick(onclick); - uiBean.setOndblclick(ondblclick); - uiBean.setOnmousedown(onmousedown); - uiBean.setOnmouseup(onmouseup); - uiBean.setOnmouseover(onmouseover); - uiBean.setOnmousemove(onmousemove); - uiBean.setOnmouseout(onmouseout); - uiBean.setOnfocus(onfocus); - uiBean.setOnblur(onblur); - uiBean.setOnkeypress(onkeypress); - uiBean.setOnkeydown(onkeydown); - uiBean.setOnkeyup(onkeyup); - uiBean.setOnselect(onselect); - uiBean.setOnchange(onchange); - uiBean.setTooltip(tooltip); - uiBean.setTooltipConfig(tooltipConfig); - uiBean.setJavascriptTooltip(javascriptTooltip); - uiBean.setTooltipCssClass(tooltipCssClass); - uiBean.setTooltipDelay(tooltipDelay); - uiBean.setTooltipIconPath(tooltipIconPath); - uiBean.setAccesskey(accesskey); - uiBean.setKey(key); - uiBean.setId(id); - - uiBean.setDynamicAttributes(dynamicAttributes); - } - -" -104,0," public long getTimestamp() { - return timestamp; - } - } -} -" -105,0," public boolean isUseRouteBuilder() { - return false; - } - - @Test -" -106,0," public ServerSocket createSocket (int port, int backlog, - InetAddress ifAddress) - throws IOException - { - if (!initialized) init(); - ServerSocket socket = sslProxy.createServerSocket(port, backlog, - ifAddress); - initServerSocket(socket); - return socket; - } - -" -107,0," public static void init() throws Exception { - - idpHttpsPort = System.getProperty(""idp.https.port""); - Assert.assertNotNull(""Property 'idp.https.port' null"", idpHttpsPort); - rpHttpsPort = System.getProperty(""rp.https.port""); - Assert.assertNotNull(""Property 'rp.https.port' null"", rpHttpsPort); - - idpServer = startServer(true, idpHttpsPort); - - WSSConfig.init(); - } - -" -108,0," public void testPrivateKeySerialisation() - throws Exception - { - String stream = ""AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAArO0ABXNyACJzdW4ucm1pLnNlcnZlci5BY3RpdmF0aW9uR3JvdXBJbXBsT+r9SAwuMqcCAARaAA1ncm91cEluYWN0aXZlTAAGYWN0aXZldAAVTGphdmEvdXRpbC9IYXNodGFibGU7TAAHZ3JvdXBJRHQAJ0xqYXZhL3JtaS9hY3RpdmF0aW9uL0FjdGl2YXRpb25Hcm91cElEO0wACWxvY2tlZElEc3QAEExqYXZhL3V0aWwvTGlzdDt4cgAjamF2YS5ybWkuYWN0aXZhdGlvbi5BY3RpdmF0aW9uR3JvdXCVLvKwBSnVVAIAA0oAC2luY2FybmF0aW9uTAAHZ3JvdXBJRHEAfgACTAAHbW9uaXRvcnQAJ0xqYXZhL3JtaS9hY3RpdmF0aW9uL0FjdGl2YXRpb25Nb25pdG9yO3hyACNqYXZhLnJtaS5zZXJ2ZXIuVW5pY2FzdFJlbW90ZU9iamVjdEUJEhX14n4xAgADSQAEcG9ydEwAA2NzZnQAKExqYXZhL3JtaS9zZXJ2ZXIvUk1JQ2xpZW50U29ja2V0RmFjdG9yeTtMAANzc2Z0AChMamF2YS9ybWkvc2VydmVyL1JNSVNlcnZlclNvY2tldEZhY3Rvcnk7eHIAHGphdmEucm1pLnNlcnZlci5SZW1vdGVTZXJ2ZXLHGQcSaPM5+wIAAHhyABxqYXZhLnJtaS5zZXJ2ZXIuUmVtb3RlT2JqZWN002G0kQxhMx4DAAB4cHcSABBVbmljYXN0U2VydmVyUmVmeAAAFbNwcAAAAAAAAAAAcHAAcHBw""; - - XMSSParameters params = new XMSSParameters(10, new SHA256Digest()); - - byte[] output = Base64.decode(new String(stream).getBytes(""UTF-8"")); - - - //Simple Exploit - - try - { - new XMSSPrivateKeyParameters.Builder(params).withPrivateKey(output, params).build(); - } - catch (IllegalArgumentException e) - { - assertTrue(e.getCause() instanceof IOException); - } - - //Same Exploit other method - - XMSS xmss2 = new XMSS(params, new SecureRandom()); - - xmss2.generateKeys(); - - byte[] publicKey = xmss2.exportPublicKey(); - - try - { - xmss2.importState(output, publicKey); - } - catch (IllegalArgumentException e) - { - assertTrue(e.getCause() instanceof IOException); - } - } - -" -109,0," public void setAllowJavaSerializedObject(boolean allowJavaSerializedObject) { - this.allowJavaSerializedObject = allowJavaSerializedObject; - } - -" -110,0," public Collection getRequiredPermissions(String regionName) { - return Collections.singletonList(new ResourcePermission(ResourcePermission.Resource.DATA, - ResourcePermission.Operation.READ, regionName)); - } - -" -111,0," abstract protected JDBCTableReader getTableReader(Connection connection, - String tableName, - EmbeddedDocumentUtil embeddedDocumentUtil); - -" -112,0," public FederationConfig getFederationConfig() { - return federationConfig; - } - -" -113,0," protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) - throws ServletException, IOException { - - String identityZoneId = request.getHeader(HEADER); - if (StringUtils.hasText(identityZoneId)) { - if (!isAuthorizedToSwitchToIdentityZone(identityZoneId)) { - response.sendError(HttpServletResponse.SC_FORBIDDEN, ""User is not authorized to switch to IdentityZone with id ""+identityZoneId); - return; - } - IdentityZone originalIdentityZone = IdentityZoneHolder.get(); - try { - - IdentityZone identityZone = null; - try { - identityZone = dao.retrieve(identityZoneId); - } catch (ZoneDoesNotExistsException ex) { - } catch (EmptyResultDataAccessException ex) { - } catch (Exception ex) { - throw ex; - } - if (identityZone == null) { - response.sendError(HttpServletResponse.SC_NOT_FOUND, ""Identity zone with id ""+identityZoneId+"" does not exist""); - return; - } - stripScopesFromAuthentication(identityZoneId, request); - IdentityZoneHolder.set(identityZone); - filterChain.doFilter(request, response); - } finally { - IdentityZoneHolder.set(originalIdentityZone); - } - } else { - filterChain.doFilter(request, response); - } - } -" -114,0," public BeanDefinition createMatcher(ParserContext pc, String path, String method) { - if ((""/**"".equals(path) || ""**"".equals(path)) && method == null) { - return new RootBeanDefinition(AnyRequestMatcher.class); - } - - BeanDefinitionBuilder matcherBldr = BeanDefinitionBuilder - .rootBeanDefinition(type); - - if (this == mvc) { - if (!pc.getRegistry().isBeanNameInUse(HANDLER_MAPPING_INTROSPECTOR_BEAN_NAME)) { - BeanDefinitionBuilder hmifb = BeanDefinitionBuilder - .rootBeanDefinition(HandlerMappingIntrospectorFactoryBean.class); - pc.getRegistry().registerBeanDefinition(HANDLER_MAPPING_INTROSPECTOR_FACTORY_BEAN_NAME, - hmifb.getBeanDefinition()); - - RootBeanDefinition hmi = new RootBeanDefinition(HANDLER_MAPPING_INTROSPECTOR_BEAN_NAME); - hmi.setFactoryBeanName(HANDLER_MAPPING_INTROSPECTOR_FACTORY_BEAN_NAME); - hmi.setFactoryMethodName(""createHandlerMappingIntrospector""); - pc.getRegistry().registerBeanDefinition(HANDLER_MAPPING_INTROSPECTOR_BEAN_NAME, hmi); - } - matcherBldr.addConstructorArgReference(HANDLER_MAPPING_INTROSPECTOR_BEAN_NAME); - } - - matcherBldr.addConstructorArgValue(path); - if (this == mvc) { - matcherBldr.addPropertyValue(""method"", method); - } - else { - matcherBldr.addConstructorArgValue(method); - } - - if (this == ciRegex) { - matcherBldr.addConstructorArgValue(true); - } - - return matcherBldr.getBeanDefinition(); - } - -" -115,0," protected Settings nodeSettings(int nodeOrdinal) { - return ImmutableSettings.builder() - // we really need local GW here since this also checks for corruption etc. - // and we need to make sure primaries are not just trashed if we don't have replicas - .put(super.nodeSettings(nodeOrdinal)).put(""gateway.type"", ""local"") - .put(TransportModule.TRANSPORT_SERVICE_TYPE_KEY, MockTransportService.class.getName()) - // speed up recoveries - .put(RecoverySettings.INDICES_RECOVERY_CONCURRENT_STREAMS, 10) - .put(RecoverySettings.INDICES_RECOVERY_CONCURRENT_SMALL_FILE_STREAMS, 10) - .put(ThrottlingAllocationDecider.CLUSTER_ROUTING_ALLOCATION_NODE_CONCURRENT_RECOVERIES, 5) - .build(); - } - - /** - * Tests that we can actually recover from a corruption on the primary given that we have replica shards around. - */ - @Test -" -116,0," private void writeFederationMetadata( - XMLStreamWriter writer, Idp config, Crypto crypto - ) throws XMLStreamException { - - writer.writeStartElement(""md"", ""RoleDescriptor"", WS_FEDERATION_NS); - writer.writeAttribute(SCHEMA_INSTANCE_NS, ""type"", ""fed:SecurityTokenServiceType""); - writer.writeAttribute(""protocolSupportEnumeration"", WS_FEDERATION_NS); - if (config.getServiceDescription() != null && config.getServiceDescription().length() > 0 ) { - writer.writeAttribute(""ServiceDescription"", config.getServiceDescription()); - } - if (config.getServiceDisplayName() != null && config.getServiceDisplayName().length() > 0 ) { - writer.writeAttribute(""ServiceDisplayName"", config.getServiceDisplayName()); - } - - //http://docs.oasis-open.org/security/saml/v2.0/saml-schema-metadata-2.0.xsd - //missing organization, contactperson - - //KeyDescriptor - writer.writeStartElement("""", ""KeyDescriptor"", SAML2_METADATA_NS); - writer.writeAttribute(""use"", ""signing""); - writer.writeStartElement("""", ""KeyInfo"", ""http://www.w3.org/2000/09/xmldsig#""); - writer.writeStartElement("""", ""X509Data"", ""http://www.w3.org/2000/09/xmldsig#""); - writer.writeStartElement("""", ""X509Certificate"", ""http://www.w3.org/2000/09/xmldsig#""); - - try { - String keyAlias = crypto.getDefaultX509Identifier(); - X509Certificate cert = CertsUtils.getX509Certificate(crypto, keyAlias); - writer.writeCharacters(Base64.encode(cert.getEncoded())); - } catch (Exception ex) { - LOG.error(""Failed to add certificate information to metadata. Metadata incomplete"", ex); - } - - writer.writeEndElement(); // X509Certificate - writer.writeEndElement(); // X509Data - writer.writeEndElement(); // KeyInfo - writer.writeEndElement(); // KeyDescriptor - - - // SecurityTokenServiceEndpoint - writer.writeStartElement(""fed"", ""SecurityTokenServiceEndpoint"", WS_FEDERATION_NS); - writer.writeStartElement(""wsa"", ""EndpointReference"", WS_ADDRESSING_NS); - - writer.writeStartElement(""wsa"", ""Address"", WS_ADDRESSING_NS); - writer.writeCharacters(config.getStsUrl().toString()); - - writer.writeEndElement(); // Address - writer.writeEndElement(); // EndpointReference - writer.writeEndElement(); // SecurityTokenServiceEndpoint - - - // PassiveRequestorEndpoint - writer.writeStartElement(""fed"", ""PassiveRequestorEndpoint"", WS_FEDERATION_NS); - writer.writeStartElement(""wsa"", ""EndpointReference"", WS_ADDRESSING_NS); - - writer.writeStartElement(""wsa"", ""Address"", WS_ADDRESSING_NS); - writer.writeCharacters(config.getIdpUrl().toString()); - - writer.writeEndElement(); // Address - writer.writeEndElement(); // EndpointReference - writer.writeEndElement(); // PassiveRequestorEndpoint - - - // create ClaimsType section - if (config.getClaimTypesOffered() != null && config.getClaimTypesOffered().size() > 0) { - writer.writeStartElement(""fed"", ""ClaimTypesOffered"", WS_FEDERATION_NS); - for (Claim claim : config.getClaimTypesOffered()) { - - writer.writeStartElement(""auth"", ""ClaimType"", WS_FEDERATION_NS); - writer.writeAttribute(""Uri"", claim.getClaimType().toString()); - writer.writeAttribute(""Optional"", ""true""); - writer.writeEndElement(); // ClaimType - - } - writer.writeEndElement(); // ClaimTypesOffered - } - - writer.writeEndElement(); // RoleDescriptor - } - - -" -117,0," public Set getSupportedTypes(ParseContext context) { - return null; - } - - @Override -" -118,0," public Container getContainer() { - - return (container); - - } - - - /** - * Set the Container with which this Realm has been associated. - * - * @param container The associated Container - */ -" -119,0," public Set getSupportedTypes(ParseContext context) { - return null; - } - - @Override -" -120,0," public void testSendEntityMessage() throws Exception { - - MockEndpoint endpoint = getMockEndpoint(""mock:result""); - endpoint.expectedMessageCount(1); - //String message = ""]>&xxe;""; - - String message = """"; - template.sendBody(""direct:start2"", message); - - assertMockEndpointsSatisfied(); - - List list = endpoint.getReceivedExchanges(); - Exchange exchange = list.get(0); - String xml = exchange.getIn().getBody(String.class); - - System.out.println(xml); - } - -" -121,0," public void execute(FunctionContext context) { - RegionFunctionContext rfc = (RegionFunctionContext) context; - context.getResultSender().lastResult(rfc.getDataSet().size()); - } - - @Override -" -122,0," public DescriptorImpl getDescriptor() { - return Hudson.getInstance().getDescriptorByType(DescriptorImpl.class); - } - - /** - * Returns the Missed Events playback manager. - * @return GerritMissedEventsPlaybackManager - */ -" -123,0," public void setAllowJavaSerializedObject(boolean allowJavaSerializedObject) { - this.allowJavaSerializedObject = allowJavaSerializedObject; - } - -" -124,0," public int doRead(ByteChunk chunk, Request req) throws IOException { - checkError(); - - if (endChunk) { - return -1; - } - - if(needCRLFParse) { - needCRLFParse = false; - parseCRLF(false); - } - - if (remaining <= 0) { - if (!parseChunkHeader()) { - throwIOException(sm.getString(""chunkedInputFilter.invalidHeader"")); - } - if (endChunk) { - parseEndChunk(); - return -1; - } - } - - int result = 0; - - if (pos >= lastValid) { - if (readBytes() < 0) { - throwIOException(sm.getString(""chunkedInputFilter.eos"")); - } - } - - if (remaining > (lastValid - pos)) { - result = lastValid - pos; - remaining = remaining - result; - chunk.setBytes(buf, pos, result); - pos = lastValid; - } else { - result = remaining; - chunk.setBytes(buf, pos, remaining); - pos = pos + remaining; - remaining = 0; - //we need a CRLF - if ((pos+1) >= lastValid) { - //if we call parseCRLF we overrun the buffer here - //so we defer it to the next call BZ 11117 - needCRLFParse = true; - } else { - parseCRLF(false); //parse the CRLF immediately - } - } - - return result; - } - - - // ---------------------------------------------------- InputFilter Methods - - /** - * Read the content length from the request. - */ - @Override -" -125,0," public byte getValue() { return value; } -" -126,0," public final Permission getRequiredPermission() { - return Jenkins.ADMINISTER; - } - - /** - * Starts the server's project list updater, send command queue and event manager. - * - */ -" -127,0," public Object compile(String expression, Map context) throws OgnlException { - Object tree; - if (enableExpressionCache) { - tree = expressions.get(expression); - if (tree == null) { - tree = Ognl.parseExpression(expression); - expressions.putIfAbsent(expression, tree); - } - } else { - tree = Ognl.parseExpression(expression); - } - - if (!enableEvalExpression && isEvalExpression(tree, context)) { - throw new OgnlException(""Eval expressions has been disabled""); - } - - return tree; - } - - /** - * Copies the properties in the object ""from"" and sets them in the object ""to"" - * using specified type converter, or {@link com.opensymphony.xwork2.conversion.impl.XWorkConverter} if none - * is specified. - * - * @param from the source object - * @param to the target object - * @param context the action context we're running under - * @param exclusions collection of method names to excluded from copying ( can be null) - * @param inclusions collection of method names to included copying (can be null) - * note if exclusions AND inclusions are supplied and not null nothing will get copied. - */ -" -128,0," public SolrInputDocument readDoc(XMLStreamReader parser) throws XMLStreamException { - SolrInputDocument doc = new SolrInputDocument(); - - String attrName = """"; - for (int i = 0; i < parser.getAttributeCount(); i++) { - attrName = parser.getAttributeLocalName(i); - if (""boost"".equals(attrName)) { - doc.setDocumentBoost(Float.parseFloat(parser.getAttributeValue(i))); - } else { - log.warn(""Unknown attribute doc/@"" + attrName); - } - } - - StringBuilder text = new StringBuilder(); - String name = null; - float boost = 1.0f; - boolean isNull = false; - String update = null; - - while (true) { - int event = parser.next(); - switch (event) { - // Add everything to the text - case XMLStreamConstants.SPACE: - case XMLStreamConstants.CDATA: - case XMLStreamConstants.CHARACTERS: - text.append(parser.getText()); - break; - - case XMLStreamConstants.END_ELEMENT: - if (""doc"".equals(parser.getLocalName())) { - return doc; - } else if (""field"".equals(parser.getLocalName())) { - Object v = isNull ? null : text.toString(); - if (update != null) { - Map extendedValue = new HashMap(1); - extendedValue.put(update, v); - v = extendedValue; - } - doc.addField(name, v, boost); - boost = 1.0f; - } - break; - - case XMLStreamConstants.START_ELEMENT: - text.setLength(0); - String localName = parser.getLocalName(); - if (!""field"".equals(localName)) { - log.warn(""unexpected XML tag doc/"" + localName); - throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, - ""unexpected XML tag doc/"" + localName); - } - boost = 1.0f; - update = null; - String attrVal = """"; - for (int i = 0; i < parser.getAttributeCount(); i++) { - attrName = parser.getAttributeLocalName(i); - attrVal = parser.getAttributeValue(i); - if (""name"".equals(attrName)) { - name = attrVal; - } else if (""boost"".equals(attrName)) { - boost = Float.parseFloat(attrVal); - } else if (""null"".equals(attrName)) { - isNull = StrUtils.parseBoolean(attrVal); - } else if (""update"".equals(attrName)) { - update = attrVal; - } else { - log.warn(""Unknown attribute doc/field/@"" + attrName); - } - } - break; - } - } - } -" -129,0," private AsymmetricCipherKeyPair genKeyPair() - { - if (!initialized) - { - initializeDefault(); - } - - // initialize authenticationPaths and treehash instances - byte[][][] currentAuthPaths = new byte[numLayer][][]; - byte[][][] nextAuthPaths = new byte[numLayer - 1][][]; - Treehash[][] currentTreehash = new Treehash[numLayer][]; - Treehash[][] nextTreehash = new Treehash[numLayer - 1][]; - - Vector[] currentStack = new Vector[numLayer]; - Vector[] nextStack = new Vector[numLayer - 1]; - - Vector[][] currentRetain = new Vector[numLayer][]; - Vector[][] nextRetain = new Vector[numLayer - 1][]; - - for (int i = 0; i < numLayer; i++) - { - currentAuthPaths[i] = new byte[heightOfTrees[i]][mdLength]; - currentTreehash[i] = new Treehash[heightOfTrees[i] - K[i]]; - - if (i > 0) - { - nextAuthPaths[i - 1] = new byte[heightOfTrees[i]][mdLength]; - nextTreehash[i - 1] = new Treehash[heightOfTrees[i] - K[i]]; - } - - currentStack[i] = new Vector(); - if (i > 0) - { - nextStack[i - 1] = new Vector(); - } - } - - // initialize roots - byte[][] currentRoots = new byte[numLayer][mdLength]; - byte[][] nextRoots = new byte[numLayer - 1][mdLength]; - // initialize seeds - byte[][] seeds = new byte[numLayer][mdLength]; - // initialize seeds[] by copying starting-seeds of first trees of each - // layer - for (int i = 0; i < numLayer; i++) - { - System.arraycopy(currentSeeds[i], 0, seeds[i], 0, mdLength); - } - - // initialize rootSigs - currentRootSigs = new byte[numLayer - 1][mdLength]; - - // ------------------------- - // ------------------------- - // --- calculation of current authpaths and current rootsigs (AUTHPATHS, - // SIG)------ - // from bottom up to the root - for (int h = numLayer - 1; h >= 0; h--) - { - GMSSRootCalc tree; - - // on lowest layer no lower root is available, so just call - // the method with null as first parameter - if (h == numLayer - 1) - { - tree = this.generateCurrentAuthpathAndRoot(null, currentStack[h], seeds[h], h); - } - else - // otherwise call the method with the former computed root - // value - { - tree = this.generateCurrentAuthpathAndRoot(currentRoots[h + 1], currentStack[h], seeds[h], h); - } - - // set initial values needed for the private key construction - for (int i = 0; i < heightOfTrees[h]; i++) - { - System.arraycopy(tree.getAuthPath()[i], 0, currentAuthPaths[h][i], 0, mdLength); - } - currentRetain[h] = tree.getRetain(); - currentTreehash[h] = tree.getTreehash(); - System.arraycopy(tree.getRoot(), 0, currentRoots[h], 0, mdLength); - } - - // --- calculation of next authpaths and next roots (AUTHPATHS+, ROOTS+) - // ------ - for (int h = numLayer - 2; h >= 0; h--) - { - GMSSRootCalc tree = this.generateNextAuthpathAndRoot(nextStack[h], seeds[h + 1], h + 1); - - // set initial values needed for the private key construction - for (int i = 0; i < heightOfTrees[h + 1]; i++) - { - System.arraycopy(tree.getAuthPath()[i], 0, nextAuthPaths[h][i], 0, mdLength); - } - nextRetain[h] = tree.getRetain(); - nextTreehash[h] = tree.getTreehash(); - System.arraycopy(tree.getRoot(), 0, nextRoots[h], 0, mdLength); - - // create seed for the Merkle tree after next (nextNextSeeds) - // SEEDs++ - System.arraycopy(seeds[h + 1], 0, this.nextNextSeeds[h], 0, mdLength); - } - // ------------ - - // generate JDKGMSSPublicKey - GMSSPublicKeyParameters publicKey = new GMSSPublicKeyParameters(currentRoots[0], gmssPS); - - // generate the JDKGMSSPrivateKey - GMSSPrivateKeyParameters privateKey = new GMSSPrivateKeyParameters(currentSeeds, nextNextSeeds, currentAuthPaths, - nextAuthPaths, currentTreehash, nextTreehash, currentStack, nextStack, currentRetain, nextRetain, nextRoots, currentRootSigs, gmssPS, digestProvider); - - // return the KeyPair - return (new AsymmetricCipherKeyPair(publicKey, privateKey)); - } - - /** - * calculates the authpath for tree in layer h which starts with seed[h] - * additionally computes the rootSignature of underlaying root - * - * @param currentStack stack used for the treehash instance created by this method - * @param lowerRoot stores the root of the lower tree - * @param seed starting seeds - * @param h actual layer - */ -" -130,0," public static void redirectToSavedRequest(ServletRequest request, ServletResponse response, String fallbackUrl) - throws IOException { - String successUrl = null; - boolean contextRelative = true; - SavedRequest savedRequest = WebUtils.getAndClearSavedRequest(request); - if (savedRequest != null && savedRequest.getMethod().equalsIgnoreCase(AccessControlFilter.GET_METHOD)) { - successUrl = savedRequest.getRequestUrl(); - contextRelative = false; - } - - if (successUrl == null) { - successUrl = fallbackUrl; - } - - if (successUrl == null) { - throw new IllegalStateException(""Success URL not available via saved request or via the "" + - ""successUrlFallback method parameter. One of these must be non-null for "" + - ""issueSuccessRedirect() to work.""); - } - - WebUtils.issueRedirect(request, response, successUrl, null, contextRelative); - } - -" -131,0," private void doTestRewrite(String config, String request, String expectedURI) throws Exception { - Tomcat tomcat = getTomcatInstance(); - - // No file system docBase required - Context ctx = tomcat.addContext("""", null); - - RewriteValve rewriteValve = new RewriteValve(); - ctx.getPipeline().addValve(rewriteValve); - - rewriteValve.setConfiguration(config); - - // Note: URLPatterns should be URL encoded - // (http://svn.apache.org/r285186) - Tomcat.addServlet(ctx, ""snoop"", new SnoopServlet()); - ctx.addServletMapping(""/a/%255A"", ""snoop""); - ctx.addServletMapping(""/c/*"", ""snoop""); - Tomcat.addServlet(ctx, ""default"", new DefaultServlet()); - ctx.addServletMapping(""/"", ""default""); - - tomcat.start(); - - ByteChunk res = getUrl(""http://localhost:"" + getPort() + request); - - String body = res.toString(); - RequestDescriptor requestDesc = SnoopResult.parse(body); - String requestURI = requestDesc.getRequestInfo(""REQUEST-URI""); - Assert.assertEquals(expectedURI, requestURI); - } -" -132,0," protected void setLocation(String location) { - this.location = location; - } - -" -133,0," protected String adjustFilterForJoin(String filter) { - if (StringUtils.hasText(filter)) { - filter = filter.replace(""displayName"", ""g.displayName""); - filter = filter.replace(""externalGroup"", ""gm.external_group""); - filter = filter.replace(""groupId"", ""g.id""); - filter = filter.replace(""origin"", ""gm.origin""); - } - return filter; - } - - @Override -" -134,0," private static void disableFeature(DocumentBuilderFactory dbfactory, String feature) { - try { - dbfactory.setFeature(feature, true); - } catch (ParserConfigurationException e) { - // This should catch a failed setFeature feature - log.info(""ParserConfigurationException was thrown. The feature '"" + - feature + ""' is probably not supported by your XML processor.""); - } - } -" -135,0," private static LinkedHashMap> processMap( - LinkedHashMap> requestMap, - ExpressionParser parser) { - Assert.notNull(parser, ""SecurityExpressionHandler returned a null parser object""); - - LinkedHashMap> requestToExpressionAttributesMap = new LinkedHashMap>( - requestMap); - - for (Map.Entry> entry : requestMap - .entrySet()) { - RequestMatcher request = entry.getKey(); - Assert.isTrue(entry.getValue().size() == 1, - ""Expected a single expression attribute for "" + request); - ArrayList attributes = new ArrayList(1); - String expression = entry.getValue().toArray(new ConfigAttribute[1])[0] - .getAttribute(); - logger.debug(""Adding web access control expression '"" + expression + ""', for "" - + request); - - AbstractVariableEvaluationContextPostProcessor postProcessor = createPostProcessor( - request); - try { - attributes.add(new WebExpressionConfigAttribute( - parser.parseExpression(expression), postProcessor)); - } - catch (ParseException e) { - throw new IllegalArgumentException( - ""Failed to parse expression '"" + expression + ""'""); - } - - requestToExpressionAttributesMap.put(request, attributes); - } - - return requestToExpressionAttributesMap; - } - -" -136,0," public T create() { - final ByteArrayOutputStream baos = new ByteArrayOutputStream(512); - ByteArrayInputStream bais = null; - try { - final ObjectOutputStream out = new ObjectOutputStream(baos); - out.writeObject(iPrototype); - - bais = new ByteArrayInputStream(baos.toByteArray()); - final ObjectInputStream in = new ObjectInputStream(bais); - return (T) in.readObject(); - - } catch (final ClassNotFoundException ex) { - throw new FunctorException(ex); - } catch (final IOException ex) { - throw new FunctorException(ex); - } finally { - try { - if (bais != null) { - bais.close(); - } - } catch (final IOException ex) { - // ignore - } - try { - baos.close(); - } catch (final IOException ex) { - // ignore - } - } - } - } - -} -" -137,0," private File getFile(String fn) throws IOException { - File tmp = null; - - String path = System.getProperty(""java.io.tmpdir"") + TMP; - File dir = new File(path); - if (!dir.exists()) { - LOGGER.fine(""Creating directory. Path: "" + dir.getCanonicalPath()); - Files.createDirectories(dir.toPath()); - } - tmp = new File(dir, fn); - LOGGER.fine(""Temp file: "" + tmp.getCanonicalPath()); - - return tmp; - } -" -138,0," private Object readResolve() { - throw new UnsupportedOperationException(); - } - - /* Traverseproc implementation */ - @Override -" -139,0," public Document getMetaData(Idp config, TrustedIdp serviceConfig) throws ProcessingException { - - try { - Crypto crypto = CertsUtils.createCrypto(config.getCertificate()); - - W3CDOMStreamWriter writer = new W3CDOMStreamWriter(); - - writer.writeStartDocument(""UTF-8"", ""1.0""); - - String referenceID = IDGenerator.generateID(""_""); - writer.writeStartElement(""md"", ""EntityDescriptor"", SAML2_METADATA_NS); - writer.writeAttribute(""ID"", referenceID); - - String serviceURL = config.getIdpUrl().toString(); - 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 (""http://docs.oasis-open.org/wsfed/federation/200706"".equals(serviceConfig.getProtocol())) { - writeFederationMetadata(writer, serviceConfig, serviceURL); - } else if (""urn:oasis:names:tc:SAML:2.0:profiles:SSO:browser"".equals(serviceConfig.getProtocol())) { - writeSAMLMetadata(writer, serviceConfig, serviceURL, crypto); - } - - writer.writeEndElement(); // EntityDescriptor - - writer.writeEndDocument(); - - writer.close(); - - if (LOG.isDebugEnabled()) { - String out = DOM2Writer.nodeToString(writer.getDocument()); - LOG.debug(""***************** unsigned ****************""); - LOG.debug(out); - LOG.debug(""***************** unsigned ****************""); - } - - Document result = SignatureUtils.signMetaInfo(crypto, null, config.getCertificatePassword(), - writer.getDocument(), referenceID); - if (result != null) { - return result; - } else { - throw new RuntimeException(""Failed to sign the metadata document: result=null""); - } - } 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()); - } - - } - -" -140,0," protected BlobStore blobStore() { - return blobStore; - } - - /** - * {@inheritDoc} - */ - @Override -" -141,0," public void recycle(boolean socketClosing) { - super.recycle(socketClosing); - - inputBuffer.clear(); - inputBuffer.limit(0); - outputBuffer.clear(); - - } -" -142,0," public void winzipBackSlashWorkaround() throws Exception { - ZipArchiveInputStream in = null; - try { - in = new ZipArchiveInputStream(new FileInputStream(getFile(""test-winzip.zip""))); - ZipArchiveEntry zae = in.getNextZipEntry(); - zae = in.getNextZipEntry(); - zae = in.getNextZipEntry(); - assertEquals(""\u00e4/"", zae.getName()); - } finally { - if (in != null) { - in.close(); - } - } - } - - /** - * @see ""https://issues.apache.org/jira/browse/COMPRESS-189"" - */ - @Test -" -143,0," public long getAvailable() { - - return (this.available); - - } - - - /** - * Set the available date/time for this servlet, in milliseconds since the - * epoch. If this date/time is Long.MAX_VALUE, it is considered to mean - * that unavailability is permanent and any request for this servlet will return - * an SC_NOT_FOUND error. If this date/time is in the future, any request for - * this servlet will return an SC_SERVICE_UNAVAILABLE error. - * - * @param available The new available date/time - */ - @Override -" -144,0," public String toString() - { - return name; - } - } - -} -" -145,0," public T transform(final Class input) { - try { - if (input == null) { - throw new FunctorException( - ""InstantiateTransformer: Input object was not an instanceof Class, it was a null object""); - } - final Constructor con = input.getConstructor(iParamTypes); - return con.newInstance(iArgs); - } catch (final NoSuchMethodException ex) { - throw new FunctorException(""InstantiateTransformer: The constructor must exist and be public ""); - } catch (final InstantiationException ex) { - throw new FunctorException(""InstantiateTransformer: InstantiationException"", ex); - } catch (final IllegalAccessException ex) { - throw new FunctorException(""InstantiateTransformer: Constructor must be public"", ex); - } catch (final InvocationTargetException ex) { - throw new FunctorException(""InstantiateTransformer: Constructor threw an exception"", ex); - } - } - -" -146,0," public String getTreeDigest() - { - return DigestUtil.getXMSSDigestName(treeDigest); - } -" -147,0," public void run() { - try { - LOGGER.info(""Initiating a re-keying of secrets. See ""+getLogFile()); - StreamTaskListener listener = new StreamTaskListener(getLogFile()); - try { - PrintStream log = listener.getLogger(); - log.println(""Started re-keying "" + new Date()); - int count = rewriter.rewriteRecursive(Jenkins.getInstance().getRootDir(), listener); - log.printf(""Completed re-keying %d files on %s\n"",count,new Date()); - new RekeySecretAdminMonitor().done.on(); - LOGGER.info(""Secret re-keying completed""); - } catch (Exception e) { - LOGGER.log(Level.SEVERE, ""Fatal failure in re-keying secrets"",e); - e.printStackTrace(listener.error(""Fatal failure in rewriting secrets"")); - } - } catch (IOException e) { - LOGGER.log(Level.SEVERE, ""Catastrophic failure to rewrite secrets"",e); - } - } - } - - private static final Logger LOGGER = Logger.getLogger(RekeySecretAdminMonitor.class.getName()); - -} -" -148,0," protected BlobPath basePath() { - return basePath; - } -" -149,0," public ServerSocket createServerSocket(int port) throws IOException { - SSLServerSocket sslServerSocket = - (SSLServerSocket) sslServerSocketFactory.createServerSocket(port, 0, bindAddress); - if (getEnabledCipherSuites() != null) { - sslServerSocket.setEnabledCipherSuites(getEnabledCipherSuites()); - } - if (getEnabledProtocols() == null) { - sslServerSocket.setEnabledProtocols(defaultProtocols); - } else { - sslServerSocket.setEnabledProtocols(getEnabledProtocols()); - } - sslServerSocket.setNeedClientAuth(getNeedClientAuth()); - return sslServerSocket; - } - } -} -" -150,0," protected boolean statusDropsConnection(int status) { - return status == 400 /* SC_BAD_REQUEST */ || - status == 408 /* SC_REQUEST_TIMEOUT */ || - status == 411 /* SC_LENGTH_REQUIRED */ || - status == 413 /* SC_REQUEST_ENTITY_TOO_LARGE */ || - status == 414 /* SC_REQUEST_URI_TOO_LARGE */ || - status == 500 /* SC_INTERNAL_SERVER_ERROR */ || - status == 503 /* SC_SERVICE_UNAVAILABLE */ || - status == 501 /* SC_NOT_IMPLEMENTED */; - } - -" -151,0," public void setExpressionParser(ExpressionParser expressionParser) { - this.expressionParser = expressionParser; - } - - /** - * Sets the service to use to expose formatters for field values. - * @param conversionService the conversion service - */ -" -152,0," void setAllowJavaSerializedObject(boolean allowJavaSerializedObject); - - /** - * Gets the header filter strategy - * - * @return the strategy - */ -" -153,0," protected String savedRequestURL(Session session) { - - SavedRequest saved = - (SavedRequest) session.getNote(Constants.FORM_REQUEST_NOTE); - if (saved == null) { - return (null); - } - StringBuilder sb = new StringBuilder(saved.getRequestURI()); - if (saved.getQueryString() != null) { - sb.append('?'); - sb.append(saved.getQueryString()); - } - return (sb.toString()); - - } - - -" -154,0," public static String getAttributeValueEmptyNull(Element e, String attributeName) { - Attr node = e.getAttributeNode(attributeName); - if (node == null) { - return null; - } - return node.getValue(); - } - - /** - * Get the trimmed text content of a node or null if there is no text - */ -" -155,0," private boolean evaluate(String text) { - try { - InputSource inputSource = new InputSource(new StringReader(text)); - Document inputDocument = builder.parse(inputSource); - return ((Boolean) xpath.evaluate(xpathExpression, inputDocument, XPathConstants.BOOLEAN)).booleanValue(); - } catch (Exception e) { - return false; - } - } - - @Override -" -156,0," public void destroy() { - // NO-OP - } - -" -157,0," public void initialize( - AlgorithmParameterSpec params, - SecureRandom random) - throws InvalidAlgorithmParameterException - { - if (!(params instanceof DSAParameterSpec)) - { - throw new InvalidAlgorithmParameterException(""parameter object not a DSAParameterSpec""); - } - DSAParameterSpec dsaParams = (DSAParameterSpec)params; - - param = new DSAKeyGenerationParameters(random, new DSAParameters(dsaParams.getP(), dsaParams.getQ(), dsaParams.getG())); - - engine.init(param); - initialised = true; - } - -" -158,0," public static String nodeMode() { - Builder builder = ImmutableSettings.builder(); - if (Strings.isEmpty(System.getProperty(""es.node.mode"")) && Strings.isEmpty(System.getProperty(""es.node.local""))) { - return ""local""; // default if nothing is specified - } - if (Strings.hasLength(System.getProperty(""es.node.mode""))) { - builder.put(""node.mode"", System.getProperty(""es.node.mode"")); - } - if (Strings.hasLength(System.getProperty(""es.node.local""))) { - builder.put(""node.local"", System.getProperty(""es.node.local"")); - } - if (DiscoveryNode.localNode(builder.build())) { - return ""local""; - } else { - return ""network""; - } - } - - @Override -" -159,0," public AsymmetricCipherKeyPair generateKeyPair() - { - return genKeyPair(); - } -" -160,0," public synchronized void save() throws IOException { - super.save(); - updateTransientActions(); - } - - @Override -" -161,0," public static ASN1Integer getInstance( - ASN1TaggedObject obj, - boolean explicit) - { - ASN1Primitive o = obj.getObject(); - - if (explicit || o instanceof ASN1Integer) - { - return getInstance(o); - } - else - { - return new ASN1Integer(ASN1OctetString.getInstance(obj.getObject()).getOctets()); - } - } - -" -162,0," public void testNoRewrite() throws Exception { - doTestRewrite("""", ""/a/%255A"", ""/a/%255A""); - } - - @Test -" -163,0," public void execute(String key, ActionMapping mapping) { - String name = key.substring(ACTION_PREFIX.length()); - if (allowDynamicMethodCalls) { - int bang = name.indexOf('!'); - if (bang != -1) { - String method = name.substring(bang + 1); - mapping.setMethod(method); - name = name.substring(0, bang); - } - } - mapping.setName(cleanupActionName(name)); - } - }); - - } - }; - } - - /** - * Adds a parameter action. Should only be called during initialization - * - * @param prefix The string prefix to trigger the action - * @param parameterAction The parameter action to execute - * @since 2.1.0 - */ -" -164,0," public Collection getRequiredPermissions(String regionName) { - return Collections.singletonList(new ResourcePermission(ResourcePermission.Resource.DATA, - ResourcePermission.Operation.READ, regionName)); - } - -" -165,0," public T create() { - // needed for post-serialization - if (iConstructor == null) { - findConstructor(); - } - - try { - return iConstructor.newInstance(iArgs); - } catch (final InstantiationException ex) { - throw new FunctorException(""InstantiateFactory: InstantiationException"", ex); - } catch (final IllegalAccessException ex) { - throw new FunctorException(""InstantiateFactory: Constructor must be public"", ex); - } catch (final InvocationTargetException ex) { - throw new FunctorException(""InstantiateFactory: Constructor threw an exception"", ex); - } - } - -" -166,0," public void parseEmbedded( - InputStream stream, ContentHandler handler, Metadata metadata, boolean outputHtml) - throws SAXException, IOException { - if(outputHtml) { - AttributesImpl attributes = new AttributesImpl(); - attributes.addAttribute("""", ""class"", ""class"", ""CDATA"", ""package-entry""); - handler.startElement(XHTML, ""div"", ""div"", attributes); - } - - String name = metadata.get(Metadata.RESOURCE_NAME_KEY); - if (name != null && name.length() > 0 && outputHtml) { - handler.startElement(XHTML, ""h1"", ""h1"", new AttributesImpl()); - char[] chars = name.toCharArray(); - handler.characters(chars, 0, chars.length); - handler.endElement(XHTML, ""h1"", ""h1""); - } - - // Use the delegate parser to parse this entry - try (TemporaryResources tmp = new TemporaryResources()) { - final TikaInputStream newStream = TikaInputStream.get(new CloseShieldInputStream(stream), tmp); - if (stream instanceof TikaInputStream) { - final Object container = ((TikaInputStream) stream).getOpenContainer(); - if (container != null) { - newStream.setOpenContainer(container); - } - } - DELEGATING_PARSER.parse( - newStream, - new EmbeddedContentHandler(new BodyContentHandler(handler)), - metadata, context); - } catch (EncryptedDocumentException ede) { - // TODO: can we log a warning that we lack the password? - // For now, just skip the content - } catch (CorruptedFileException e) { - throw new IOExceptionWithCause(e); - } catch (TikaException e) { - // TODO: can we log a warning somehow? - // Could not parse the entry, just skip the content - } - - if(outputHtml) { - handler.endElement(XHTML, ""div"", ""div""); - } - } - -" -167,0," private void checkParams() - { - if (vi == null) - { - throw new IllegalArgumentException(""no layers defined.""); - } - if (vi.length > 1) - { - for (int i = 0; i < vi.length - 1; i++) - { - if (vi[i] >= vi[i + 1]) - { - throw new IllegalArgumentException( - ""v[i] has to be smaller than v[i+1]""); - } - } - } - else - { - throw new IllegalArgumentException( - ""Rainbow needs at least 1 layer, such that v1 < v2.""); - } - } - - /** - * Getter for the number of layers - * - * @return the number of layers - */ -" -168,0," public void markPaused() { - paused = true; - } - } - - // ---------------------------------------------------- Wrapper Inner Class - - - protected static class MappedWrapper extends MapElement { - - public final boolean jspWildCard; - public final boolean resourceOnly; - - public MappedWrapper(String name, Wrapper wrapper, boolean jspWildCard, - boolean resourceOnly) { - super(name, wrapper); - this.jspWildCard = jspWildCard; - this.resourceOnly = resourceOnly; - } - } -} -" -169,0," public String getUsername() { - return username; - } - -" -170,0," public boolean isMapHeaders() { - return mapHeaders; - } - - /** - * If this option is enabled, then during binding from Spark to Camel Message then the headers will be mapped as well - * (eg added as header to the Camel Message as well). You can turn off this option to disable this. - * The headers can still be accessed from the org.apache.camel.component.sparkrest.SparkMessage message with the - * method getRequest() that returns the Spark HTTP request instance. - */ -" -171,0," public int[] getVi() - { - return this.vi; - } -" -172,0," public void setUp() throws Exception { - int randomInt = new SecureRandom().nextInt(); - - String adminAccessToken = testClient.getOAuthAccessToken(""admin"", ""adminsecret"", ""client_credentials"", ""clients.read clients.write clients.secret""); - - String scimClientId = ""scim"" + randomInt; - testClient.createScimClient(adminAccessToken, scimClientId); - - String scimAccessToken = testClient.getOAuthAccessToken(scimClientId, ""scimsecret"", ""client_credentials"", ""scim.read scim.write password.write""); - - userEmail = ""user"" + randomInt + ""@example.com""; - testClient.createUser(scimAccessToken, userEmail, userEmail, PASSWORD, true); - } - - @Test -" -173,0," public final void invoke(Request request, Response response) - throws IOException, ServletException { - - // Select the Context to be used for this Request - Context context = request.getContext(); - if (context == null) { - response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, - sm.getString(""standardHost.noContext"")); - return; - } - - if (request.isAsyncSupported()) { - request.setAsyncSupported(context.getPipeline().isAsyncSupported()); - } - - boolean asyncAtStart = request.isAsync(); - boolean asyncDispatching = request.isAsyncDispatching(); - - try { - context.bind(Globals.IS_SECURITY_ENABLED, MY_CLASSLOADER); - - if (!asyncAtStart && !context.fireRequestInitEvent(request.getRequest())) { - // Don't fire listeners during async processing (the listener - // fired for the request that called startAsync()). - // If a request init listener throws an exception, the request - // is aborted. - return; - } - - // Ask this Context to process this request. Requests that are in - // async mode and are not being dispatched to this resource must be - // in error and have been routed here to check for application - // defined error pages. - try { - if (!asyncAtStart || asyncDispatching) { - context.getPipeline().getFirst().invoke(request, response); - } else { - // Make sure this request/response is here because an error - // report is required. - if (!response.isErrorReportRequired()) { - throw new IllegalStateException(sm.getString(""standardHost.asyncStateError"")); - } - } - } catch (Throwable t) { - ExceptionUtils.handleThrowable(t); - container.getLogger().error(""Exception Processing "" + request.getRequestURI(), t); - // If a new error occurred while trying to report a previous - // error allow the original error to be reported. - if (!response.isErrorReportRequired()) { - request.setAttribute(RequestDispatcher.ERROR_EXCEPTION, t); - throwable(request, response, t); - } - } - - // Now that the request/response pair is back under container - // control lift the suspension so that the error handling can - // complete and/or the container can flush any remaining data - response.setSuspended(false); - - Throwable t = (Throwable) request.getAttribute(RequestDispatcher.ERROR_EXCEPTION); - - // Protect against NPEs if the context was destroyed during a - // long running request. - if (!context.getState().isAvailable()) { - return; - } - - // Look for (and render if found) an application level error page - if (response.isErrorReportRequired()) { - if (t != null) { - throwable(request, response, t); - } else { - status(request, response); - } - } - - if (!request.isAsync() && !asyncAtStart) { - context.fireRequestDestroyEvent(request.getRequest()); - } - } finally { - // Access a session (if present) to update last accessed time, based - // on a strict interpretation of the specification - if (ACCESS_SESSION) { - request.getSession(false); - } - - context.unbind(Globals.IS_SECURITY_ENABLED, MY_CLASSLOADER); - } - } - - - // -------------------------------------------------------- Private Methods - - /** - * Handle the HTTP status code (and corresponding message) generated - * while processing the specified Request to produce the specified - * Response. Any exceptions that occur during generation of the error - * report are logged and swallowed. - * - * @param request The request being processed - * @param response The response being generated - */ -" -174,0," private T run(PrivilegedExceptionAction action) throws Exception { - return System.getSecurityManager() != null ? AccessController.doPrivileged( action ) : action.run(); - } -" -175,0," public void setUp() throws Exception { - sshKey = SshdServerMock.generateKeyPair(); - System.setProperty(PluginImpl.TEST_SSH_KEYFILE_LOCATION_PROPERTY, sshKey.getPrivateKey().getAbsolutePath()); - server = new SshdServerMock(); - sshd = SshdServerMock.startServer(server); - server.returnCommandFor(""gerrit ls-projects"", SshdServerMock.EofCommandMock.class); - server.returnCommandFor(GERRIT_STREAM_EVENTS, SshdServerMock.CommandMock.class); - server.returnCommandFor(""gerrit review.*"", SshdServerMock.EofCommandMock.class); - server.returnCommandFor(""gerrit version"", SshdServerMock.EofCommandMock.class); - } - - /** - * Runs after test method. - * - * @throws Exception throw if so. - */ - @After -" -176,0," public boolean getSource_location() { - return m_source_location; - } - -" -177,0," public void setCoyoteRequest(org.apache.coyote.Request coyoteRequest) { - this.coyoteRequest = coyoteRequest; - inputBuffer.setRequest(coyoteRequest); - } - - /** - * Get the Coyote request. - */ -" -178,0," public ExpressionInterceptUrlRegistry access(String attribute) { - if (not) { - attribute = ""!"" + attribute; - } - interceptUrl(requestMatchers, SecurityConfig.createList(attribute)); - return ExpressionUrlAuthorizationConfigurer.this.REGISTRY; - } - } -} -" -179,0," private @CheckForNull File getDirectChild(File parentFile, String childPath){ - File current = new File(parentFile, childPath); - while (current != null && !parentFile.equals(current.getParentFile())) { - current = current.getParentFile(); - } - return current; - } - } - - private static final SoloFilePathFilter UNRESTRICTED = SoloFilePathFilter.wrap(FilePathFilter.UNRESTRICTED); -} -" -180,0," public static boolean containsExpression(String expr) { - return expr.contains(""%{"") && expr.contains(""}""); - } - -" -181,0," public void derIntegerTest() - throws Exception - { - try - { - new ASN1Integer(new byte[] { 0, 0, 0, 1}); - } - catch (IllegalArgumentException e) - { - isTrue(""wrong exc"", ""malformed integer"".equals(e.getMessage())); - } - - try - { - new ASN1Integer(new byte[] {(byte)0xff, (byte)0x80, 0, 1}); - } - catch (IllegalArgumentException e) - { - isTrue(""wrong exc"", ""malformed integer"".equals(e.getMessage())); - } - - try - { - new ASN1Enumerated(new byte[] { 0, 0, 0, 1}); - } - catch (IllegalArgumentException e) - { - isTrue(""wrong exc"", ""malformed enumerated"".equals(e.getMessage())); - } - - try - { - new ASN1Enumerated(new byte[] {(byte)0xff, (byte)0x80, 0, 1}); - } - catch (IllegalArgumentException e) - { - isTrue(""wrong exc"", ""malformed enumerated"".equals(e.getMessage())); - } - } - -" -182,0," public void cleanUp() { - Set names = files.keySet(); - for (String name : names) { - List items = files.get(name); - for (FileItem item : items) { - if (LOG.isDebugEnabled()) { - String msg = LocalizedTextUtil.findText(this.getClass(), ""struts.messages.removing.file"", - Locale.ENGLISH, ""no.message.found"", new Object[]{name, item}); - LOG.debug(msg); - } - if (!item.isInMemory()) { - item.delete(); - } - } - } - } - -" -183,0," protected JDBCTableReader getTableReader(Connection connection, String tableName, EmbeddedDocumentUtil embeddedDocumentUtil) { - return new SQLite3TableReader(connection, tableName, embeddedDocumentUtil); - } -" -184,0," public Character decodeCharacter( PushbackString input ) { - input.mark(); - Character first = input.next(); - if ( first == null ) { - input.reset(); - return null; - } - - // if this is not an encoded character, return null - if (first != '%' ) { - input.reset(); - return null; - } - - // Search for exactly 2 hex digits following - StringBuilder sb = new StringBuilder(); - for ( int i=0; i<2; i++ ) { - Character c = input.nextHex(); - if ( c != null ) sb.append( c ); - } - if ( sb.length() == 2 ) { - try { - // parse the hex digit and create a character - int i = Integer.parseInt(sb.toString(), 16); - if (Character.isValidCodePoint(i)) { - return (char) i; - } - } catch( NumberFormatException ignored ) { } - } - input.reset(); - return null; - } - -" -185,0," public String getPathname() { - - return pathname; - - } - - - /** - * Set the pathname of our XML file containing user definitions. If a - * relative pathname is specified, it is resolved against ""catalina.base"". - * - * @param pathname The new pathname - */ -" -186,0," public boolean isSecureProcessing() - { - return m_isSecureProcessing; - } -" -187,0," public void write(OutputStream outputStream) - throws IOException, WebApplicationException { - Writer writer = new OutputStreamWriter(outputStream, UTF_8); - ContentHandler content; - - try { - SAXTransformerFactory factory = (SAXTransformerFactory) SAXTransformerFactory.newInstance(); - TransformerHandler handler = factory.newTransformerHandler(); - handler.getTransformer().setOutputProperty(OutputKeys.METHOD, format); - handler.getTransformer().setOutputProperty(OutputKeys.INDENT, ""yes""); - handler.getTransformer().setOutputProperty(OutputKeys.ENCODING, UTF_8.name()); - handler.setResult(new StreamResult(writer)); - content = new ExpandedTitleContentHandler(handler); - } catch (TransformerConfigurationException e) { - throw new WebApplicationException(e); - } - - parse(parser, LOG, info.getPath(), is, content, metadata, context); - } - }; - } -} -" -188,0," private boolean isSameAs( - byte[] a, - byte[] b) - { - if (a.length != b.length) - { - return false; - } - - for (int i = 0; i != a.length; i++) - { - if (a[i] != b[i]) - { - return false; - } - } - - return true; - } - -" -189,0," private void testModified() - throws Exception - { - KeyFactory kFact = KeyFactory.getInstance(""DSA"", ""BC""); - PublicKey pubKey = kFact.generatePublic(PUBLIC_KEY); - Signature sig = Signature.getInstance(""DSA"", ""BC""); - - for (int i = 0; i != MODIFIED_SIGNATURES.length; i++) - { - sig.initVerify(pubKey); - - sig.update(Strings.toByteArray(""Hello"")); - - boolean failed; - - try - { - failed = !sig.verify(Hex.decode(MODIFIED_SIGNATURES[i])); - } - catch (SignatureException e) - { - failed = true; - } - - isTrue(""sig verified when shouldn't"", failed); - } - } - -" -190,0," public LockoutPolicyRetriever getLockoutPolicyRetriever() { - return lockoutPolicyRetriever; - } -" -191,0," public void close() throws IOException { - if (!closed) { - synchronized (this) { - if (!closed) { - closed = true; - socket.close(); - } - } - } - } - -" -192,0," protected abstract void recycleInternal(); -" -193,0," public static JWTDecoder getInstance() { - if (instance == null) { - instance = new JWTDecoder(); - } - - return instance; - } - - /** - * Decode the JWT using one of they provided verifiers. One more verifiers may be provided, the first verifier found - * supporting the algorithm reported by the JWT header will be utilized. - *

- * A JWT that is expired or not yet valid will not be decoded, instead a {@link JWTExpiredException} or {@link - * JWTUnavailableForProcessingException} exception will be thrown respectively. - * - * @param encodedJWT The encoded JWT in string format. - * @param verifiers A map of verifiers. - * @return a decoded JWT. - */ -" -194,0," public boolean check(String path, Resource resource) - { - int slash = path.lastIndexOf('/'); - if (slash<0 || resource.exists()) - return false; - String suffix=path.substring(slash); - return resource.getAlias().toString().endsWith(suffix); - } - } -} -" -195,0," public void setMaxParameterCount(int maxParameterCount) { - this.maxParameterCount = maxParameterCount; - } - - - /** - * Return the maximum size of a POST which will be automatically - * parsed by the container. - */ -" -196,0," protected boolean requiresAuthentication(final HttpServletRequest request, final HttpServletResponse response) { - boolean result = request.getRequestURI().contains(getFilterProcessesUrl()); - result |= isTokenExpired(); - if (logger.isDebugEnabled()) { - logger.debug(""requiresAuthentication = "" + result); - } - return result; - } - -" -197,0," public JettyContentExchange createContentExchange() { - return new JettyContentExchange9(); - } -" -198,0," protected void populateResponse(Exchange exchange, JettyContentExchange httpExchange, - Message in, HeaderFilterStrategy strategy, int responseCode) throws IOException { - Message answer = exchange.getOut(); - - answer.setHeader(Exchange.HTTP_RESPONSE_CODE, responseCode); - - // must use response fields to get the http headers as - // httpExchange.getHeaders() does not work well with multi valued headers - Map> headers = httpExchange.getResponseHeaders(); - for (Map.Entry> ent : headers.entrySet()) { - String name = ent.getKey(); - Collection values = ent.getValue(); - for (String value : values) { - if (name.toLowerCase().equals(""content-type"")) { - name = Exchange.CONTENT_TYPE; - exchange.setProperty(Exchange.CHARSET_NAME, IOHelper.getCharsetNameFromContentType(value)); - } - if (strategy != null && !strategy.applyFilterToExternalHeaders(name, value, exchange)) { - HttpHelper.appendHeader(answer.getHeaders(), name, value); - } - } - } - - // preserve headers from in by copying any non existing headers - // to avoid overriding existing headers with old values - // We also need to apply the httpProtocolHeaderFilterStrategy to filter the http protocol header - MessageHelper.copyHeaders(exchange.getIn(), answer, httpProtocolHeaderFilterStrategy, false); - - // extract body after headers has been set as we want to ensure content-type from Jetty HttpExchange - // has been populated first - answer.setBody(extractResponseBody(exchange, httpExchange)); - } - -" -199,0," protected boolean isAuthorizedToSwitchToIdentityZone(String identityZoneId) { - Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); - boolean hasScope = OAuth2ExpressionUtils.hasAnyScope(authentication, getZoneSwitchingScopes(identityZoneId)); - boolean isUaa = IdentityZoneHolder.isUaa(); - boolean isTokenAuth = (authentication instanceof OAuth2Authentication); - return isTokenAuth && isUaa && hasScope; - } - -" -200,0," protected static void copyBytes(byte[] b, int dest, int src, int len) { - for (int pos = 0; pos < len; pos++) { - b[pos + dest] = b[pos + src]; - } - } - - -" -201,0," public String getSessionId() - throws IOException { - // Look up the current SSLSession - SSLSession session = ssl.getSession(); - if (session == null) - return null; - // Expose ssl_session (getId) - byte [] ssl_session = session.getId(); - if ( ssl_session == null) - return null; - StringBuffer buf=new StringBuffer(""""); - for(int x=0; x2) digit=digit.substring(digit.length()-2); - buf.append(digit); - } - return buf.toString(); - } - - -" -202,0," private void login(String clientId) throws Exception { - getMockMvc().perform(post(""/oauth/token"") - .accept(MediaType.APPLICATION_JSON_VALUE) - .header(""Authorization"", ""Basic "" + new String(Base64.encode((clientId + "":"" + SECRET).getBytes()))) - .param(""grant_type"", ""client_credentials"") - ) - .andExpect(status().isOk()) - .andReturn().getResponse().getContentAsString(); - } - - @Test -" -203,0," public abstract JettyContentExchange createContentExchange(); - -" -204,0," public void testParameterNameAware() { - ParametersInterceptor pi = createParametersInterceptor(); - final Map actual = injectValueStackFactory(pi); - ValueStack stack = createStubValueStack(actual); - final Map expected = new HashMap() { - { - put(""fooKey"", ""fooValue""); - put(""barKey"", ""barValue""); - } - }; - Object a = new ParameterNameAware() { - public boolean acceptableParameterName(String parameterName) { - return expected.containsKey(parameterName); - } - }; - Map parameters = new HashMap() { - { - put(""fooKey"", ""fooValue""); - put(""barKey"", ""barValue""); - put(""error"", ""error""); - } - }; - pi.setParameters(a, stack, parameters); - assertEquals(expected, actual); - } - -" -205,0," protected CloseButtonBehavior newCloseButtonBehavior() - { - return new CloseButtonBehavior(); - } -" -206,0," public void repositoryVerificationTimeoutTest() throws Exception { - Client client = client(); - - Settings settings = ImmutableSettings.settingsBuilder() - .put(""location"", randomRepoPath()) - .put(""random_control_io_exception_rate"", 1.0).build(); - logger.info(""--> creating repository that cannot write any files - should fail""); - assertThrows(client.admin().cluster().preparePutRepository(""test-repo-1"") - .setType(MockRepositoryModule.class.getCanonicalName()).setSettings(settings), - RepositoryVerificationException.class); - - logger.info(""--> creating repository that cannot write any files, but suppress verification - should be acked""); - assertAcked(client.admin().cluster().preparePutRepository(""test-repo-1"") - .setType(MockRepositoryModule.class.getCanonicalName()).setSettings(settings).setVerify(false)); - - logger.info(""--> verifying repository""); - assertThrows(client.admin().cluster().prepareVerifyRepository(""test-repo-1""), RepositoryVerificationException.class); - - File location = randomRepoPath(); - - logger.info(""--> creating repository""); - try { - client.admin().cluster().preparePutRepository(""test-repo-1"") - .setType(MockRepositoryModule.class.getCanonicalName()) - .setSettings(ImmutableSettings.settingsBuilder() - .put(""location"", location) - .put(""localize_location"", true) - ).get(); - fail(""RepositoryVerificationException wasn't generated""); - } catch (RepositoryVerificationException ex) { - assertThat(ex.getMessage(), containsString(""is not shared"")); - } - } - -" -207,0," private static void log( String s ) { - if (log.isDebugEnabled()) - log.debug(""URLDecoder: "" + s ); - } - -" -208,0," private boolean evaluate(String text) { - try { - InputSource inputSource = new InputSource(new StringReader(text)); - Document inputDocument = builder.parse(inputSource); - return ((Boolean)xpath.evaluate(xpathExpression, inputDocument, XPathConstants.BOOLEAN)).booleanValue(); - } catch (Exception e) { - return false; - } - } - - @Override -" -209,0," public void basicWorkFlowTest() throws Exception { - Client client = client(); - - logger.info(""--> creating repository""); - assertAcked(client.admin().cluster().preparePutRepository(""test-repo"") - .setType(""fs"").setSettings(ImmutableSettings.settingsBuilder() - .put(""location"", randomRepoPath()) - .put(""compress"", randomBoolean()) - .put(""chunk_size"", randomIntBetween(100, 1000)))); - - createIndex(""test-idx-1"", ""test-idx-2"", ""test-idx-3""); - ensureGreen(); - - logger.info(""--> indexing some data""); - for (int i = 0; i < 100; i++) { - index(""test-idx-1"", ""doc"", Integer.toString(i), ""foo"", ""bar"" + i); - index(""test-idx-2"", ""doc"", Integer.toString(i), ""foo"", ""baz"" + i); - index(""test-idx-3"", ""doc"", Integer.toString(i), ""foo"", ""baz"" + i); - } - refresh(); - assertHitCount(client.prepareCount(""test-idx-1"").get(), 100L); - assertHitCount(client.prepareCount(""test-idx-2"").get(), 100L); - assertHitCount(client.prepareCount(""test-idx-3"").get(), 100L); - - ListenableActionFuture flushResponseFuture = null; - if (randomBoolean()) { - ArrayList indicesToFlush = newArrayList(); - for (int i = 1; i < 4; i++) { - if (randomBoolean()) { - indicesToFlush.add(""test-idx-"" + i); - } - } - if (!indicesToFlush.isEmpty()) { - String[] indices = indicesToFlush.toArray(new String[indicesToFlush.size()]); - logger.info(""--> starting asynchronous flush for indices {}"", Arrays.toString(indices)); - flushResponseFuture = client.admin().indices().prepareFlush(indices).execute(); - } - } - logger.info(""--> snapshot""); - CreateSnapshotResponse createSnapshotResponse = client.admin().cluster().prepareCreateSnapshot(""test-repo"", ""test-snap"").setWaitForCompletion(true).setIndices(""test-idx-*"", ""-test-idx-3"").get(); - assertThat(createSnapshotResponse.getSnapshotInfo().successfulShards(), greaterThan(0)); - assertThat(createSnapshotResponse.getSnapshotInfo().successfulShards(), equalTo(createSnapshotResponse.getSnapshotInfo().totalShards())); - - assertThat(client.admin().cluster().prepareGetSnapshots(""test-repo"").setSnapshots(""test-snap"").get().getSnapshots().get(0).state(), equalTo(SnapshotState.SUCCESS)); - - logger.info(""--> delete some data""); - for (int i = 0; i < 50; i++) { - client.prepareDelete(""test-idx-1"", ""doc"", Integer.toString(i)).get(); - } - for (int i = 50; i < 100; i++) { - client.prepareDelete(""test-idx-2"", ""doc"", Integer.toString(i)).get(); - } - for (int i = 0; i < 100; i += 2) { - client.prepareDelete(""test-idx-3"", ""doc"", Integer.toString(i)).get(); - } - refresh(); - assertHitCount(client.prepareCount(""test-idx-1"").get(), 50L); - assertHitCount(client.prepareCount(""test-idx-2"").get(), 50L); - assertHitCount(client.prepareCount(""test-idx-3"").get(), 50L); - - logger.info(""--> close indices""); - client.admin().indices().prepareClose(""test-idx-1"", ""test-idx-2"").get(); - - logger.info(""--> restore all indices from the snapshot""); - RestoreSnapshotResponse restoreSnapshotResponse = client.admin().cluster().prepareRestoreSnapshot(""test-repo"", ""test-snap"").setWaitForCompletion(true).execute().actionGet(); - assertThat(restoreSnapshotResponse.getRestoreInfo().totalShards(), greaterThan(0)); - - ensureGreen(); - for (int i=0; i<5; i++) { - assertHitCount(client.prepareCount(""test-idx-1"").get(), 100L); - assertHitCount(client.prepareCount(""test-idx-2"").get(), 100L); - assertHitCount(client.prepareCount(""test-idx-3"").get(), 50L); - } - - // Test restore after index deletion - logger.info(""--> delete indices""); - cluster().wipeIndices(""test-idx-1"", ""test-idx-2""); - logger.info(""--> restore one index after deletion""); - restoreSnapshotResponse = client.admin().cluster().prepareRestoreSnapshot(""test-repo"", ""test-snap"").setWaitForCompletion(true).setIndices(""test-idx-*"", ""-test-idx-2"").execute().actionGet(); - assertThat(restoreSnapshotResponse.getRestoreInfo().totalShards(), greaterThan(0)); - - ensureGreen(); - for (int i=0; i<5; i++) { - assertHitCount(client.prepareCount(""test-idx-1"").get(), 100L); - } - ClusterState clusterState = client.admin().cluster().prepareState().get().getState(); - assertThat(clusterState.getMetaData().hasIndex(""test-idx-1""), equalTo(true)); - assertThat(clusterState.getMetaData().hasIndex(""test-idx-2""), equalTo(false)); - - if (flushResponseFuture != null) { - // Finish flush - flushResponseFuture.actionGet(); - } - } - - - @Test -" -210,0," public ReturnValueDescriptor asDescriptor(boolean defaultGroupSequenceRedefined, List> defaultGroupSequence) { - return new ReturnValueDescriptorImpl( - getType(), - asDescriptors( getConstraints() ), - isCascading(), - defaultGroupSequenceRedefined, - defaultGroupSequence, - groupConversionHelper.asDescriptors() - ); - } -" -211,0," static final PyObject function___new__(PyNewWrapper new_, boolean init, PyType subtype, - PyObject[] args, String[] keywords) { - ArgParser ap = new ArgParser(""function"", args, keywords, - new String[] {""code"", ""globals"", ""name"", ""argdefs"", - ""closure""}, 0); - PyObject code = ap.getPyObject(0); - PyObject globals = ap.getPyObject(1); - PyObject name = ap.getPyObject(2, Py.None); - PyObject defaults = ap.getPyObject(3, Py.None); - PyObject closure = ap.getPyObject(4, Py.None); - - if (!(code instanceof PyBaseCode)) { - throw Py.TypeError(""function() argument 1 must be code, not "" + - code.getType().fastGetName()); - } - if (name != Py.None && !Py.isInstance(name, PyString.TYPE)) { - throw Py.TypeError(""arg 3 (name) must be None or string""); - } - if (defaults != Py.None && !(defaults instanceof PyTuple)) { - throw Py.TypeError(""arg 4 (defaults) must be None or tuple""); - } - - PyBaseCode tcode = (PyBaseCode)code; - int nfree = tcode.co_freevars == null ? 0 : tcode.co_freevars.length; - if (!(closure instanceof PyTuple)) { - if (nfree > 0 && closure == Py.None) { - throw Py.TypeError(""arg 5 (closure) must be tuple""); - } else if (closure != Py.None) { - throw Py.TypeError(""arg 5 (closure) must be None or tuple""); - } - } - - int nclosure = closure == Py.None ? 0 : closure.__len__(); - if (nfree != nclosure) { - throw Py.ValueError(String.format(""%s requires closure of length %d, not %d"", - tcode.co_name, nfree, nclosure)); - } - if (nclosure > 0) { - for (PyObject o : ((PyTuple)closure).asIterable()) { - if (!(o instanceof PyCell)) { - throw Py.TypeError(String.format(""arg 5 (closure) expected cell, found %s"", - o.getType().fastGetName())); - } - } - } - - PyFunction function = new PyFunction(globals, - defaults == Py.None - ? null : ((PyTuple)defaults).getArray(), - tcode, null, - closure == Py.None - ? null : ((PyTuple)closure).getArray()); - if (name != Py.None) { - function.__name__ = name.toString(); - } - return function; - } - - @ExposedSet(name = ""__name__"") -" -212,0," private static byte[] toUtf8Bytes(String str) - { - try - { - return str.getBytes(""UTF-8""); - } - catch(UnsupportedEncodingException e) - { - throw new IllegalStateException(""The Java spec requires UTF-8 support."", e); - } - } - - /** - * Append the two upper case hex characters for a byte. - * @param sb The string buffer to append to. - * @param b The byte to hexify - * @return sb with the hex characters appended. - */ - // rfc3986 2.1: For consistency, URI producers - // should use uppercase hexadecimal digits for all percent- - // encodings. -" -213,0," void getElUnsupported(String expression); - -" -214,0," public String toString() { - return xpathExpression; - } -" -215,0," public Descriptor getDescriptor() { - throw new UnsupportedOperationException(); - } - } -} -" -216,1," public void getAllPropertiesRequiresAdmin() { - j.jenkins.setAuthorizationStrategy(new MockAuthorizationStrategy() - .grant(Jenkins.ADMINISTER).everywhere().to(""admin"") - .grant(Jenkins.READ).everywhere().toEveryone()); - j.jenkins.setSecurityRealm(j.createDummySecurityRealm()); - - User admin = User.get(""admin""); - User alice = User.get(""alice""); - User bob = User.get(""bob""); - - // Admin can access user properties for all users - try (ACLContext as = ACL.as(admin)) { - assertThat(alice.getAllProperties(), not(empty())); - assertThat(bob.getAllProperties(), not(empty())); - assertThat(admin.getAllProperties(), not(empty())); - } - - // Non admins can only view their own - try (ACLContext as = ACL.as(alice)) { - assertThat(alice.getAllProperties(), not(empty())); - assertThat(bob.getAllProperties(), empty()); - assertThat(admin.getAllProperties(), empty()); - } - } - -" -217,1," protected

P postProcess(P object) { - return (P) this.objectPostProcessor.postProcess(object); - } - - /** - * Executes the build using the {@link SecurityConfigurer}'s that have been applied - * using the following steps: - * - *

    - *
  • Invokes {@link #beforeInit()} for any subclass to hook into
  • - *
  • Invokes {@link SecurityConfigurer#init(SecurityBuilder)} for any - * {@link SecurityConfigurer} that was applied to this builder.
  • - *
  • Invokes {@link #beforeConfigure()} for any subclass to hook into
  • - *
  • Invokes {@link #performBuild()} which actually builds the Object
  • - *
- */ - @Override -" -218,1," public SAXSource toSAXSourceFromStream(StreamSource source, Exchange exchange) throws SAXException { - InputSource inputSource; - if (source.getReader() != null) { - inputSource = new InputSource(source.getReader()); - } else { - inputSource = new InputSource(source.getInputStream()); - } - inputSource.setSystemId(source.getSystemId()); - inputSource.setPublicId(source.getPublicId()); - XMLReader xmlReader = null; - SAXParserFactory sfactory = null; - //Need to setup XMLReader security feature by default - try { - // use the SAXPaserFactory which is set from exchange - if (exchange != null) { - sfactory = exchange.getProperty(Exchange.SAXPARSER_FACTORY, SAXParserFactory.class); - } - if (sfactory == null) { - sfactory = SAXParserFactory.newInstance(); - try { - sfactory.setFeature(javax.xml.XMLConstants.FEATURE_SECURE_PROCESSING, true); - } catch (Exception e) { - LOG.warn(""SAXParser doesn't support the feature {} with value {}, due to {}."", new Object[]{javax.xml.XMLConstants.FEATURE_SECURE_PROCESSING, ""true"", e}); - } - } - sfactory.setNamespaceAware(true); - SAXParser parser = sfactory.newSAXParser(); - xmlReader = parser.getXMLReader(); - } catch (Exception ex) { - LOG.warn(""Cannot create the SAXParser XMLReader, due to {}"", ex); - } - return new SAXSource(xmlReader, inputSource); - } - - /** - * @deprecated will be removed in Camel 3.0. Use the method which has 2 parameters. - */ - @Deprecated -" -219,1," public String getDisplayName() { - return Messages.CommandLauncher_displayName(); - } - } -} -" -220,1," public SSOValidatorResponse validateSamlResponse( - org.opensaml.saml.saml2.core.Response samlResponse, - boolean postBinding - ) throws WSSecurityException { - // Check the Issuer - validateIssuer(samlResponse.getIssuer()); - - // The Response must contain at least one Assertion. - if (samlResponse.getAssertions() == null || samlResponse.getAssertions().isEmpty()) { - LOG.fine(""The Response must contain at least one Assertion""); - throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, ""invalidSAMLsecurity""); - } - - // The Response must contain a Destination that matches the assertionConsumerURL if it is - // signed - String destination = samlResponse.getDestination(); - if (samlResponse.isSigned() - && (destination == null || !destination.equals(assertionConsumerURL))) { - LOG.fine(""The Response must contain a destination that matches the assertion consumer URL""); - throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, ""invalidSAMLsecurity""); - } - - // Validate Assertions - boolean foundValidSubject = false; - Date sessionNotOnOrAfter = null; - for (org.opensaml.saml.saml2.core.Assertion assertion : samlResponse.getAssertions()) { - // Check the Issuer - if (assertion.getIssuer() == null) { - LOG.fine(""Assertion Issuer must not be null""); - throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, ""invalidSAMLsecurity""); - } - validateIssuer(assertion.getIssuer()); - - if (enforceAssertionsSigned && postBinding && assertion.getSignature() == null) { - LOG.fine(""If the HTTP Post binding is used to deliver the Response, "" - + ""the enclosed assertions must be signed""); - throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, ""invalidSAMLsecurity""); - } - - // Check for AuthnStatements and validate the Subject accordingly - if (assertion.getAuthnStatements() != null - && !assertion.getAuthnStatements().isEmpty()) { - org.opensaml.saml.saml2.core.Subject subject = assertion.getSubject(); - if (validateAuthenticationSubject(subject, assertion.getID(), postBinding)) { - validateAudienceRestrictionCondition(assertion.getConditions()); - foundValidSubject = true; - // Store Session NotOnOrAfter - for (AuthnStatement authnStatment : assertion.getAuthnStatements()) { - if (authnStatment.getSessionNotOnOrAfter() != null) { - sessionNotOnOrAfter = authnStatment.getSessionNotOnOrAfter().toDate(); - } - } - } - } - - } - - if (!foundValidSubject) { - LOG.fine(""The Response did not contain any Authentication Statement that matched "" - + ""the Subject Confirmation criteria""); - throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, ""invalidSAMLsecurity""); - } - - SSOValidatorResponse validatorResponse = new SSOValidatorResponse(); - validatorResponse.setResponseId(samlResponse.getID()); - validatorResponse.setSessionNotOnOrAfter(sessionNotOnOrAfter); - if (samlResponse.getIssueInstant() != null) { - validatorResponse.setCreated(samlResponse.getIssueInstant().toDate()); - } - - // the assumption for now is that SAMLResponse will contain only a single assertion - Element assertionElement = samlResponse.getAssertions().get(0).getDOM(); - Element clonedAssertionElement = (Element)assertionElement.cloneNode(true); - validatorResponse.setAssertionElement(clonedAssertionElement); - validatorResponse.setAssertion(DOM2Writer.nodeToString(clonedAssertionElement)); - - return validatorResponse; - } - - /** - * Validate the Issuer (if it exists) - */ -" -221,1," private JWT decode(String encodedJWT, Header header, String[] parts, Verifier verifier) { - int index = encodedJWT.lastIndexOf("".""); - // The message comprises the first two segments of the entire JWT, the signature is the last segment. - byte[] message = encodedJWT.substring(0, index).getBytes(StandardCharsets.UTF_8); - - // If a signature is provided and verifier must be provided. - if (parts.length == 3 && verifier == null) { - throw new MissingVerifierException(""No Verifier has been provided for verify a signature signed using ["" + header.algorithm.getName() + ""]""); - } - - // A verifier was provided but no signature exists, this is treated as an invalid signature. - if (parts.length == 2 && verifier != null) { - throw new InvalidJWTSignatureException(); - } - - if (parts.length == 3) { - // Verify the signature before de-serializing the payload. - byte[] signature = base64Decode(parts[2].getBytes(StandardCharsets.UTF_8)); - verifier.verify(header.algorithm, message, signature); - } - - JWT jwt = Mapper.deserialize(base64Decode(parts[1].getBytes(StandardCharsets.UTF_8)), JWT.class); - - // Verify expiration claim - if (jwt.isExpired()) { - throw new JWTExpiredException(); - } - - // Verify the notBefore claim - if (jwt.isUnavailableForProcessing()) { - throw new JWTUnavailableForProcessingException(); - } - - return jwt; - } - -" -222,1," String postProcessVariableName(String variableName) { - return this.matcher.postProcessVariableName(variableName); - } - } - -} -" -223,1," public String toString() { - - StringBuilder sb = new StringBuilder("" 0) { - sb.append("" groups=\""""); - int n = 0; - Iterator 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 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()); - - } - - -" -224,1," public void processParameters( String str ) { - int end=str.length(); - int pos=0; - if( debug > 0) - log(""String: "" + str ); - - do { - boolean noEq=false; - int valStart=-1; - int valEnd=-1; - - int nameStart=pos; - int nameEnd=str.indexOf('=', nameStart ); - int nameEnd2=str.indexOf('&', nameStart ); - if( nameEnd2== -1 ) nameEnd2=end; - if( (nameEnd2!=-1 ) && - ( nameEnd==-1 || nameEnd > nameEnd2) ) { - nameEnd=nameEnd2; - noEq=true; - valStart=nameEnd; - valEnd=nameEnd; - if(debug>0) log(""no equal "" + nameStart + "" "" + nameEnd + "" "" + - str.substring(nameStart, nameEnd)); - } - - if( nameEnd== -1 ) nameEnd=end; - - if( ! noEq ) { - valStart=nameEnd+1; - valEnd=str.indexOf('&', valStart); - if( valEnd== -1 ) valEnd = (valStart < end) ? end : valStart; - } - - pos=valEnd+1; - - if( nameEnd<=nameStart ) { - continue; - } - if( debug>0) - log( ""XXX "" + nameStart + "" "" + nameEnd + "" "" - + valStart + "" "" + valEnd ); - - try { - tmpNameC.append(str, nameStart, nameEnd-nameStart ); - tmpValueC.append(str, valStart, valEnd-valStart ); - - if( debug > 0 ) - log( tmpNameC + ""= "" + tmpValueC); - - if( urlDec==null ) { - urlDec=new UDecoder(); - } - - urlDec.convert( tmpNameC ); - urlDec.convert( tmpValueC ); - - if( debug > 0 ) - log( tmpNameC + ""= "" + tmpValueC); - - addParam( tmpNameC.toString(), tmpValueC.toString() ); - } catch( IOException ex ) { - ex.printStackTrace(); - } - - tmpNameC.recycle(); - tmpValueC.recycle(); - - } while( pos users = userProvisioning.query(""username eq \""marissa\""""); - assertNotNull(users); - assertEquals(1, users.size()); - ScimUser user = users.get(0); - - ExpiringCode code = codeStore.generateCode(user.getId(), new Timestamp(System.currentTimeMillis() + UaaResetPasswordService.PASSWORD_RESET_LIFETIME), null); - getMockMvc().perform(createChangePasswordRequest(user, code, true, ""d3faultPasswd"", ""d3faultPasswd"")); - - code = codeStore.generateCode(user.getId(), new Timestamp(System.currentTimeMillis() + UaaResetPasswordService.PASSWORD_RESET_LIFETIME), null); - getMockMvc().perform(createChangePasswordRequest(user, code, true, ""d3faultPasswd"", ""d3faultPasswd"")) - .andExpect(status().isUnprocessableEntity()) - .andExpect(view().name(""forgot_password"")) - .andExpect(model().attribute(""message"", ""Your new password cannot be the same as the old password."")); - } - -" -227,1," public void recycle() { - if (buffered.getBuffer().length > 65536) { - buffered = null; - } else { - buffered.recycle(); - } - tempRead.recycle(); - hasRead = false; - buffer = null; - } - -" -228,1," public XMLLoader init(SolrParams args) { - inputFactory = XMLInputFactory.newInstance(); - 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); - } - inputFactory.setXMLReporter(xmllog); - - xsltCacheLifetimeSeconds = XSLT_CACHE_DEFAULT; - if(args != null) { - xsltCacheLifetimeSeconds = args.getInt(XSLT_CACHE_PARAM,XSLT_CACHE_DEFAULT); - log.info(""xsltCacheLifetimeSeconds="" + xsltCacheLifetimeSeconds); - } - return this; - } - -" -229,1," protected void execute() { - - Arrays.asList(controllersListStrings).forEach( - cInfoString -> controllers.add(parseCInfoString(cInfoString))); - 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 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()); - } - - -" -230,1," protected boolean parseChunkHeader() - throws IOException { - - int result = 0; - boolean eol = false; - boolean readDigit = false; - boolean trailer = false; - - while (!eol) { - - if (pos >= lastValid) { - if (readBytes() <= 0) - return false; - } - - if (buf[pos] == Constants.CR || buf[pos] == Constants.LF) { - parseCRLF(false); - eol = true; - } else if (buf[pos] == Constants.SEMI_COLON) { - trailer = true; - } else if (!trailer) { - //don't read data after the trailer - int charValue = HexUtils.getDec(buf[pos]); - if (charValue != -1) { - readDigit = true; - result *= 16; - result += charValue; - } else { - //we shouldn't allow invalid, non hex characters - //in the chunked header - return false; - } - } - - // Parsing the CRLF increments pos - if (!eol) { - pos++; - } - - } - - if (!readDigit) - return false; - - if (result == 0) - endChunk = true; - - remaining = result; - if (remaining < 0) - return false; - - return true; - - } - - - /** - * Parse CRLF at end of chunk. - * - * @param tolerant Should tolerant parsing (LF and CRLF) be used? This - * is recommended (RFC2616, section 19.3) for message - * headers. - */ -" -231,1," private static DocumentBuilder getBuilder() throws ParserConfigurationException { - ClassLoader loader = Thread.currentThread().getContextClassLoader(); - if (loader == null) { - loader = DOMUtils.class.getClassLoader(); - } - if (loader == null) { - return XMLUtils.getParser(); - } - DocumentBuilder builder = DOCUMENT_BUILDERS.get(loader); - if (builder == null) { - builder = XMLUtils.getParser(); - DOCUMENT_BUILDERS.put(loader, builder); - } - return builder; - } - - /** - * This function is much like getAttribute, but returns null, not """", for a nonexistent attribute. - * - * @param e - * @param attributeName - */ -" -232,1," public void init(Map 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) { - throw new SolrException(ErrorCode.SERVER_ERROR, ""Error initializing "" + getClass().getName() + "": ""+e); - } - } - - @SuppressWarnings(""unchecked"") -" -233,1," public void addRecipients(final ExtendedEmailPublisherContext context, EnvVars env, Set to, Set cc, Set 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.getListener(), 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 - */ -" -234,1," public void test_noVerification() throws Exception { - // Sign a JWT and then attempt to verify it using None. - JWT jwt = new JWT().setSubject(""art""); - String encodedJWT = JWT.getEncoder().encode(jwt, HMACSigner.newSHA256Signer(""secret"")); - - expectException(MissingVerifierException.class, () - -> JWT.getDecoder().decode(encodedJWT)); - } - - @Test -" -235,1," protected void configure(HttpSecurity http) throws Exception { - // This config is also on UrlAuthorizationConfigurer javadoc - http - .apply(new UrlAuthorizationConfigurer()).getRegistry() - .antMatchers(""/users**"",""/sessions/**"").hasRole(""USER"") - .antMatchers(""/signup"").hasRole(""ANONYMOUS"") - .anyRequest().hasRole(""USER""); - } - // @formatter:on -" -236,1," 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.RELOAD_XML_CONFIGURATION, Boolean.FALSE.toString()); - } - -" -237,1," public void fireOnComplete() { - List listenersCopy = new ArrayList<>(); - listenersCopy.addAll(listeners); - - ClassLoader oldCL = context.bind(Globals.IS_SECURITY_ENABLED, null); - try { - for (AsyncListenerWrapper listener : listenersCopy) { - try { - listener.fireOnComplete(event); - } catch (Throwable t) { - ExceptionUtils.handleThrowable(t); - log.warn(""onComplete() failed for listener of type ["" + - listener.getClass().getName() + ""]"", t); - } - } - } finally { - context.fireRequestDestroyEvent(request); - clearServletRequestResponse(); - context.unbind(Globals.IS_SECURITY_ENABLED, oldCL); - } - } - - -" -238,1," public void testExcludedTrickyParameters() throws Exception { - Map params = new HashMap() { - { - put(""blah"", ""This is blah""); - put(""name"", ""try_1""); - put(""(name)"", ""try_2""); - put(""['name']"", ""try_3""); - put(""['na' + 'me']"", ""try_4""); - put(""{name}[0]"", ""try_5""); - put(""(new string{'name'})[0]"", ""try_6""); - put(""#{key: 'name'}.key"", ""try_7""); - - } - }; - - HashMap extraContext = new HashMap(); - extraContext.put(ActionContext.PARAMETERS, params); - - ActionProxy proxy = actionProxyFactory.createActionProxy("""", MockConfigurationProvider.PARAM_INTERCEPTOR_ACTION_NAME, extraContext); - - ActionConfig config = configuration.getRuntimeConfiguration().getActionConfig("""", MockConfigurationProvider.PARAM_INTERCEPTOR_ACTION_NAME); - ParametersInterceptor pi =(ParametersInterceptor) config.getInterceptors().get(0).getInterceptor(); - pi.setExcludeParams(""name""); - - proxy.execute(); - - SimpleAction action = (SimpleAction) proxy.getAction(); - assertNull(action.getName()); - assertEquals(""This is blah"", (action).getBlah()); - } - -" -239,1," protected BindResult process(final LDAPConnection connection, final int depth) - throws LDAPException - { - if (connection.synchronousMode()) - { - @SuppressWarnings(""deprecation"") - final boolean autoReconnect = - connection.getConnectionOptions().autoReconnect(); - return processSync(connection, autoReconnect); - } - - // See if a bind DN was provided without a password. If that is the case - // and this should not be allowed, then throw an exception. - if (password != null) - { - if ((bindDN.getValue().length > 0) && (password.getValue().length == 0) && - connection.getConnectionOptions().bindWithDNRequiresPassword()) - { - final LDAPException le = new LDAPException(ResultCode.PARAM_ERROR, - ERR_SIMPLE_BIND_DN_WITHOUT_PASSWORD.get()); - debugCodingError(le); - throw le; - } - } - - - // Create the LDAP message. - messageID = connection.nextMessageID(); - final LDAPMessage message = new LDAPMessage(messageID, this, getControls()); - - - // Register with the connection reader to be notified of responses for the - // request that we've created. - connection.registerResponseAcceptor(messageID, this); - - - try - { - // Send the request to the server. - final long responseTimeout = getResponseTimeoutMillis(connection); - debugLDAPRequest(Level.INFO, this, messageID, connection); - final long requestTime = System.nanoTime(); - connection.getConnectionStatistics().incrementNumBindRequests(); - connection.sendMessage(message, responseTimeout); - - // Wait for and process the response. - final LDAPResponse response; - try - { - if (responseTimeout > 0) - { - response = responseQueue.poll(responseTimeout, TimeUnit.MILLISECONDS); - } - else - { - response = responseQueue.take(); - } - } - catch (final InterruptedException ie) - { - debugException(ie); - Thread.currentThread().interrupt(); - throw new LDAPException(ResultCode.LOCAL_ERROR, - ERR_BIND_INTERRUPTED.get(connection.getHostPort()), ie); - } - - return handleResponse(connection, response, requestTime, false); - } - finally - { - connection.deregisterResponseAcceptor(messageID); - } - } - - - - /** - * Processes this bind operation in synchronous mode, in which the same - * thread will send the request and read the response. - * - * @param connection The connection to use to communicate with the directory - * server. - * @param allowRetry Indicates whether the request may be re-tried on a - * re-established connection if the initial attempt fails - * in a way that indicates the connection is no longer - * valid and autoReconnect is true. - * - * @return An LDAP result object that provides information about the result - * of the bind processing. - * - * @throws LDAPException If a problem occurs while sending the request or - * reading the response. - */ -" -240,1," public Set getControllerServices(final boolean recursive) { - readLock.lock(); - try { - final Set services = new HashSet<>(); - services.addAll(controllerServices.values()); - - if (recursive && parent.get() != null) { - services.addAll(parent.get().getControllerServices(true)); - } - - return services; - } finally { - readLock.unlock(); - } - } - - @Override -" -241,1," public boolean getValidateClientProvidedNewSessionId() { - return validateClientProvidedNewSessionId; - } - - @Override -" -242,1," private static void doZipDir(File dir, ZipOutputStream out) throws IOException { - File[] children = dir.listFiles(); - if (children == null) { - throw new IllegalStateException(""Fail to list files of directory "" + dir.getAbsolutePath()); - } - for (File child : children) { - doZip(child.getName(), child, out); - } - } - - /** - * @see #unzip(File, File, Predicate) - * @deprecated replaced by {@link Predicate} in 6.2. - */ - @Deprecated - @FunctionalInterface -" -243,1," public H and() { - return ChannelSecurityConfigurer.this.and(); - } - -" -244,1," public boolean isLockoutEnabled() { - return countFailuresWithin > 0; - } - -" -245,1," protected synchronized void authenticatorConfig() { - - // Always need an authenticator to support @ServletSecurity annotations - LoginConfig loginConfig = context.getLoginConfig(); - if (loginConfig == null) { - loginConfig = DUMMY_LOGIN_CONFIG; - context.setLoginConfig(loginConfig); - } - - // Has an authenticator been configured already? - if (context.getAuthenticator() != null) - return; - - if (!(context instanceof ContainerBase)) { - return; // Cannot install a Valve even if it would be needed - } - - // Has a Realm been configured for us to authenticate against? - if (context.getRealm() == null) { - log.error(sm.getString(""contextConfig.missingRealm"")); - ok = false; - return; - } - - /* - * First check to see if there is a custom mapping for the login - * method. If so, use it. Otherwise, check if there is a mapping in - * org/apache/catalina/startup/Authenticators.properties. - */ - Valve authenticator = null; - if (customAuthenticators != null) { - authenticator = (Valve) - customAuthenticators.get(loginConfig.getAuthMethod()); - } - if (authenticator == null) { - // Load our mapping properties if necessary - if (authenticators == null) { - try { - InputStream is=this.getClass().getClassLoader().getResourceAsStream(""org/apache/catalina/startup/Authenticators.properties""); - if( is!=null ) { - authenticators = new Properties(); - authenticators.load(is); - } else { - log.error(sm.getString( - ""contextConfig.authenticatorResources"")); - ok=false; - return; - } - } catch (IOException e) { - log.error(sm.getString( - ""contextConfig.authenticatorResources""), e); - ok = false; - return; - } - } - - // Identify the class name of the Valve we should configure - String authenticatorName = null; - authenticatorName = - authenticators.getProperty(loginConfig.getAuthMethod()); - if (authenticatorName == null) { - log.error(sm.getString(""contextConfig.authenticatorMissing"", - loginConfig.getAuthMethod())); - ok = false; - return; - } - - // Instantiate and install an Authenticator of the requested class - try { - Class authenticatorClass = Class.forName(authenticatorName); - authenticator = (Valve) authenticatorClass.newInstance(); - } catch (Throwable t) { - ExceptionUtils.handleThrowable(t); - log.error(sm.getString( - ""contextConfig.authenticatorInstantiate"", - authenticatorName), - t); - ok = false; - } - } - - if (authenticator != null && context instanceof ContainerBase) { - Pipeline pipeline = ((ContainerBase) context).getPipeline(); - if (pipeline != null) { - ((ContainerBase) context).getPipeline().addValve(authenticator); - if (log.isDebugEnabled()) { - log.debug(sm.getString( - ""contextConfig.authenticatorConfigured"", - loginConfig.getAuthMethod())); - } - } - } - - } - - - /** - * Create (if necessary) and return a Digester configured to process the - * web application deployment descriptor (web.xml). - */ -" -246,1," private void processInternal(Exchange exchange, AsyncCallback callback) throws Exception { - // creating the url to use takes 2-steps - String url = HttpHelper.createURL(exchange, getEndpoint()); - URI uri = HttpHelper.createURI(exchange, url, getEndpoint()); - // get the url from the uri - url = uri.toASCIIString(); - - // execute any custom url rewrite - String rewriteUrl = HttpHelper.urlRewrite(exchange, url, getEndpoint(), this); - if (rewriteUrl != null) { - // update url and query string from the rewritten url - url = rewriteUrl; - } - - String methodName = HttpHelper.createMethod(exchange, getEndpoint(), exchange.getIn().getBody() != null).name(); - - JettyContentExchange httpExchange = getEndpoint().createContentExchange(); - httpExchange.init(exchange, getBinding(), client, callback); - httpExchange.setURL(url); // Url has to be set first - httpExchange.setMethod(methodName); - - if (getEndpoint().getHttpClientParameters() != null) { - // For jetty 9 these parameters can not be set on the client - // so we need to set them on the httpExchange - String timeout = (String)getEndpoint().getHttpClientParameters().get(""timeout""); - if (timeout != null) { - httpExchange.setTimeout(new Long(timeout)); - } - String supportRedirect = (String)getEndpoint().getHttpClientParameters().get(""supportRedirect""); - if (supportRedirect != null) { - httpExchange.setSupportRedirect(Boolean.valueOf(supportRedirect)); - } - } - - LOG.trace(""Using URL: {} with method: {}"", url, methodName); - - // if there is a body to send as data - if (exchange.getIn().getBody() != null) { - String contentType = ExchangeHelper.getContentType(exchange); - if (contentType != null) { - httpExchange.setRequestContentType(contentType); - } - - if (contentType != null && HttpConstants.CONTENT_TYPE_JAVA_SERIALIZED_OBJECT.equals(contentType)) { - // serialized java object - Serializable obj = exchange.getIn().getMandatoryBody(Serializable.class); - // write object to output stream - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - try { - HttpHelper.writeObjectToStream(bos, obj); - httpExchange.setRequestContent(bos.toByteArray()); - } finally { - IOHelper.close(bos, ""body"", LOG); - } - } else { - Object body = exchange.getIn().getBody(); - if (body instanceof String) { - String data = (String) body; - // be a bit careful with String as any type can most likely be converted to String - // so we only do an instanceof check and accept String if the body is really a String - // do not fallback to use the default charset as it can influence the request - // (for example application/x-www-form-urlencoded forms being sent) - String charset = IOHelper.getCharsetName(exchange, false); - httpExchange.setRequestContent(data, charset); - } else { - // then fallback to input stream - InputStream is = exchange.getContext().getTypeConverter().mandatoryConvertTo(InputStream.class, exchange, exchange.getIn().getBody()); - httpExchange.setRequestContent(is); - // setup the content length if it is possible - String length = exchange.getIn().getHeader(Exchange.CONTENT_LENGTH, String.class); - if (ObjectHelper.isNotEmpty(length)) { - httpExchange.addRequestHeader(Exchange.CONTENT_LENGTH, length); - } - } - } - } - - // 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 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""); - } - - // propagate headers as HTTP headers - Message in = exchange.getIn(); - HeaderFilterStrategy strategy = getEndpoint().getHeaderFilterStrategy(); - for (Map.Entry 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 values to add as a request header - final List values = new ArrayList(); - - // 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); - httpExchange.addRequestHeader(key, s); - } - } - } - - // set the callback, which will handle all the response logic - if (LOG.isDebugEnabled()) { - LOG.debug(""Sending HTTP request to: {}"", httpExchange.getUrl()); - } - httpExchange.send(client); - } - -" -247,1," public void send(final String format, final Object... args) { - descriptor.debug(logger, format, args); - } - } - final Debug debug = new Debug(); - - Set users = null; - - final Run currentRun = context.getRun(); - if (currentRun == null) { - debug.send(""currentRun was null""); - } else { - if (!Objects.equals(currentRun.getResult(), Result.FAILURE)) { - debug.send(""currentBuild did not fail""); - } else { - users = new HashSet<>(); - debug.send(""Collecting builds with suspects...""); - final HashSet> buildsWithSuspects = new HashSet<>(); - Run firstFailedBuild = currentRun; - Run candidate = currentRun; - while (candidate != null) { - final Result candidateResult = candidate.getResult(); - if ( candidateResult == null || !candidateResult.isWorseOrEqualTo(Result.FAILURE) ) { - break; - } - firstFailedBuild = candidate; - candidate = candidate.getPreviousCompletedBuild(); - } - if (firstFailedBuild instanceof AbstractBuild) { - buildsWithSuspects.add(firstFailedBuild); - } else { - debug.send("" firstFailedBuild was not an instance of AbstractBuild""); - } - debug.send(""Collecting suspects...""); - users.addAll(RecipientProviderUtilities.getChangeSetAuthors(buildsWithSuspects, debug)); - users.addAll(RecipientProviderUtilities.getUsersTriggeringTheBuilds(buildsWithSuspects, debug)); - } - } - if (users != null) { - RecipientProviderUtilities.addUsers(users, context.getListener(), env, to, cc, bcc, debug); - } - } - - @Extension - public static final class DescriptorImpl extends RecipientProviderDescriptor { - @Override - public String getDisplayName() { - return ""Suspects Causing the Build to Begin Failing""; - } - } - -} -" -248,1," public Document getMetaData(Idp config) throws RuntimeException { - //Return as text/xml - try { - Crypto crypto = CertsUtils.createCrypto(config.getCertificate()); - - ByteArrayOutputStream bout = new ByteArrayOutputStream(4096); - Writer streamWriter = new OutputStreamWriter(bout, ""UTF-8""); - XMLStreamWriter writer = XML_OUTPUT_FACTORY.createXMLStreamWriter(streamWriter); - - writer.writeStartDocument(""UTF-8"", ""1.0""); - - String referenceID = IDGenerator.generateID(""_""); - writer.writeStartElement(""md"", ""EntityDescriptor"", SAML2_METADATA_NS); - writer.writeAttribute(""ID"", referenceID); - - writer.writeAttribute(""entityID"", config.getIdpUrl().toString()); - - 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); - - writeFederationMetadata(writer, config, crypto); - - 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()); - - Document result = SignatureUtils.signMetaInfo(crypto, null, config.getCertificatePassword(), is, referenceID); - if (result != null) { - return result; - } else { - throw new RuntimeException(""Failed to sign the metadata document: result=null""); - } - } catch (RuntimeException e) { - throw e; - } catch (Exception e) { - LOG.error(""Error creating service metadata information "", e); - throw new RuntimeException(""Error creating service metadata information: "" + e.getMessage()); - } - - } - -" -249,1," public void chaosSnapshotTest() throws Exception { - final List indices = new CopyOnWriteArrayList<>(); - Settings settings = settingsBuilder().put(""action.write_consistency"", ""one"").build(); - int initialNodes = between(1, 3); - logger.info(""--> start {} nodes"", initialNodes); - for (int i = 0; i < initialNodes; i++) { - internalCluster().startNode(settings); - } - - logger.info(""--> creating repository""); - assertAcked(client().admin().cluster().preparePutRepository(""test-repo"") - .setType(""fs"").setSettings(ImmutableSettings.settingsBuilder() - .put(""location"", newTempDir(LifecycleScope.SUITE)) - .put(""compress"", randomBoolean()) - .put(""chunk_size"", randomIntBetween(100, 1000)))); - - int initialIndices = between(1, 3); - logger.info(""--> create {} indices"", initialIndices); - for (int i = 0; i < initialIndices; i++) { - createTestIndex(""test-"" + i); - indices.add(""test-"" + i); - } - - int asyncNodes = between(0, 5); - logger.info(""--> start {} additional nodes asynchronously"", asyncNodes); - ListenableFuture> asyncNodesFuture = internalCluster().startNodesAsync(asyncNodes, settings); - - int asyncIndices = between(0, 10); - logger.info(""--> create {} additional indices asynchronously"", asyncIndices); - Thread[] asyncIndexThreads = new Thread[asyncIndices]; - for (int i = 0; i < asyncIndices; i++) { - final int cur = i; - asyncIndexThreads[i] = new Thread(new Runnable() { - @Override - public void run() { - createTestIndex(""test-async-"" + cur); - indices.add(""test-async-"" + cur); - - } - }); - asyncIndexThreads[i].start(); - } - - logger.info(""--> snapshot""); - - ListenableActionFuture snapshotResponseFuture = client().admin().cluster().prepareCreateSnapshot(""test-repo"", ""test-snap"").setWaitForCompletion(true).setIndices(""test-*"").setPartial(true).execute(); - - long start = System.currentTimeMillis(); - // Produce chaos for 30 sec or until snapshot is done whatever comes first - int randomIndices = 0; - while (System.currentTimeMillis() - start < 30000 && !snapshotIsDone(""test-repo"", ""test-snap"")) { - Thread.sleep(100); - int chaosType = randomInt(10); - if (chaosType < 4) { - // Randomly delete an index - if (indices.size() > 0) { - String index = indices.remove(randomInt(indices.size() - 1)); - logger.info(""--> deleting random index [{}]"", index); - internalCluster().wipeIndices(index); - } - } else if (chaosType < 6) { - // Randomly shutdown a node - if (cluster().size() > 1) { - logger.info(""--> shutting down random node""); - internalCluster().stopRandomDataNode(); - } - } else if (chaosType < 8) { - // Randomly create an index - String index = ""test-rand-"" + randomIndices; - logger.info(""--> creating random index [{}]"", index); - createTestIndex(index); - randomIndices++; - } else { - // Take a break - logger.info(""--> noop""); - } - } - - logger.info(""--> waiting for async indices creation to finish""); - for (int i = 0; i < asyncIndices; i++) { - asyncIndexThreads[i].join(); - } - - logger.info(""--> update index settings to back to normal""); - assertAcked(client().admin().indices().prepareUpdateSettings(""test-*"").setSettings(ImmutableSettings.builder() - .put(AbstractIndexStore.INDEX_STORE_THROTTLE_TYPE, ""node"") - )); - - // Make sure that snapshot finished - doesn't matter if it failed or succeeded - try { - CreateSnapshotResponse snapshotResponse = snapshotResponseFuture.get(); - SnapshotInfo snapshotInfo = snapshotResponse.getSnapshotInfo(); - assertNotNull(snapshotInfo); - logger.info(""--> snapshot is done with state [{}], total shards [{}], successful shards [{}]"", snapshotInfo.state(), snapshotInfo.totalShards(), snapshotInfo.successfulShards()); - } catch (Exception ex) { - logger.info(""--> snapshot didn't start properly"", ex); - } - - asyncNodesFuture.get(); - logger.info(""--> done""); - } - -" -250,1," public Principal authenticate(String username, String credentials) { - - // No user or no credentials - // Can't possibly authenticate, don't bother the database then - if (username == null || credentials == null) { - if (log.isDebugEnabled()) - log.debug(sm.getString(""memoryRealm.authenticateFailure"", username)); - return null; - } - - GenericPrincipal principal = principals.get(username); - - if(principal == null || principal.getPassword() == null) { - // User was not found in the database of the password was null - - if (log.isDebugEnabled()) - log.debug(sm.getString(""memoryRealm.authenticateFailure"", username)); - return null; - } - - boolean validated = getCredentialHandler().matches(credentials, principal.getPassword()); - - if (validated) { - if (log.isDebugEnabled()) - log.debug(sm.getString(""memoryRealm.authenticateSuccess"", username)); - return principal; - } else { - if (log.isDebugEnabled()) - log.debug(sm.getString(""memoryRealm.authenticateFailure"", username)); - return null; - } - } - - - // -------------------------------------------------------- Package Methods - - - /** - * Add a new user to the in-memory database. - * - * @param username User's username - * @param password User's password (clear text) - * @param roles Comma-delimited set of roles associated with this user - */ -" -251,1," public Object getValue(Object o) { - if ( location.getMember() == null ) { - return o; - } - else { - return ReflectionHelper.getValue( location.getMember(), o ); - } - } - - @Override -" -252,1," private String buildErrorMessage(Throwable e, Object[] args) { - String errorKey = ""struts.message.upload.error."" + e.getClass().getSimpleName(); - if (LOG.isDebugEnabled()) - LOG.debug(""Preparing error message for key: [#0]"", errorKey); - return LocalizedTextUtil.findText(this.getClass(), errorKey, defaultLocale, e.getMessage(), args); - } - - /** - * Build action message. - * - * @param e - * @param args - * @return - */ -" -253,1," private void resetContext() throws Exception { - // Restore the original state ( pre reading web.xml in start ) - // If you extend this - override this method and make sure to clean up - - // Don't reset anything that is read from a element since - // elements are read at initialisation will not be read - // again for this object - children = new HashMap(); - startupTime = 0; - startTime = 0; - tldScanTime = 0; - - // Bugzilla 32867 - distributable = false; - - applicationListeners = new String[0]; - applicationEventListenersObjects = new Object[0]; - applicationLifecycleListenersObjects = new Object[0]; - jspConfigDescriptor = new ApplicationJspConfigDescriptor(); - - initializers.clear(); - - if(log.isDebugEnabled()) - log.debug(""resetContext "" + getObjectName()); - } - - /** - * Return a String representation of this component. - */ - @Override -" -254,1," public void testRestoreToShadow() throws ExecutionException, InterruptedException { - Settings nodeSettings = nodeSettings(); - - internalCluster().startNodesAsync(3, nodeSettings).get(); - final Path dataPath = newTempDir().toPath(); - Settings idxSettings = ImmutableSettings.builder() - .put(IndexMetaData.SETTING_NUMBER_OF_SHARDS, 1) - .put(IndexMetaData.SETTING_NUMBER_OF_REPLICAS, 0).build(); - assertAcked(prepareCreate(""foo"").setSettings(idxSettings)); - ensureGreen(); - final int numDocs = randomIntBetween(10, 100); - for (int i = 0; i < numDocs; i++) { - client().prepareIndex(""foo"", ""doc"", """"+i).setSource(""foo"", ""bar"").get(); - } - assertNoFailures(client().admin().indices().prepareFlush().setForce(true).setWaitIfOngoing(true).execute().actionGet()); - - assertAcked(client().admin().cluster().preparePutRepository(""test-repo"") - .setType(""fs"").setSettings(ImmutableSettings.settingsBuilder() - .put(""location"", newTempDir().toPath()))); - CreateSnapshotResponse createSnapshotResponse = client().admin().cluster().prepareCreateSnapshot(""test-repo"", ""test-snap"").setWaitForCompletion(true).setIndices(""foo"").get(); - assertThat(createSnapshotResponse.getSnapshotInfo().successfulShards(), greaterThan(0)); - assertThat(createSnapshotResponse.getSnapshotInfo().successfulShards(), equalTo(createSnapshotResponse.getSnapshotInfo().totalShards())); - assertThat(client().admin().cluster().prepareGetSnapshots(""test-repo"").setSnapshots(""test-snap"").get().getSnapshots().get(0).state(), equalTo(SnapshotState.SUCCESS)); - - Settings shadowSettings = ImmutableSettings.builder() - .put(IndexMetaData.SETTING_DATA_PATH, dataPath.toAbsolutePath().toString()) - .put(IndexMetaData.SETTING_SHADOW_REPLICAS, true) - .put(IndexMetaData.SETTING_SHARED_FILESYSTEM, true) - .put(IndexMetaData.SETTING_NUMBER_OF_REPLICAS, 2).build(); - - logger.info(""--> restore the index into shadow replica index""); - RestoreSnapshotResponse restoreSnapshotResponse = client().admin().cluster().prepareRestoreSnapshot(""test-repo"", ""test-snap"") - .setIndexSettings(shadowSettings).setWaitForCompletion(true) - .setRenamePattern(""(.+)"").setRenameReplacement(""$1-copy"") - .execute().actionGet(); - assertThat(restoreSnapshotResponse.getRestoreInfo().totalShards(), greaterThan(0)); - ensureGreen(); - refresh(); - - for (IndicesService service : internalCluster().getDataNodeInstances(IndicesService.class)) { - if (service.hasIndex(""foo-copy"")) { - IndexShard shard = service.indexServiceSafe(""foo-copy"").shard(0); - if (shard.routingEntry().primary()) { - assertFalse(shard instanceof ShadowIndexShard); - } else { - assertTrue(shard instanceof ShadowIndexShard); - } - } - } - logger.info(""--> performing query""); - SearchResponse resp = client().prepareSearch(""foo-copy"").setQuery(matchAllQuery()).get(); - assertHitCount(resp, numDocs); - - } - - @Test -" -255,1," public KeyPair generateKeyPair() - { - if (!initialised) - { - DSAParametersGenerator pGen = new DSAParametersGenerator(); - - pGen.init(strength, certainty, random); - param = new DSAKeyGenerationParameters(random, pGen.generateParameters()); - engine.init(param); - initialised = true; - } - - AsymmetricCipherKeyPair pair = engine.generateKeyPair(); - DSAPublicKeyParameters pub = (DSAPublicKeyParameters)pair.getPublic(); - DSAPrivateKeyParameters priv = (DSAPrivateKeyParameters)pair.getPrivate(); - - return new KeyPair(new BCDSAPublicKey(pub), new BCDSAPrivateKey(priv)); - } -" -256,1," public void testInvalidate() throws IOException { - ProjectWorkspace workspace = - TestDataHelper.createProjectWorkspaceForScenario(this, ""parser_with_cell"", tmp); - workspace.setUp(); - - // Warm the parser cache. - TestContext context = new TestContext(); - ProcessResult runBuckResult = - workspace.runBuckdCommand(context, ""query"", ""deps(//Apps:TestAppsLibrary)""); - runBuckResult.assertSuccess(); - assertThat( - runBuckResult.getStdout(), - Matchers.containsString( - ""//Apps:TestAppsLibrary\n"" - + ""//Libraries/Dep1:Dep1_1\n"" - + ""//Libraries/Dep1:Dep1_2\n"" - + ""bar//Dep2:Dep2"")); - - // Save the parser cache to a file. - NamedTemporaryFile tempFile = new NamedTemporaryFile(""parser_data"", null); - runBuckResult = - workspace.runBuckdCommand(context, ""parser-cache"", ""--save"", tempFile.get().toString()); - runBuckResult.assertSuccess(); - - // Write an empty content to Apps/BUCK. - Path path = tmp.getRoot().resolve(""Apps/BUCK""); - byte[] data = {}; - Files.write(path, data); - - // Write an empty content to Apps/BUCK. - Path invalidationJsonPath = tmp.getRoot().resolve(""invalidation-data.json""); - String jsonData = ""[{\""path\"":\""Apps/BUCK\"",\""status\"":\""M\""}]""; - Files.write(invalidationJsonPath, jsonData.getBytes(StandardCharsets.UTF_8)); - - context = new TestContext(); - // Load the parser cache to a new buckd context. - runBuckResult = - workspace.runBuckdCommand( - context, - ""parser-cache"", - ""--load"", - tempFile.get().toString(), - ""--changes"", - invalidationJsonPath.toString()); - runBuckResult.assertSuccess(); - - // Perform the query again. - try { - workspace.runBuckdCommand(context, ""query"", ""deps(//Apps:TestAppsLibrary)""); - } catch (HumanReadableException e) { - assertThat( - e.getMessage(), Matchers.containsString(""//Apps:TestAppsLibrary could not be found"")); - } - } -" -257,1," public void send(final String format, final Object... args) { - descriptor.debug(logger, format, args); - } - } - final Debug debug = new Debug(); - Set users = RecipientProviderUtilities.getChangeSetAuthors(Collections.>singleton(context.getRun()), debug); - RecipientProviderUtilities.addUsers(users, context.getListener(), env, to, cc, bcc, debug); - } - - @Extension - public static final class DescriptorImpl extends RecipientProviderDescriptor { - @Override - public String getDisplayName() { - return ""Developers""; - } - } -} -" -258,1," public void testRejectBindWithDNButNoPassword() - throws Exception - { - if (! isDirectoryInstanceAvailable()) - { - return; - } - - LDAPConnection conn = getUnauthenticatedConnection(); - SimpleBindRequest bindRequest = new SimpleBindRequest(getTestBindDN(), """"); - - try - { - bindRequest.process(conn, 1); - fail(""Expected an exception when binding with a DN but no password""); - } - catch (LDAPException le) - { - assertEquals(le.getResultCode(), ResultCode.PARAM_ERROR); - } - - - // Reconfigure the connection so that it will allow binds with a DN but no - // password. - conn.getConnectionOptions().setBindWithDNRequiresPassword(false); - try - { - bindRequest.process(conn, 1); - } - catch (LDAPException le) - { - // The server will still likely reject the operation, but we should at - // least verify that it wasn't a parameter error. - assertFalse(le.getResultCode() == ResultCode.PARAM_ERROR); - } - - conn.getConnectionOptions().setBindWithDNRequiresPassword(true); - conn.close(); - } -" -259,1," public LockoutPolicy getLockoutPolicy() { - LockoutPolicy res = IdentityZoneHolder.get().getConfig().getClientLockoutPolicy(); - return res.getLockoutAfterFailures() != -1 ? res : defaultLockoutPolicy; - } - - @Override -" -260,1," private void detectJPA() { - // check whether we have Persistence on the classpath - Class persistenceClass; - try { - persistenceClass = run( LoadClass.action( PERSISTENCE_CLASS_NAME, this.getClass() ) ); - } - catch ( ValidationException e ) { - log.debugf( - ""Cannot find %s on classpath. Assuming non JPA 2 environment. All properties will per default be traversable."", - PERSISTENCE_CLASS_NAME - ); - return; - } - - // check whether Persistence contains getPersistenceUtil - Method persistenceUtilGetter = run( GetMethod.action( persistenceClass, PERSISTENCE_UTIL_METHOD ) ); - if ( persistenceUtilGetter == null ) { - log.debugf( - ""Found %s on classpath, but no method '%s'. Assuming JPA 1 environment. All properties will per default be traversable."", - PERSISTENCE_CLASS_NAME, - PERSISTENCE_UTIL_METHOD - ); - return; - } - - // try to invoke the method to make sure that we are dealing with a complete JPA2 implementation - // unfortunately there are several incomplete implementations out there (see HV-374) - try { - Object persistence = run( NewInstance.action( persistenceClass, ""persistence provider"" ) ); - ReflectionHelper.getValue(persistenceUtilGetter, persistence ); - } - catch ( Exception e ) { - log.debugf( - ""Unable to invoke %s.%s. Inconsistent JPA environment. All properties will per default be traversable."", - PERSISTENCE_CLASS_NAME, - PERSISTENCE_UTIL_METHOD - ); - } - - log.debugf( - ""Found %s on classpath containing '%s'. Assuming JPA 2 environment. Trying to instantiate JPA aware TraversableResolver"", - PERSISTENCE_CLASS_NAME, - PERSISTENCE_UTIL_METHOD - ); - - try { - @SuppressWarnings(""unchecked"") - Class jpaAwareResolverClass = (Class) - run( LoadClass.action( JPA_AWARE_TRAVERSABLE_RESOLVER_CLASS_NAME, this.getClass() ) ); - jpaTraversableResolver = run( NewInstance.action( jpaAwareResolverClass, """" ) ); - log.debugf( - ""Instantiated JPA aware TraversableResolver of type %s."", JPA_AWARE_TRAVERSABLE_RESOLVER_CLASS_NAME - ); - } - catch ( ValidationException e ) { - log.debugf( - ""Unable to load or instantiate JPA aware resolver %s. All properties will per default be traversable."", - JPA_AWARE_TRAVERSABLE_RESOLVER_CLASS_NAME - ); - } - } - - @Override -" -261,1," public void addRecipients(final ExtendedEmailPublisherContext context, EnvVars env, Set to, Set cc, Set 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(); - Run run = context.getRun(); - final Result runResult = run.getResult(); - if (run instanceof AbstractBuild) { - Set users = ((AbstractBuild)run).getCulprits(); - RecipientProviderUtilities.addUsers(users, context.getListener(), env, to, cc, bcc, debug); - } else if (runResult != null) { - List> builds = new ArrayList<>(); - Run build = run; - builds.add(build); - build = build.getPreviousCompletedBuild(); - while (build != null) { - final Result buildResult = build.getResult(); - if (buildResult != null) { - if (buildResult.isWorseThan(Result.SUCCESS)) { - debug.send(""Including build %s with status %s"", build.getId(), buildResult); - builds.add(build); - } else { - break; - } - } - build = build.getPreviousCompletedBuild(); - } - Set users = RecipientProviderUtilities.getChangeSetAuthors(builds, debug); - RecipientProviderUtilities.addUsers(users, context.getListener(), env, to, cc, bcc, debug); - } - } - - @Extension -" -262,1," protected boolean isProbablePrime(BigInteger x) - { - /* - * Primes class for FIPS 186-4 C.3 primality checking - */ - return !Primes.hasAnySmallFactors(x) && Primes.isMRProbablePrime(x, param.getRandom(), iterations); - } - -" -263,1," public void batchingShardUpdateTaskTest() throws Exception { - - final Client client = client(); - - logger.info(""--> creating repository""); - assertAcked(client.admin().cluster().preparePutRepository(""test-repo"") - .setType(""fs"").setSettings(ImmutableSettings.settingsBuilder() - .put(""location"", newTempDir()) - .put(""compress"", randomBoolean()) - .put(""chunk_size"", randomIntBetween(100, 1000)))); - - assertAcked(prepareCreate(""test-idx"", 0, settingsBuilder().put(""number_of_shards"", between(1, 20)) - .put(""number_of_replicas"", 0))); - ensureGreen(); - - logger.info(""--> indexing some data""); - final int numdocs = randomIntBetween(10, 100); - IndexRequestBuilder[] builders = new IndexRequestBuilder[numdocs]; - for (int i = 0; i < builders.length; i++) { - builders[i] = client().prepareIndex(""test-idx"", ""type1"", Integer.toString(i)).setSource(""field1"", ""bar "" + i); - } - indexRandom(true, builders); - flushAndRefresh(); - - final int numberOfShards = getNumShards(""test-idx"").numPrimaries; - logger.info(""number of shards: {}"", numberOfShards); - - final ClusterService clusterService = internalCluster().clusterService(internalCluster().getMasterName()); - BlockingClusterStateListener snapshotListener = new BlockingClusterStateListener(clusterService, ""update_snapshot ["", ""update snapshot state"", Priority.HIGH); - try { - clusterService.addFirst(snapshotListener); - logger.info(""--> snapshot""); - ListenableActionFuture snapshotFuture = client.admin().cluster().prepareCreateSnapshot(""test-repo"", ""test-snap"").setWaitForCompletion(true).setIndices(""test-idx"").execute(); - - // Await until shard updates are in pending state. - assertBusyPendingTasks(""update snapshot state"", numberOfShards); - snapshotListener.unblock(); - - // Check that the snapshot was successful - CreateSnapshotResponse createSnapshotResponse = snapshotFuture.actionGet(); - assertEquals(SnapshotState.SUCCESS, createSnapshotResponse.getSnapshotInfo().state()); - assertEquals(numberOfShards, createSnapshotResponse.getSnapshotInfo().totalShards()); - assertEquals(numberOfShards, createSnapshotResponse.getSnapshotInfo().successfulShards()); - - } finally { - clusterService.remove(snapshotListener); - } - - // Check that we didn't timeout - assertFalse(snapshotListener.timedOut()); - // Check that cluster state update task was called only once - assertEquals(1, snapshotListener.count()); - - logger.info(""--> close indices""); - client.admin().indices().prepareClose(""test-idx"").get(); - - BlockingClusterStateListener restoreListener = new BlockingClusterStateListener(clusterService, ""restore_snapshot["", ""update snapshot state"", Priority.HIGH); - - try { - clusterService.addFirst(restoreListener); - logger.info(""--> restore snapshot""); - ListenableActionFuture futureRestore = client.admin().cluster().prepareRestoreSnapshot(""test-repo"", ""test-snap"").setWaitForCompletion(true).execute(); - - // Await until shard updates are in pending state. - assertBusyPendingTasks(""update snapshot state"", numberOfShards); - restoreListener.unblock(); - - RestoreSnapshotResponse restoreSnapshotResponse = futureRestore.actionGet(); - assertThat(restoreSnapshotResponse.getRestoreInfo().totalShards(), equalTo(numberOfShards)); - - } finally { - clusterService.remove(restoreListener); - } - - // Check that we didn't timeout - assertFalse(restoreListener.timedOut()); - // Check that cluster state update task was called only once - assertEquals(1, restoreListener.count()); - } - -" -264,1," private File getLocationUnderBuild(AbstractBuild build) { - return new File(build.getRootDir(), ""fileParameters/"" + location); - } - - /** - * Default implementation from {@link File}. - */ -" -265,1," protected Details authenticate(String username, String password) throws AuthenticationException { - Details u = loadUserByUsername(username); - if (!u.isPasswordCorrect(password)) - throw new BadCredentialsException(""Failed to login as ""+username); - return u; - } - - /** - * Show the sign up page with the data from the identity. - */ - @Override -" -266,1," public void resetPassword_InvalidPasswordException_NewPasswordSameAsOld() { - ScimUser user = new ScimUser(""user-id"", ""username"", ""firstname"", ""lastname""); - user.setMeta(new ScimMeta(new Date(), new Date(), 0)); - user.setPrimaryEmail(""foo@example.com""); - ExpiringCode expiringCode = new ExpiringCode(""good_code"", - new Timestamp(System.currentTimeMillis() + UaaResetPasswordService.PASSWORD_RESET_LIFETIME), ""user-id"", null); - when(codeStore.retrieveCode(""good_code"")).thenReturn(expiringCode); - when(scimUserProvisioning.retrieve(""user-id"")).thenReturn(user); - when(scimUserProvisioning.checkPasswordMatches(""user-id"", ""Passwo3dAsOld"")) - .thenThrow(new InvalidPasswordException(""Your new password cannot be the same as the old password."", UNPROCESSABLE_ENTITY)); - SecurityContext securityContext = mock(SecurityContext.class); - when(securityContext.getAuthentication()).thenReturn(new MockAuthentication()); - SecurityContextHolder.setContext(securityContext); - try { - emailResetPasswordService.resetPassword(""good_code"", ""Passwo3dAsOld""); - fail(); - } catch (InvalidPasswordException e) { - assertEquals(""Your new password cannot be the same as the old password."", e.getMessage()); - assertEquals(UNPROCESSABLE_ENTITY, e.getStatus()); - } - } - - @Test -" -267,1," public boolean getValidateClientProvidedNewSessionId() { return false; } -" -268,1," protected Http11AprProcessor createProcessor() { - Http11AprProcessor processor = new Http11AprProcessor( - proto.getMaxHttpHeaderSize(), (AprEndpoint)proto.endpoint, - proto.getMaxTrailerSize()); - processor.setAdapter(proto.getAdapter()); - processor.setMaxKeepAliveRequests(proto.getMaxKeepAliveRequests()); - processor.setKeepAliveTimeout(proto.getKeepAliveTimeout()); - processor.setConnectionUploadTimeout( - proto.getConnectionUploadTimeout()); - processor.setDisableUploadTimeout(proto.getDisableUploadTimeout()); - processor.setCompressionMinSize(proto.getCompressionMinSize()); - processor.setCompression(proto.getCompression()); - processor.setNoCompressionUserAgents(proto.getNoCompressionUserAgents()); - processor.setCompressableMimeTypes(proto.getCompressableMimeTypes()); - processor.setRestrictedUserAgents(proto.getRestrictedUserAgents()); - processor.setSocketBuffer(proto.getSocketBuffer()); - processor.setMaxSavePostSize(proto.getMaxSavePostSize()); - processor.setServer(proto.getServer()); - processor.setClientCertProvider(proto.getClientCertProvider()); - register(processor); - return processor; - } - - @Override -" -269,1," public synchronized Servlet loadServlet() throws ServletException { - - // Nothing to do if we already have an instance or an instance pool - if (!singleThreadModel && (instance != null)) - return instance; - - PrintStream out = System.out; - if (swallowOutput) { - SystemLogHandler.startCapture(); - } - - Servlet servlet; - try { - long t1=System.currentTimeMillis(); - // Complain if no servlet class has been specified - if (servletClass == null) { - unavailable(null); - throw new ServletException - (sm.getString(""standardWrapper.notClass"", getName())); - } - - InstanceManager instanceManager = ((StandardContext)getParent()).getInstanceManager(); - try { - servlet = (Servlet) instanceManager.newInstance(servletClass); - } catch (ClassCastException e) { - unavailable(null); - // Restore the context ClassLoader - throw new ServletException - (sm.getString(""standardWrapper.notServlet"", servletClass), e); - } catch (Throwable e) { - ExceptionUtils.handleThrowable(e); - unavailable(null); - - // Added extra log statement for Bugzilla 36630: - // http://issues.apache.org/bugzilla/show_bug.cgi?id=36630 - if(log.isDebugEnabled()) { - log.debug(sm.getString(""standardWrapper.instantiate"", servletClass), e); - } - - // Restore the context ClassLoader - throw new ServletException - (sm.getString(""standardWrapper.instantiate"", servletClass), e); - } - - if (multipartConfigElement == null) { - MultipartConfig annotation = - servlet.getClass().getAnnotation(MultipartConfig.class); - if (annotation != null) { - multipartConfigElement = - new MultipartConfigElement(annotation); - } - } - - ServletSecurity secAnnotation = - servlet.getClass().getAnnotation(ServletSecurity.class); - Context ctxt = (Context) getParent(); - if (secAnnotation != null) { - ctxt.addServletSecurity( - new ApplicationServletRegistration(this, ctxt), - new ServletSecurityElement(secAnnotation)); - } - - - // Special handling for ContainerServlet instances - if ((servlet instanceof ContainerServlet) && - (isContainerProvidedServlet(servletClass) || - ctxt.getPrivileged() )) { - ((ContainerServlet) servlet).setWrapper(this); - } - - classLoadTime=(int) (System.currentTimeMillis() -t1); - - initServlet(servlet); - - // Register our newly initialized instance - singleThreadModel = servlet instanceof SingleThreadModel; - if (singleThreadModel) { - if (instancePool == null) - instancePool = new Stack(); - } - fireContainerEvent(""load"", this); - - loadTime=System.currentTimeMillis() -t1; - } finally { - if (swallowOutput) { - String log = SystemLogHandler.stopCapture(); - if (log != null && log.length() > 0) { - if (getServletContext() != null) { - getServletContext().log(log); - } else { - out.println(log); - } - } - } - } - return servlet; - - } - -" -270,1," public void testWelcomeFileStrict() throws Exception { - - Tomcat tomcat = getTomcatInstance(); - - File appDir = new File(""test/webapp""); - - StandardContext ctxt = (StandardContext) tomcat.addWebapp(null, ""/test"", - appDir.getAbsolutePath()); - ctxt.setReplaceWelcomeFiles(true); - ctxt.addWelcomeFile(""index.jsp""); - // Mapping for *.do is defined in web.xml - ctxt.addWelcomeFile(""index.do""); - - // Simulate STRICT_SERVLET_COMPLIANCE - ctxt.setResourceOnlyServlets(""""); - - tomcat.start(); - ByteChunk bc = new ByteChunk(); - int rc = getUrl(""http://localhost:"" + getPort() + - ""/test/welcome-files"", bc, new HashMap>()); - Assert.assertEquals(HttpServletResponse.SC_OK, rc); - Assert.assertTrue(bc.toString().contains(""JSP"")); - - rc = getUrl(""http://localhost:"" + getPort() + - ""/test/welcome-files/sub"", bc, - new HashMap>()); - Assert.assertEquals(HttpServletResponse.SC_NOT_FOUND, rc); - } - - /** - * Prepare a string to search in messages that contain a timestamp, when it - * is known that the timestamp was printed between {@code timeA} and - * {@code timeB}. - */ -" -271,1," protected void stripScopesFromAuthentication(String identityZoneId, HttpServletRequest servletRequest) { - OAuth2Authentication oa = (OAuth2Authentication)SecurityContextHolder.getContext().getAuthentication(); - - Object oaDetails = oa.getDetails(); - - //strip client scopes - OAuth2Request request = oa.getOAuth2Request(); - Collection requestAuthorities = UaaStringUtils.getStringsFromAuthorities(request.getAuthorities()); - Set clientScopes = new HashSet<>(); - Set clientAuthorities = new HashSet<>(); - for (String s : getZoneSwitchingScopes(identityZoneId)) { - String scope = stripPrefix(s, identityZoneId); - if (request.getScope().contains(s)) { - clientScopes.add(scope); - } - if (requestAuthorities.contains(s)) { - clientAuthorities.add(scope); - } - } - request = new OAuth2Request( - request.getRequestParameters(), - request.getClientId(), - UaaStringUtils.getAuthoritiesFromStrings(clientAuthorities), - request.isApproved(), - clientScopes, - request.getResourceIds(), - request.getRedirectUri(), - request.getResponseTypes(), - request.getExtensions() - ); - - - UaaAuthentication userAuthentication = (UaaAuthentication)oa.getUserAuthentication(); - if (userAuthentication!=null) { - userAuthentication = new UaaAuthentication( - userAuthentication.getPrincipal(), - null, - UaaStringUtils.getAuthoritiesFromStrings(clientScopes), - new UaaAuthenticationDetails(servletRequest), - true); - } - oa = new OAuth2Authentication(request, userAuthentication); - oa.setDetails(oaDetails); - SecurityContextHolder.getContext().setAuthentication(oa); - } - -" -272,1," public void testHandleNoInitialResponseNull() throws Exception - { - final AuthenticationResult result = _negotiator.handleResponse(null); - assertEquals(""Unexpected authentication status"", AuthenticationResult.AuthenticationStatus.CONTINUE, result.getStatus()); - assertArrayEquals(""Unexpected authentication challenge"", new byte[0], result.getChallenge()); - - final AuthenticationResult firstResult = _negotiator.handleResponse(VALID_RESPONSE.getBytes()); - assertEquals(""Unexpected first authentication result"", _expectedResult, firstResult); - } -" -273,1," private int readStored(final byte[] buffer, final int offset, final int length) throws IOException { - - if (current.hasDataDescriptor) { - if (lastStoredEntry == null) { - readStoredEntry(); - } - return lastStoredEntry.read(buffer, offset, length); - } - - final long csize = current.entry.getSize(); - if (current.bytesRead >= csize) { - return -1; - } - - if (buf.position() >= buf.limit()) { - buf.position(0); - final int l = in.read(buf.array()); - if (l == -1) { - return -1; - } - buf.limit(l); - - count(l); - current.bytesReadFromStream += l; - } - - int toRead = Math.min(buf.remaining(), length); - if ((csize - current.bytesRead) < toRead) { - // if it is smaller than toRead then it fits into an int - toRead = (int) (csize - current.bytesRead); - } - buf.get(buffer, offset, toRead); - current.bytesRead += toRead; - return toRead; - } - - /** - * Implementation of read for DEFLATED entries. - */ -" -274,1," private Object readResolve() { - return INSTANCE; - } - -" -275,1," private static ZipOutputStream getZipOutputStream(OutputStream out, Charset charset) { - charset = (null == charset) ? DEFAULT_CHARSET : charset; - return new ZipOutputStream(out, charset); - } - - /** - * 递归压缩文件夹 - * - * @param out 压缩文件存储对象 - * @param srcRootDir 压缩文件夹根目录的子路径 - * @param file 当前递归压缩的文件或目录对象 - * @throws UtilException IO异常 - */ -" -276,1," public boolean isFinished() { - return endChunk; - } -" -277,1," public Object compile(String expression) throws OgnlException { - if (enableExpressionCache) { - Object o = expressions.get(expression); - if (o == null) { - o = Ognl.parseExpression(expression); - expressions.putIfAbsent(expression, o); - } - return o; - } else - return Ognl.parseExpression(expression); - } - - /** - * Copies the properties in the object ""from"" and sets them in the object ""to"" - * using specified type converter, or {@link com.opensymphony.xwork2.conversion.impl.XWorkConverter} if none - * is specified. - * - * @param from the source object - * @param to the target object - * @param context the action context we're running under - * @param exclusions collection of method names to excluded from copying ( can be null) - * @param inclusions collection of method names to included copying (can be null) - * note if exclusions AND inclusions are supplied and not null nothing will get copied. - */ -" -278,1," String hash(String plaintext, String salt, int iterations) throws EncryptionException; - - /** - * Encrypts the provided plaintext and returns a ciphertext string using the - * master secret key and default cipher transformation. - *

- * Compatibility with earlier ESAPI versions: The symmetric encryption - * in ESAPI 2.0 and later is not compatible with the encryption in ESAPI 1.4 - * or earlier. Not only are the interfaces slightly different, but they format - * of the serialized encrypted data is incompatible. Therefore, if you have - * encrypted data with ESAPI 1.4 or earlier, you must first encrypt it and - * then re-encrypt it with ESAPI 2.0. Backward compatibility with ESAPI 1.4 - * was proposed to both the ESAPI Developers and ESAPI Users mailing lists - * and voted down. More details are available in the ESAPI document - * - * Why Is OWASP Changing ESAPI Encryption? - *

- * Why this method is deprecated: Most cryptographers strongly suggest - * that if you are creating crypto functionality for general-purpose use, - * at a minimum you should ensure that it provides authenticity, integrity, - * and confidentiality. This method only provides confidentiality, but not - * authenticity or integrity. Therefore, you are encouraged to use - * one of the other encryption methods referenced below. Because this - * method provides neither authenticity nor integrity, it may be - * removed in some future ESAPI Java release. Note: there are some cases - * where authenticity / integrity are not that important. For instance, consider - * a case where the encrypted data is never out of your application's control. For - * example, if you receive data that your application is encrypting itself and then - * storing the encrypted data in its own database for later use (and no other - * applications can query or update that column of the database), providing - * confidentiality alone might be sufficient. However, if there are cases - * where your application will be sending or receiving already encrypted data - * over an insecure, unauthenticated channel, in such cases authenticity and - * integrity of the encrypted data likely is important and this method should - * be avoided in favor of one of the other two. - * - * @param plaintext - * the plaintext {@code String} to encrypt. Note that if you are encrypting - * general bytes, you should encypt that byte array to a String using - * ""UTF-8"" encoding. - * - * @return - * the encrypted, base64-encoded String representation of 'plaintext' plus - * the random IV used. - * - * @throws EncryptionException - * if the specified encryption algorithm could not be found or another problem exists with - * the encryption of 'plaintext' - * - * @see #encrypt(PlainText) - * @see #encrypt(SecretKey, PlainText) - * - * @deprecated As of 1.4.2; use {@link #encrypt(PlainText)} instead, which - * also ensures message authenticity. This method will be - * completely removed as of the next major release or point - * release (3.0 or 2.1, whichever comes first) as per OWASP - * deprecation policy. - */ -" -279,1," public void handleDialog(ActionRequest req, ActionResponse resp) throws IOException, PortletException { - List lines = new ArrayList(); - req.getPortletSession().setAttribute(""lines"", lines); - - lines.add(""handling dialog""); - StringBuilder txt = new StringBuilder(128); - - String clr = req.getActionParameters().getValue(""color""); - txt.append(""Color: "").append(clr); - lines.add(txt.toString()); - LOGGER.fine(txt.toString()); - - resp.getRenderParameters().setValue(""color"", clr); - - txt.setLength(0); - Part part = null; - try { - part = req.getPart(""file""); - } catch (Throwable t) {} - - if ((part != null) && (part.getSubmittedFileName() != null) && - (part.getSubmittedFileName().length() > 0)) { - txt.append(""Uploaded file name: "").append(part.getSubmittedFileName()); - txt.append("", part name: "").append(part.getName()); - txt.append("", size: "").append(part.getSize()); - txt.append("", content type: "").append(part.getContentType()); - lines.add(txt.toString()); - LOGGER.fine(txt.toString()); - txt.setLength(0); - txt.append(""Headers: ""); - String sep = """"; - for (String hdrname : part.getHeaderNames()) { - txt.append(sep).append(hdrname).append(""="").append(part.getHeaders(hdrname)); - sep = "", ""; - } - lines.add(txt.toString()); - LOGGER.fine(txt.toString()); - - // Store the file in a temporary location in the webapp where it can be served. - // Note that this is, in general, not what you want to do in production, as - // there can be problems serving the resource. Did it this way for a - // quick solution that doesn't require additional Tomcat configuration. - - try { - String path = req.getPortletContext().getRealPath(TMP); - File dir = new File(path); - lines.add(""Temp path: "" + dir.getCanonicalPath()); - if (!dir.exists()) { - lines.add(""Creating directory. Path: "" + dir.getCanonicalPath()); - Files.createDirectories(dir.toPath()); - } - String fn = TMP + part.getSubmittedFileName(); - lines.add(""Temp file: "" + fn); - path = req.getPortletContext().getRealPath(fn); - File img = new File(path); - if (img.exists()) { - lines.add(""deleting existing temp file.""); - img.delete(); - } - InputStream is = part.getInputStream(); - Files.copy(is, img.toPath(), StandardCopyOption.REPLACE_EXISTING); - - resp.getRenderParameters().setValue(""fn"", fn); - resp.getRenderParameters().setValue(""ct"", part.getContentType()); - - } catch (Exception e) { - lines.add(""Exception doing I/O: "" + e.toString()); - } - } else { - lines.add(""file part was null""); - } - - } - - @RenderMethod(portletNames = ""MultipartPortlet"") -" -280,1," protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) - throws ServletException, IOException { - - HttpServletRequest requestToUse = request; - - if (""POST"".equals(request.getMethod()) && request.getAttribute(WebUtils.ERROR_EXCEPTION_ATTRIBUTE) == null) { - String paramValue = request.getParameter(this.methodParam); - if (StringUtils.hasLength(paramValue)) { - requestToUse = new HttpMethodRequestWrapper(request, paramValue); - } - } - - filterChain.doFilter(requestToUse, response); - } - - - /** - * Simple {@link HttpServletRequest} wrapper that returns the supplied method for - * {@link HttpServletRequest#getMethod()}. - */ -" -281,1," private ScimGroupExternalMember getExternalGroupMap(final String groupId, - final String externalGroup, - final String origin) - throws ScimResourceNotFoundException { - try { - ScimGroupExternalMember u = jdbcTemplate.queryForObject(GET_GROUPS_WITH_EXTERNAL_GROUP_MAPPINGS_SQL, - rowMapper, groupId, origin, externalGroup); - return u; - } catch (EmptyResultDataAccessException e) { - throw new ScimResourceNotFoundException(""The mapping between groupId "" + groupId + "" and external group "" - + externalGroup + "" does not exist""); - } - } - -" -282,1," protected void serveResource(HttpServletRequest request, - HttpServletResponse response, - boolean content, - String encoding) - throws IOException, ServletException { - - boolean serveContent = content; - - // Identify the requested resource path - String path = getRelativePath(request); - if (debug > 0) { - if (serveContent) - log(""DefaultServlet.serveResource: Serving resource '"" + - path + ""' headers and data""); - else - log(""DefaultServlet.serveResource: Serving resource '"" + - path + ""' headers only""); - } - - WebResource resource = resources.getResource(path); - - if (!resource.exists()) { - // Check if we're included so we can return the appropriate - // missing resource name in the error - String requestUri = (String) request.getAttribute( - RequestDispatcher.INCLUDE_REQUEST_URI); - if (requestUri == null) { - requestUri = request.getRequestURI(); - } else { - // We're included - // SRV.9.3 says we must throw a FNFE - throw new FileNotFoundException(sm.getString( - ""defaultServlet.missingResource"", requestUri)); - } - - response.sendError(HttpServletResponse.SC_NOT_FOUND, requestUri); - return; - } - - if (!resource.canRead()) { - // Check if we're included so we can return the appropriate - // missing resource name in the error - String requestUri = (String) request.getAttribute( - RequestDispatcher.INCLUDE_REQUEST_URI); - if (requestUri == null) { - requestUri = request.getRequestURI(); - } else { - // We're included - // Spec doesn't say what to do in this case but a FNFE seems - // reasonable - throw new FileNotFoundException(sm.getString( - ""defaultServlet.missingResource"", requestUri)); - } - - response.sendError(HttpServletResponse.SC_FORBIDDEN, requestUri); - return; - } - - // If the resource is not a collection, and the resource path - // ends with ""/"" or ""\"", return NOT FOUND - if (resource.isFile() && (path.endsWith(""/"") || path.endsWith(""\\""))) { - // Check if we're included so we can return the appropriate - // missing resource name in the error - String requestUri = (String) request.getAttribute( - RequestDispatcher.INCLUDE_REQUEST_URI); - if (requestUri == null) { - requestUri = request.getRequestURI(); - } - response.sendError(HttpServletResponse.SC_NOT_FOUND, requestUri); - return; - } - - boolean isError = response.getStatus() >= HttpServletResponse.SC_BAD_REQUEST; - - boolean included = false; - // Check if the conditions specified in the optional If headers are - // satisfied. - if (resource.isFile()) { - // Checking If headers - included = (request.getAttribute( - RequestDispatcher.INCLUDE_CONTEXT_PATH) != null); - if (!included && !isError && !checkIfHeaders(request, response, resource)) { - return; - } - } - - // Find content type. - String contentType = resource.getMimeType(); - if (contentType == null) { - contentType = getServletContext().getMimeType(resource.getName()); - resource.setMimeType(contentType); - } - - // These need to reflect the original resource, not the potentially - // gzip'd version of the resource so get them now if they are going to - // be needed later - String eTag = null; - String lastModifiedHttp = null; - if (resource.isFile() && !isError) { - eTag = resource.getETag(); - lastModifiedHttp = resource.getLastModifiedHttp(); - } - - - // Serve a gzipped version of the file if present - boolean usingGzippedVersion = false; - if (gzip && !included && resource.isFile() && !path.endsWith("".gz"")) { - WebResource gzipResource = resources.getResource(path + "".gz""); - if (gzipResource.exists() && gzipResource.isFile()) { - Collection varyHeaders = response.getHeaders(""Vary""); - boolean addRequired = true; - for (String varyHeader : varyHeaders) { - if (""*"".equals(varyHeader) || - ""accept-encoding"".equalsIgnoreCase(varyHeader)) { - addRequired = false; - break; - } - } - if (addRequired) { - response.addHeader(""Vary"", ""accept-encoding""); - } - if (checkIfGzip(request)) { - response.addHeader(""Content-Encoding"", ""gzip""); - resource = gzipResource; - usingGzippedVersion = true; - } - } - } - - ArrayList ranges = null; - long contentLength = -1L; - - if (resource.isDirectory()) { - // Skip directory listings if we have been configured to - // suppress them - if (!listings) { - response.sendError(HttpServletResponse.SC_NOT_FOUND, - request.getRequestURI()); - return; - } - contentType = ""text/html;charset=UTF-8""; - } else { - if (!isError) { - if (useAcceptRanges) { - // Accept ranges header - response.setHeader(""Accept-Ranges"", ""bytes""); - } - - // Parse range specifier - ranges = parseRange(request, response, resource); - - // ETag header - response.setHeader(""ETag"", eTag); - - // Last-Modified header - response.setHeader(""Last-Modified"", lastModifiedHttp); - } - - // Get content length - contentLength = resource.getContentLength(); - // Special case for zero length files, which would cause a - // (silent) ISE when setting the output buffer size - if (contentLength == 0L) { - serveContent = false; - } - } - - ServletOutputStream ostream = null; - PrintWriter writer = null; - - if (serveContent) { - // Trying to retrieve the servlet output stream - try { - ostream = response.getOutputStream(); - } catch (IllegalStateException e) { - // If it fails, we try to get a Writer instead if we're - // trying to serve a text file - if (!usingGzippedVersion && - ((contentType == null) || - (contentType.startsWith(""text"")) || - (contentType.endsWith(""xml"")) || - (contentType.contains(""/javascript""))) - ) { - writer = response.getWriter(); - // Cannot reliably serve partial content with a Writer - ranges = FULL; - } else { - throw e; - } - } - } - - // Check to see if a Filter, Valve of wrapper has written some content. - // If it has, disable range requests and setting of a content length - // since neither can be done reliably. - ServletResponse r = response; - long contentWritten = 0; - while (r instanceof ServletResponseWrapper) { - r = ((ServletResponseWrapper) r).getResponse(); - } - if (r instanceof ResponseFacade) { - contentWritten = ((ResponseFacade) r).getContentWritten(); - } - if (contentWritten > 0) { - ranges = FULL; - } - - if (resource.isDirectory() || - isError || - ( (ranges == null || ranges.isEmpty()) - && request.getHeader(""Range"") == null ) || - ranges == FULL ) { - - // Set the appropriate output headers - if (contentType != null) { - if (debug > 0) - log(""DefaultServlet.serveFile: contentType='"" + - contentType + ""'""); - response.setContentType(contentType); - } - if (resource.isFile() && contentLength >= 0 && - (!serveContent || ostream != null)) { - if (debug > 0) - log(""DefaultServlet.serveFile: contentLength="" + - contentLength); - // Don't set a content length if something else has already - // written to the response. - if (contentWritten == 0) { - response.setContentLengthLong(contentLength); - } - } - - if (serveContent) { - try { - response.setBufferSize(output); - } catch (IllegalStateException e) { - // Silent catch - } - InputStream renderResult = null; - if (ostream == null) { - // Output via a writer so can't use sendfile or write - // content directly. - if (resource.isDirectory()) { - renderResult = render(getPathPrefix(request), resource); - } else { - renderResult = resource.getInputStream(); - } - copy(resource, renderResult, writer, encoding); - } else { - // Output is via an InputStream - if (resource.isDirectory()) { - renderResult = render(getPathPrefix(request), resource); - } else { - // Output is content of resource - if (!checkSendfile(request, response, resource, - contentLength, null)) { - // sendfile not possible so check if resource - // content is available directly - byte[] resourceBody = resource.getContent(); - if (resourceBody == null) { - // Resource content not available, use - // inputstream - renderResult = resource.getInputStream(); - } else { - // Use the resource content directly - ostream.write(resourceBody); - } - } - } - // If a stream was configured, it needs to be copied to - // the output (this method closes the stream) - if (renderResult != null) { - copy(resource, renderResult, ostream); - } - } - } - - } else { - - if ((ranges == null) || (ranges.isEmpty())) - return; - - // Partial content response. - - response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); - - if (ranges.size() == 1) { - - Range range = ranges.get(0); - response.addHeader(""Content-Range"", ""bytes "" - + range.start - + ""-"" + range.end + ""/"" - + range.length); - long length = range.end - range.start + 1; - response.setContentLengthLong(length); - - if (contentType != null) { - if (debug > 0) - log(""DefaultServlet.serveFile: contentType='"" + - contentType + ""'""); - response.setContentType(contentType); - } - - if (serveContent) { - try { - response.setBufferSize(output); - } catch (IllegalStateException e) { - // Silent catch - } - if (ostream != null) { - if (!checkSendfile(request, response, resource, - range.end - range.start + 1, range)) - copy(resource, ostream, range); - } else { - // we should not get here - throw new IllegalStateException(); - } - } - } else { - response.setContentType(""multipart/byteranges; boundary="" - + mimeSeparation); - if (serveContent) { - try { - response.setBufferSize(output); - } catch (IllegalStateException e) { - // Silent catch - } - if (ostream != null) { - copy(resource, ostream, ranges.iterator(), contentType); - } else { - // we should not get here - throw new IllegalStateException(); - } - } - } - } - } - - - /** - * Parse the content-range header. - * - * @param request The servlet request we a)re processing - * @param response The servlet response we are creating - * @return Range - */ -" -283,1," private void findCloneMethod() { - try { - iCloneMethod = iPrototype.getClass().getMethod(""clone"", (Class[]) null); - } catch (final NoSuchMethodException ex) { - throw new IllegalArgumentException(""PrototypeCloneFactory: The clone method must exist and be public ""); - } - } - - /** - * Creates an object by calling the clone method. - * - * @return the new object - */ - @SuppressWarnings(""unchecked"") -" -284,1," public boolean isSequenceType() { return false; } - - - /* Traverseproc implementation */ - @Override -" -285,1," public void setDynamicAttribute(String uri, String localName, Object value) throws JspException { - if (ComponentUtils.altSyntax(getStack()) && ComponentUtils.isExpression(value)) { - dynamicAttributes.put(localName, String.valueOf(ObjectUtils.defaultIfNull(findValue(value.toString()), value))); - } else { - dynamicAttributes.put(localName, value); - } - } - -" -286,1," protected void onModified() throws IOException { - super.onModified(); - Jenkins.getInstance().trimLabels(); - } - } - - /** - * Set of installed cluster nodes. - *

- * We use this field with copy-on-write semantics. - * This field has mutable list (to keep the serialization look clean), - * but it shall never be modified. Only new completely populated slave - * list can be set here. - *

- * The field name should be really {@code nodes}, but again the backward compatibility - * prevents us from renaming. - */ - protected volatile NodeList slaves; - - /** - * Quiet period. - * - * This is {@link Integer} so that we can initialize it to '5' for upgrading users. - */ - /*package*/ Integer quietPeriod; - - /** - * Global default for {@link AbstractProject#getScmCheckoutRetryCount()} - */ - /*package*/ int scmCheckoutRetryCount; - - /** - * {@link View}s. - */ - private final CopyOnWriteArrayList views = new CopyOnWriteArrayList(); - - /** - * Name of the primary view. - *

- * Start with null, so that we can upgrade pre-1.269 data well. - * @since 1.269 - */ - private volatile String primaryView; - - private transient final ViewGroupMixIn viewGroupMixIn = new ViewGroupMixIn(this) { - protected List views() { return views; } - protected String primaryView() { return primaryView; } - protected void primaryView(String name) { primaryView=name; } - }; - - - private transient final FingerprintMap fingerprintMap = new FingerprintMap(); - - /** - * Loaded plugins. - */ - public transient final PluginManager pluginManager; - - public transient volatile TcpSlaveAgentListener tcpSlaveAgentListener; - - private transient UDPBroadcastThread udpBroadcastThread; - - private transient DNSMultiCast dnsMultiCast; - - /** - * List of registered {@link SCMListener}s. - */ - private transient final CopyOnWriteList scmListeners = new CopyOnWriteList(); - - /** - * TCP slave agent port. - * 0 for random, -1 to disable. - */ - private int slaveAgentPort =0; - - /** - * Whitespace-separated labels assigned to the master as a {@link Node}. - */ - private String label=""""; - - /** - * {@link hudson.security.csrf.CrumbIssuer} - */ - private volatile CrumbIssuer crumbIssuer; - - /** - * All labels known to Jenkins. This allows us to reuse the same label instances - * as much as possible, even though that's not a strict requirement. - */ - private transient final ConcurrentHashMap labels = new ConcurrentHashMap(); - - /** - * Load statistics of the entire system. - * - * This includes every executor and every job in the system. - */ - @Exported - public transient final OverallLoadStatistics overallLoad = new OverallLoadStatistics(); - - /** - * Load statistics of the free roaming jobs and slaves. - * - * This includes all executors on {@link Mode#NORMAL} nodes and jobs that do not have any assigned nodes. - * - * @since 1.467 - */ - @Exported - public transient final LoadStatistics unlabeledLoad = new UnlabeledLoadStatistics(); - - /** - * {@link NodeProvisioner} that reacts to {@link #unlabeledLoad}. - * @since 1.467 - */ - public transient final NodeProvisioner unlabeledNodeProvisioner = new NodeProvisioner(null,unlabeledLoad); - - /** - * @deprecated as of 1.467 - * Use {@link #unlabeledNodeProvisioner}. - * This was broken because it was tracking all the executors in the system, but it was only tracking - * free-roaming jobs in the queue. So {@link Cloud} fails to launch nodes when you have some exclusive - * slaves and free-roaming jobs in the queue. - */ - @Restricted(NoExternalUse.class) - public transient final NodeProvisioner overallNodeProvisioner = unlabeledNodeProvisioner; - - - public transient final ServletContext servletContext; - - /** - * Transient action list. Useful for adding navigation items to the navigation bar - * on the left. - */ - private transient final List actions = new CopyOnWriteArrayList(); - - /** - * List of master node properties - */ - private DescribableList,NodePropertyDescriptor> nodeProperties = new DescribableList,NodePropertyDescriptor>(this); - - /** - * List of global properties - */ - private DescribableList,NodePropertyDescriptor> globalNodeProperties = new DescribableList,NodePropertyDescriptor>(this); - - /** - * {@link AdministrativeMonitor}s installed on this system. - * - * @see AdministrativeMonitor - */ - public transient final List administrativeMonitors = getExtensionList(AdministrativeMonitor.class); - - /** - * Widgets on Hudson. - */ - private transient final List widgets = getExtensionList(Widget.class); - - /** - * {@link AdjunctManager} - */ - private transient final AdjunctManager adjuncts; - - /** - * Code that handles {@link ItemGroup} work. - */ - private transient final ItemGroupMixIn itemGroupMixIn = new ItemGroupMixIn(this,this) { - @Override - protected void add(TopLevelItem item) { - items.put(item.getName(),item); - } - - @Override - protected File getRootDirFor(String name) { - return Jenkins.this.getRootDirFor(name); - } - - /** - * Send the browser to the config page. - * use View to trim view/{default-view} from URL if possible - */ - @Override - protected String redirectAfterCreateItem(StaplerRequest req, TopLevelItem result) throws IOException { - String redirect = result.getUrl()+""configure""; - List ancestors = req.getAncestors(); - for (int i = ancestors.size() - 1; i >= 0; i--) { - Object o = ancestors.get(i).getObject(); - if (o instanceof View) { - redirect = req.getContextPath() + '/' + ((View)o).getUrl() + redirect; - break; - } - } - return redirect; - } - }; - - - /** - * Hook for a test harness to intercept Jenkins.getInstance() - * - * Do not use in the production code as the signature may change. - */ - public interface JenkinsHolder { - Jenkins getInstance(); - } - - static JenkinsHolder HOLDER = new JenkinsHolder() { - public Jenkins getInstance() { - return theInstance; - } - }; - - @CLIResolver - public static Jenkins getInstance() { - return HOLDER.getInstance(); - } - - /** - * Secret key generated once and used for a long time, beyond - * container start/stop. Persisted outside config.xml to avoid - * accidental exposure. - */ - private transient final String secretKey; - - private transient final UpdateCenter updateCenter = new UpdateCenter(); - - /** - * True if the user opted out from the statistics tracking. We'll never send anything if this is true. - */ - private Boolean noUsageStatistics; - - /** - * HTTP proxy configuration. - */ - public transient volatile ProxyConfiguration proxy; - - /** - * Bound to ""/log"". - */ - private transient final LogRecorderManager log = new LogRecorderManager(); - - protected Jenkins(File root, ServletContext context) throws IOException, InterruptedException, ReactorException { - this(root,context,null); - } - - /** - * @param pluginManager - * If non-null, use existing plugin manager. create a new one. - */ - @edu.umd.cs.findbugs.annotations.SuppressWarnings({ - ""SC_START_IN_CTOR"", // bug in FindBugs. It flags UDPBroadcastThread.start() call but that's for another class - ""ST_WRITE_TO_STATIC_FROM_INSTANCE_METHOD"" // Trigger.timer - }) - protected Jenkins(File root, ServletContext context, PluginManager pluginManager) throws IOException, InterruptedException, ReactorException { - long start = System.currentTimeMillis(); - - // As Jenkins is starting, grant this process full control - ACL.impersonate(ACL.SYSTEM); - try { - this.root = root; - this.servletContext = context; - computeVersion(context); - if(theInstance!=null) - throw new IllegalStateException(""second instance""); - theInstance = this; - - if (!new File(root,""jobs"").exists()) { - // if this is a fresh install, use more modern default layout that's consistent with slaves - workspaceDir = ""${JENKINS_HOME}/workspace/${ITEM_FULLNAME}""; - } - - // doing this early allows InitStrategy to set environment upfront - final InitStrategy is = InitStrategy.get(Thread.currentThread().getContextClassLoader()); - - Trigger.timer = new Timer(""Jenkins cron thread""); - queue = new Queue(LoadBalancer.CONSISTENT_HASH); - - try { - dependencyGraph = DependencyGraph.EMPTY; - } catch (InternalError e) { - if(e.getMessage().contains(""window server"")) { - throw new Error(""Looks like the server runs without X. Please specify -Djava.awt.headless=true as JVM option"",e); - } - throw e; - } - - // get or create the secret - TextFile secretFile = new TextFile(new File(getRootDir(),""secret.key"")); - if(secretFile.exists()) { - secretKey = secretFile.readTrim(); - } else { - SecureRandom sr = new SecureRandom(); - byte[] random = new byte[32]; - sr.nextBytes(random); - secretKey = Util.toHexString(random); - secretFile.write(secretKey); - } - - try { - proxy = ProxyConfiguration.load(); - } catch (IOException e) { - LOGGER.log(SEVERE, ""Failed to load proxy configuration"", e); - } - - if (pluginManager==null) - pluginManager = new LocalPluginManager(this); - this.pluginManager = pluginManager; - // JSON binding needs to be able to see all the classes from all the plugins - WebApp.get(servletContext).setClassLoader(pluginManager.uberClassLoader); - - adjuncts = new AdjunctManager(servletContext, pluginManager.uberClassLoader,""adjuncts/""+SESSION_HASH); - - // initialization consists of ... - executeReactor( is, - pluginManager.initTasks(is), // loading and preparing plugins - loadTasks(), // load jobs - InitMilestone.ordering() // forced ordering among key milestones - ); - - if(KILL_AFTER_LOAD) - System.exit(0); - - if(slaveAgentPort!=-1) { - try { - tcpSlaveAgentListener = new TcpSlaveAgentListener(slaveAgentPort); - } catch (BindException e) { - new AdministrativeError(getClass().getName()+"".tcpBind"", - ""Failed to listen to incoming slave connection"", - ""Failed to listen to incoming slave connection. Change the port number to solve the problem."",e); - } - } else - tcpSlaveAgentListener = null; - - try { - udpBroadcastThread = new UDPBroadcastThread(this); - udpBroadcastThread.start(); - } catch (IOException e) { - LOGGER.log(Level.WARNING, ""Failed to broadcast over UDP"",e); - } - dnsMultiCast = new DNSMultiCast(this); - - Timer timer = Trigger.timer; - if (timer != null) { - timer.scheduleAtFixedRate(new SafeTimerTask() { - @Override - protected void doRun() throws Exception { - trimLabels(); - } - }, TimeUnit2.MINUTES.toMillis(5), TimeUnit2.MINUTES.toMillis(5)); - } - - updateComputerList(); - - {// master is online now - Computer c = toComputer(); - if(c!=null) - for (ComputerListener cl : ComputerListener.all()) - cl.onOnline(c,StreamTaskListener.fromStdout()); - } - - for (ItemListener l : ItemListener.all()) { - long itemListenerStart = System.currentTimeMillis(); - l.onLoaded(); - if (LOG_STARTUP_PERFORMANCE) - LOGGER.info(String.format(""Took %dms for item listener %s startup"", - System.currentTimeMillis()-itemListenerStart,l.getClass().getName())); - } - - if (LOG_STARTUP_PERFORMANCE) - LOGGER.info(String.format(""Took %dms for complete Jenkins startup"", - System.currentTimeMillis()-start)); - } finally { - SecurityContextHolder.clearContext(); - } - } - - /** - * Executes a reactor. - * - * @param is - * If non-null, this can be consulted for ignoring some tasks. Only used during the initialization of Hudson. - */ - private void executeReactor(final InitStrategy is, TaskBuilder... builders) throws IOException, InterruptedException, ReactorException { - Reactor reactor = new Reactor(builders) { - /** - * Sets the thread name to the task for better diagnostics. - */ - @Override - protected void runTask(Task task) throws Exception { - if (is!=null && is.skipInitTask(task)) return; - - ACL.impersonate(ACL.SYSTEM); // full access in the initialization thread - String taskName = task.getDisplayName(); - - Thread t = Thread.currentThread(); - String name = t.getName(); - if (taskName !=null) - t.setName(taskName); - try { - long start = System.currentTimeMillis(); - super.runTask(task); - if(LOG_STARTUP_PERFORMANCE) - LOGGER.info(String.format(""Took %dms for %s by %s"", - System.currentTimeMillis()-start, taskName, name)); - } finally { - t.setName(name); - SecurityContextHolder.clearContext(); - } - } - }; - - new InitReactorRunner() { - @Override - protected void onInitMilestoneAttained(InitMilestone milestone) { - initLevel = milestone; - } - }.run(reactor); - } - - - public TcpSlaveAgentListener getTcpSlaveAgentListener() { - return tcpSlaveAgentListener; - } - - /** - * Makes {@link AdjunctManager} URL-bound. - * The dummy parameter allows us to use different URLs for the same adjunct, - * for proper cache handling. - */ - public AdjunctManager getAdjuncts(String dummy) { - return adjuncts; - } - - @Exported - public int getSlaveAgentPort() { - return slaveAgentPort; - } - - /** - * @param port - * 0 to indicate random available TCP port. -1 to disable this service. - */ - public void setSlaveAgentPort(int port) throws IOException { - this.slaveAgentPort = port; - - // relaunch the agent - if(tcpSlaveAgentListener==null) { - if(slaveAgentPort!=-1) - tcpSlaveAgentListener = new TcpSlaveAgentListener(slaveAgentPort); - } else { - if(tcpSlaveAgentListener.configuredPort!=slaveAgentPort) { - tcpSlaveAgentListener.shutdown(); - tcpSlaveAgentListener = null; - if(slaveAgentPort!=-1) - tcpSlaveAgentListener = new TcpSlaveAgentListener(slaveAgentPort); - } - } - } - - public void setNodeName(String name) { - throw new UnsupportedOperationException(); // not allowed - } - - public String getNodeDescription() { - return Messages.Hudson_NodeDescription(); - } - - @Exported - public String getDescription() { - return systemMessage; - } - - public PluginManager getPluginManager() { - return pluginManager; - } - - public UpdateCenter getUpdateCenter() { - return updateCenter; - } - - public boolean isUsageStatisticsCollected() { - return noUsageStatistics==null || !noUsageStatistics; - } - - public void setNoUsageStatistics(Boolean noUsageStatistics) throws IOException { - this.noUsageStatistics = noUsageStatistics; - save(); - } - - public View.People getPeople() { - return new View.People(this); - } - - /** - * @since 1.484 - */ - public View.AsynchPeople getAsynchPeople() { - return new View.AsynchPeople(this); - } - - /** - * Does this {@link View} has any associated user information recorded? - */ - public boolean hasPeople() { - return View.People.isApplicable(items.values()); - } - - public Api getApi() { - return new Api(this); - } - - /** - * Returns a secret key that survives across container start/stop. - *

- * This value is useful for implementing some of the security features. - * - * @deprecated - * Due to the past security advisory, this value should not be used any more to protect sensitive information. - * See {@link ConfidentialStore} and {@link ConfidentialKey} for how to store secrets. - */ - public String getSecretKey() { - return secretKey; - } - - /** - * Gets {@linkplain #getSecretKey() the secret key} as a key for AES-128. - * @since 1.308 - * @deprecated - * See {@link #getSecretKey()}. - */ - public SecretKey getSecretKeyAsAES128() { - return Util.toAes128Key(secretKey); - } - - /** - * Returns the unique identifier of this Jenkins that has been historically used to identify - * this Jenkins to the outside world. - * - *

- * This form of identifier is weak in that it can be impersonated by others. See - * https://wiki.jenkins-ci.org/display/JENKINS/Instance+Identity for more modern form of instance ID - * that can be challenged and verified. - * - * @since 1.498 - */ - @SuppressWarnings(""deprecation"") - public String getLegacyInstanceId() { - return Util.getDigestOf(getSecretKey()); - } - - /** - * Gets the SCM descriptor by name. Primarily used for making them web-visible. - */ - public Descriptor getScm(String shortClassName) { - return findDescriptor(shortClassName,SCM.all()); - } - - /** - * Gets the repository browser descriptor by name. Primarily used for making them web-visible. - */ - public Descriptor> getRepositoryBrowser(String shortClassName) { - return findDescriptor(shortClassName,RepositoryBrowser.all()); - } - - /** - * Gets the builder descriptor by name. Primarily used for making them web-visible. - */ - public Descriptor getBuilder(String shortClassName) { - return findDescriptor(shortClassName, Builder.all()); - } - - /** - * Gets the build wrapper descriptor by name. Primarily used for making them web-visible. - */ - public Descriptor getBuildWrapper(String shortClassName) { - return findDescriptor(shortClassName, BuildWrapper.all()); - } - - /** - * Gets the publisher descriptor by name. Primarily used for making them web-visible. - */ - public Descriptor getPublisher(String shortClassName) { - return findDescriptor(shortClassName, Publisher.all()); - } - - /** - * Gets the trigger descriptor by name. Primarily used for making them web-visible. - */ - public TriggerDescriptor getTrigger(String shortClassName) { - return (TriggerDescriptor) findDescriptor(shortClassName, Trigger.all()); - } - - /** - * Gets the retention strategy descriptor by name. Primarily used for making them web-visible. - */ - public Descriptor> getRetentionStrategy(String shortClassName) { - return findDescriptor(shortClassName, RetentionStrategy.all()); - } - - /** - * Gets the {@link JobPropertyDescriptor} by name. Primarily used for making them web-visible. - */ - public JobPropertyDescriptor getJobProperty(String shortClassName) { - // combining these two lines triggers javac bug. See issue #610. - Descriptor d = findDescriptor(shortClassName, JobPropertyDescriptor.all()); - return (JobPropertyDescriptor) d; - } - - /** - * @deprecated - * UI method. Not meant to be used programatically. - */ - public ComputerSet getComputer() { - return new ComputerSet(); - } - - /** - * Exposes {@link Descriptor} by its name to URL. - * - * After doing all the {@code getXXX(shortClassName)} methods, I finally realized that - * this just doesn't scale. - * - * @param id - * Either {@link Descriptor#getId()} (recommended) or the short name of a {@link Describable} subtype (for compatibility) - * @throws IllegalArgumentException if a short name was passed which matches multiple IDs (fail fast) - */ - @SuppressWarnings({""unchecked"", ""rawtypes""}) // too late to fix - public Descriptor getDescriptor(String id) { - // legacy descriptors that are reigstered manually doesn't show up in getExtensionList, so check them explicitly. - Iterable descriptors = Iterators.sequence(getExtensionList(Descriptor.class), DescriptorExtensionList.listLegacyInstances()); - for (Descriptor d : descriptors) { - if (d.getId().equals(id)) { - return d; - } - } - Descriptor candidate = null; - for (Descriptor d : descriptors) { - String name = d.getId(); - if (name.substring(name.lastIndexOf('.') + 1).equals(id)) { - if (candidate == null) { - candidate = d; - } else { - throw new IllegalArgumentException(id + "" is ambiguous; matches both "" + name + "" and "" + candidate.getId()); - } - } - } - return candidate; - } - - /** - * Alias for {@link #getDescriptor(String)}. - */ - public Descriptor getDescriptorByName(String id) { - return getDescriptor(id); - } - - /** - * Gets the {@link Descriptor} that corresponds to the given {@link Describable} type. - *

- * If you have an instance of {@code type} and call {@link Describable#getDescriptor()}, - * you'll get the same instance that this method returns. - */ - public Descriptor getDescriptor(Class type) { - for( Descriptor d : getExtensionList(Descriptor.class) ) - if(d.clazz==type) - return d; - return null; - } - - /** - * Works just like {@link #getDescriptor(Class)} but don't take no for an answer. - * - * @throws AssertionError - * If the descriptor is missing. - * @since 1.326 - */ - public Descriptor getDescriptorOrDie(Class type) { - Descriptor d = getDescriptor(type); - if (d==null) - throw new AssertionError(type+"" is missing its descriptor""); - return d; - } - - /** - * Gets the {@link Descriptor} instance in the current Hudson by its type. - */ - public T getDescriptorByType(Class type) { - for( Descriptor d : getExtensionList(Descriptor.class) ) - if(d.getClass()==type) - return type.cast(d); - return null; - } - - /** - * Gets the {@link SecurityRealm} descriptors by name. Primarily used for making them web-visible. - */ - public Descriptor getSecurityRealms(String shortClassName) { - return findDescriptor(shortClassName,SecurityRealm.all()); - } - - /** - * Finds a descriptor that has the specified name. - */ - private > - Descriptor findDescriptor(String shortClassName, Collection> descriptors) { - String name = '.'+shortClassName; - for (Descriptor d : descriptors) { - if(d.clazz.getName().endsWith(name)) - return d; - } - return null; - } - - protected void updateComputerList() throws IOException { - updateComputerList(AUTOMATIC_SLAVE_LAUNCH); - } - - /** - * Gets all the installed {@link SCMListener}s. - */ - public CopyOnWriteList getSCMListeners() { - return scmListeners; - } - - /** - * Gets the plugin object from its short name. - * - *

- * This allows URL hudson/plugin/ID to be served by the views - * of the plugin class. - */ - public Plugin getPlugin(String shortName) { - PluginWrapper p = pluginManager.getPlugin(shortName); - if(p==null) return null; - return p.getPlugin(); - } - - /** - * Gets the plugin object from its class. - * - *

- * This allows easy storage of plugin information in the plugin singleton without - * every plugin reimplementing the singleton pattern. - * - * @param clazz The plugin class (beware class-loader fun, this will probably only work - * from within the jpi that defines the plugin class, it may or may not work in other cases) - * - * @return The plugin instance. - */ - @SuppressWarnings(""unchecked"") - public

P getPlugin(Class

clazz) { - PluginWrapper p = pluginManager.getPlugin(clazz); - if(p==null) return null; - return (P) p.getPlugin(); - } - - /** - * Gets the plugin objects from their super-class. - * - * @param clazz The plugin class (beware class-loader fun) - * - * @return The plugin instances. - */ - public

List

getPlugins(Class

clazz) { - List

result = new ArrayList

(); - for (PluginWrapper w: pluginManager.getPlugins(clazz)) { - result.add((P)w.getPlugin()); - } - return Collections.unmodifiableList(result); - } - - /** - * Synonym for {@link #getDescription}. - */ - public String getSystemMessage() { - return systemMessage; - } - - /** - * Gets the markup formatter used in the system. - * - * @return - * never null. - * @since 1.391 - */ - public MarkupFormatter getMarkupFormatter() { - return markupFormatter!=null ? markupFormatter : RawHtmlMarkupFormatter.INSTANCE; - } - - /** - * Sets the markup formatter used in the system globally. - * - * @since 1.391 - */ - public void setMarkupFormatter(MarkupFormatter f) { - this.markupFormatter = f; - } - - /** - * Sets the system message. - */ - public void setSystemMessage(String message) throws IOException { - this.systemMessage = message; - save(); - } - - public FederatedLoginService getFederatedLoginService(String name) { - for (FederatedLoginService fls : FederatedLoginService.all()) { - if (fls.getUrlName().equals(name)) - return fls; - } - return null; - } - - public List getFederatedLoginServices() { - return FederatedLoginService.all(); - } - - public Launcher createLauncher(TaskListener listener) { - return new LocalLauncher(listener).decorateFor(this); - } - - - public String getFullName() { - return """"; - } - - public String getFullDisplayName() { - return """"; - } - - /** - * Returns the transient {@link Action}s associated with the top page. - * - *

- * Adding {@link Action} is primarily useful for plugins to contribute - * an item to the navigation bar of the top page. See existing {@link Action} - * implementation for it affects the GUI. - * - *

- * To register an {@link Action}, implement {@link RootAction} extension point, or write code like - * {@code Hudson.getInstance().getActions().add(...)}. - * - * @return - * Live list where the changes can be made. Can be empty but never null. - * @since 1.172 - */ - public List getActions() { - return actions; - } - - /** - * Gets just the immediate children of {@link Jenkins}. - * - * @see #getAllItems(Class) - */ - @Exported(name=""jobs"") - public List getItems() { - if (authorizationStrategy instanceof AuthorizationStrategy.Unsecured || - authorizationStrategy instanceof FullControlOnceLoggedInAuthorizationStrategy) { - return new ArrayList(items.values()); - } - - List viewableItems = new ArrayList(); - for (TopLevelItem item : items.values()) { - if (item.hasPermission(Item.READ)) - viewableItems.add(item); - } - - return viewableItems; - } - - /** - * Returns the read-only view of all the {@link TopLevelItem}s keyed by their names. - *

- * This method is efficient, as it doesn't involve any copying. - * - * @since 1.296 - */ - public Map getItemMap() { - return Collections.unmodifiableMap(items); - } - - /** - * Gets just the immediate children of {@link Jenkins} but of the given type. - */ - public List getItems(Class type) { - List r = new ArrayList(); - for (TopLevelItem i : getItems()) - if (type.isInstance(i)) - r.add(type.cast(i)); - return r; - } - - /** - * Gets all the {@link Item}s recursively in the {@link ItemGroup} tree - * and filter them by the given type. - */ - public List getAllItems(Class type) { - List r = new ArrayList(); - - Stack q = new Stack(); - q.push(this); - - while(!q.isEmpty()) { - ItemGroup parent = q.pop(); - for (Item i : parent.getItems()) { - if(type.isInstance(i)) { - if (i.hasPermission(Item.READ)) - r.add(type.cast(i)); - } - if(i instanceof ItemGroup) - q.push((ItemGroup)i); - } - } - - return r; - } - - /** - * Gets all the items recursively. - * - * @since 1.402 - */ - public List getAllItems() { - return getAllItems(Item.class); - } - - /** - * Gets a list of simple top-level projects. - * @deprecated This method will ignore Maven and matrix projects, as well as projects inside containers such as folders. - * You may prefer to call {@link #getAllItems(Class)} on {@link AbstractProject}, - * perhaps also using {@link Util#createSubList} to consider only {@link TopLevelItem}s. - * (That will also consider the caller's permissions.) - * If you really want to get just {@link Project}s at top level, ignoring permissions, - * you can filter the values from {@link #getItemMap} using {@link Util#createSubList}. - */ - @Deprecated - public List getProjects() { - return Util.createSubList(items.values(),Project.class); - } - - /** - * Gets the names of all the {@link Job}s. - */ - public Collection getJobNames() { - List names = new ArrayList(); - for (Job j : getAllItems(Job.class)) - names.add(j.getFullName()); - return names; - } - - public List getViewActions() { - return getActions(); - } - - /** - * Gets the names of all the {@link TopLevelItem}s. - */ - public Collection getTopLevelItemNames() { - List names = new ArrayList(); - for (TopLevelItem j : items.values()) - names.add(j.getName()); - return names; - } - - public View getView(String name) { - return viewGroupMixIn.getView(name); - } - - /** - * Gets the read-only list of all {@link View}s. - */ - @Exported - public Collection getViews() { - return viewGroupMixIn.getViews(); - } - - public void addView(View v) throws IOException { - viewGroupMixIn.addView(v); - } - - public boolean canDelete(View view) { - return viewGroupMixIn.canDelete(view); - } - - public synchronized void deleteView(View view) throws IOException { - viewGroupMixIn.deleteView(view); - } - - public void onViewRenamed(View view, String oldName, String newName) { - viewGroupMixIn.onViewRenamed(view,oldName,newName); - } - - /** - * Returns the primary {@link View} that renders the top-page of Hudson. - */ - @Exported - public View getPrimaryView() { - return viewGroupMixIn.getPrimaryView(); - } - - public void setPrimaryView(View v) { - this.primaryView = v.getViewName(); - } - - public ViewsTabBar getViewsTabBar() { - return viewsTabBar; - } - - public void setViewsTabBar(ViewsTabBar viewsTabBar) { - this.viewsTabBar = viewsTabBar; - } - - public Jenkins getItemGroup() { - return this; - } - - public MyViewsTabBar getMyViewsTabBar() { - return myViewsTabBar; - } - - public void setMyViewsTabBar(MyViewsTabBar myViewsTabBar) { - this.myViewsTabBar = myViewsTabBar; - } - - /** - * Returns true if the current running Hudson is upgraded from a version earlier than the specified version. - * - *

- * This method continues to return true until the system configuration is saved, at which point - * {@link #version} will be overwritten and Hudson forgets the upgrade history. - * - *

- * To handle SNAPSHOTS correctly, pass in ""1.N.*"" to test if it's upgrading from the version - * equal or younger than N. So say if you implement a feature in 1.301 and you want to check - * if the installation upgraded from pre-1.301, pass in ""1.300.*"" - * - * @since 1.301 - */ - public boolean isUpgradedFromBefore(VersionNumber v) { - try { - return new VersionNumber(version).isOlderThan(v); - } catch (IllegalArgumentException e) { - // fail to parse this version number - return false; - } - } - - /** - * Gets the read-only list of all {@link Computer}s. - */ - public Computer[] getComputers() { - Computer[] r = computers.values().toArray(new Computer[computers.size()]); - Arrays.sort(r,new Comparator() { - final Collator collator = Collator.getInstance(); - public int compare(Computer lhs, Computer rhs) { - if(lhs.getNode()==Jenkins.this) return -1; - if(rhs.getNode()==Jenkins.this) return 1; - return collator.compare(lhs.getDisplayName(), rhs.getDisplayName()); - } - }); - return r; - } - - @CLIResolver - public Computer getComputer(@Argument(required=true,metaVar=""NAME"",usage=""Node name"") String name) { - if(name.equals(""(master)"")) - name = """"; - - for (Computer c : computers.values()) { - if(c.getName().equals(name)) - return c; - } - return null; - } - - /** - * Gets the label that exists on this system by the name. - * - * @return null if name is null. - * @see Label#parseExpression(String) (String) - */ - public Label getLabel(String expr) { - if(expr==null) return null; - while(true) { - Label l = labels.get(expr); - if(l!=null) - return l; - - // non-existent - try { - labels.putIfAbsent(expr,Label.parseExpression(expr)); - } catch (ANTLRException e) { - // laxly accept it as a single label atom for backward compatibility - return getLabelAtom(expr); - } - } - } - - /** - * Returns the label atom of the given name. - * @return non-null iff name is non-null - */ - public @Nullable LabelAtom getLabelAtom(@CheckForNull String name) { - if (name==null) return null; - - while(true) { - Label l = labels.get(name); - if(l!=null) - return (LabelAtom)l; - - // non-existent - LabelAtom la = new LabelAtom(name); - if (labels.putIfAbsent(name, la)==null) - la.load(); - } - } - - /** - * Gets all the active labels in the current system. - */ - public Set

- * This method first tries to use the manually configured value, then - * fall back to {@link StaplerRequest#getRootPath()}. - * It is done in this order so that it can work correctly even in the face - * of a reverse proxy. - * - * @return - * This method returns null if this parameter is not configured by the user. - * The caller must gracefully deal with this situation. - * The returned URL will always have the trailing '/'. - * @since 1.66 - * @see Descriptor#getCheckUrl(String) - * @see #getRootUrlFromRequest() - */ - public String getRootUrl() { - // for compatibility. the actual data is stored in Mailer - String url = JenkinsLocationConfiguration.get().getUrl(); - if(url!=null) { - if (!url.endsWith(""/"")) url += '/'; - return url; - } - - StaplerRequest req = Stapler.getCurrentRequest(); - if(req!=null) - return getRootUrlFromRequest(); - return null; - } - - /** - * Is Jenkins running in HTTPS? - * - * Note that we can't really trust {@link StaplerRequest#isSecure()} because HTTPS might be terminated - * in the reverse proxy. - */ - public boolean isRootUrlSecure() { - String url = getRootUrl(); - return url!=null && url.startsWith(""https""); - } - - /** - * Gets the absolute URL of Hudson top page, such as ""http://localhost/hudson/"". - * - *

- * Unlike {@link #getRootUrl()}, which uses the manually configured value, - * this one uses the current request to reconstruct the URL. The benefit is - * that this is immune to the configuration mistake (users often fail to set the root URL - * correctly, especially when a migration is involved), but the downside - * is that unless you are processing a request, this method doesn't work. - * - * Please note that this will not work in all cases if Jenkins is running behind a - * reverse proxy (e.g. when user has switched off ProxyPreserveHost, which is - * default setup or the actual url uses https) and you should use getRootUrl if - * you want to be sure you reflect user setup. - * See https://wiki.jenkins-ci.org/display/JENKINS/Running+Jenkins+behind+Apache - * - * @since 1.263 - */ - public String getRootUrlFromRequest() { - StaplerRequest req = Stapler.getCurrentRequest(); - StringBuilder buf = new StringBuilder(); - buf.append(req.getScheme()+""://""); - buf.append(req.getServerName()); - if(req.getServerPort()!=80) - buf.append(':').append(req.getServerPort()); - buf.append(req.getContextPath()).append('/'); - return buf.toString(); - } - - public File getRootDir() { - return root; - } - - public FilePath getWorkspaceFor(TopLevelItem item) { - return new FilePath(expandVariablesForDirectory(workspaceDir, item)); - } - - public File getBuildDirFor(Job job) { - return expandVariablesForDirectory(buildsDir, job); - } - - private File expandVariablesForDirectory(String base, Item item) { - return new File(Util.replaceMacro(base, ImmutableMap.of( - ""JENKINS_HOME"", getRootDir().getPath(), - ""ITEM_ROOTDIR"", item.getRootDir().getPath(), - ""ITEM_FULLNAME"", item.getFullName()))); - } - - public String getRawWorkspaceDir() { - return workspaceDir; - } - - public String getRawBuildsDir() { - return buildsDir; - } - - public FilePath getRootPath() { - return new FilePath(getRootDir()); - } - - @Override - public FilePath createPath(String absolutePath) { - return new FilePath((VirtualChannel)null,absolutePath); - } - - public ClockDifference getClockDifference() { - return ClockDifference.ZERO; - } - - /** - * For binding {@link LogRecorderManager} to ""/log"". - * Everything below here is admin-only, so do the check here. - */ - public LogRecorderManager getLog() { - checkPermission(ADMINISTER); - return log; - } - - /** - * A convenience method to check if there's some security - * restrictions in place. - */ - @Exported - public boolean isUseSecurity() { - return securityRealm!=SecurityRealm.NO_AUTHENTICATION || authorizationStrategy!=AuthorizationStrategy.UNSECURED; - } - - public boolean isUseProjectNamingStrategy(){ - return projectNamingStrategy != DefaultProjectNamingStrategy.DEFAULT_NAMING_STRATEGY; - } - - /** - * If true, all the POST requests to Hudson would have to have crumb in it to protect - * Hudson from CSRF vulnerabilities. - */ - @Exported - public boolean isUseCrumbs() { - return crumbIssuer!=null; - } - - /** - * Returns the constant that captures the three basic security modes - * in Hudson. - */ - public SecurityMode getSecurity() { - // fix the variable so that this code works under concurrent modification to securityRealm. - SecurityRealm realm = securityRealm; - - if(realm==SecurityRealm.NO_AUTHENTICATION) - return SecurityMode.UNSECURED; - if(realm instanceof LegacySecurityRealm) - return SecurityMode.LEGACY; - return SecurityMode.SECURED; - } - - /** - * @return - * never null. - */ - public SecurityRealm getSecurityRealm() { - return securityRealm; - } - - public void setSecurityRealm(SecurityRealm securityRealm) { - if(securityRealm==null) - securityRealm= SecurityRealm.NO_AUTHENTICATION; - this.useSecurity = true; - this.securityRealm = securityRealm; - // reset the filters and proxies for the new SecurityRealm - try { - HudsonFilter filter = HudsonFilter.get(servletContext); - if (filter == null) { - // Fix for #3069: This filter is not necessarily initialized before the servlets. - // when HudsonFilter does come back, it'll initialize itself. - LOGGER.fine(""HudsonFilter has not yet been initialized: Can't perform security setup for now""); - } else { - LOGGER.fine(""HudsonFilter has been previously initialized: Setting security up""); - filter.reset(securityRealm); - LOGGER.fine(""Security is now fully set up""); - } - } catch (ServletException e) { - // for binary compatibility, this method cannot throw a checked exception - throw new AcegiSecurityException(""Failed to configure filter"",e) {}; - } - } - - public void setAuthorizationStrategy(AuthorizationStrategy a) { - if (a == null) - a = AuthorizationStrategy.UNSECURED; - useSecurity = true; - authorizationStrategy = a; - } - - public void disableSecurity() { - useSecurity = null; - setSecurityRealm(SecurityRealm.NO_AUTHENTICATION); - authorizationStrategy = AuthorizationStrategy.UNSECURED; - markupFormatter = null; - } - - public void setProjectNamingStrategy(ProjectNamingStrategy ns) { - if(ns == null){ - ns = DefaultProjectNamingStrategy.DEFAULT_NAMING_STRATEGY; - } - projectNamingStrategy = ns; - } - - public Lifecycle getLifecycle() { - return Lifecycle.get(); - } - - /** - * Gets the dependency injection container that hosts all the extension implementations and other - * components in Jenkins. - * - * @since 1.GUICE - */ - public Injector getInjector() { - return lookup(Injector.class); - } - - /** - * Returns {@link ExtensionList} that retains the discovered instances for the given extension type. - * - * @param extensionType - * The base type that represents the extension point. Normally {@link ExtensionPoint} subtype - * but that's not a hard requirement. - * @return - * Can be an empty list but never null. - */ - @SuppressWarnings({""unchecked""}) - public ExtensionList getExtensionList(Class extensionType) { - return extensionLists.get(extensionType); - } - - /** - * Used to bind {@link ExtensionList}s to URLs. - * - * @since 1.349 - */ - public ExtensionList getExtensionList(String extensionType) throws ClassNotFoundException { - return getExtensionList(pluginManager.uberClassLoader.loadClass(extensionType)); - } - - /** - * Returns {@link ExtensionList} that retains the discovered {@link Descriptor} instances for the given - * kind of {@link Describable}. - * - * @return - * Can be an empty list but never null. - */ - @SuppressWarnings({""unchecked""}) - public ,D extends Descriptor> DescriptorExtensionList getDescriptorList(Class type) { - return descriptorLists.get(type); - } - - /** - * Refresh {@link ExtensionList}s by adding all the newly discovered extensions. - * - * Exposed only for {@link PluginManager#dynamicLoad(File)}. - */ - public void refreshExtensions() throws ExtensionRefreshException { - ExtensionList finders = getExtensionList(ExtensionFinder.class); - for (ExtensionFinder ef : finders) { - if (!ef.isRefreshable()) - throw new ExtensionRefreshException(ef+"" doesn't support refresh""); - } - - List fragments = Lists.newArrayList(); - for (ExtensionFinder ef : finders) { - fragments.add(ef.refresh()); - } - ExtensionComponentSet delta = ExtensionComponentSet.union(fragments).filtered(); - - // if we find a new ExtensionFinder, we need it to list up all the extension points as well - List> newFinders = Lists.newArrayList(delta.find(ExtensionFinder.class)); - while (!newFinders.isEmpty()) { - ExtensionFinder f = newFinders.remove(newFinders.size()-1).getInstance(); - - ExtensionComponentSet ecs = ExtensionComponentSet.allOf(f).filtered(); - newFinders.addAll(ecs.find(ExtensionFinder.class)); - delta = ExtensionComponentSet.union(delta, ecs); - } - - for (ExtensionList el : extensionLists.values()) { - el.refresh(delta); - } - for (ExtensionList el : descriptorLists.values()) { - el.refresh(delta); - } - - // TODO: we need some generalization here so that extension points can be notified when a refresh happens? - for (ExtensionComponent ea : delta.find(RootAction.class)) { - Action a = ea.getInstance(); - if (!actions.contains(a)) actions.add(a); - } - } - - /** - * Returns the root {@link ACL}. - * - * @see AuthorizationStrategy#getRootACL() - */ - @Override - public ACL getACL() { - return authorizationStrategy.getRootACL(); - } - - /** - * @return - * never null. - */ - public AuthorizationStrategy getAuthorizationStrategy() { - return authorizationStrategy; - } - - /** - * The strategy used to check the project names. - * @return never null - */ - public ProjectNamingStrategy getProjectNamingStrategy() { - return projectNamingStrategy == null ? ProjectNamingStrategy.DEFAULT_NAMING_STRATEGY : projectNamingStrategy; - } - - /** - * Returns true if Hudson is quieting down. - *

- * No further jobs will be executed unless it - * can be finished while other current pending builds - * are still in progress. - */ - @Exported - public boolean isQuietingDown() { - return isQuietingDown; - } - - /** - * Returns true if the container initiated the termination of the web application. - */ - public boolean isTerminating() { - return terminating; - } - - /** - * Gets the initialization milestone that we've already reached. - * - * @return - * {@link InitMilestone#STARTED} even if the initialization hasn't been started, so that this method - * never returns null. - */ - public InitMilestone getInitLevel() { - return initLevel; - } - - public void setNumExecutors(int n) throws IOException { - this.numExecutors = n; - save(); - } - - - - /** - * {@inheritDoc}. - * - * Note that the look up is case-insensitive. - */ - public TopLevelItem getItem(String name) { - if (name==null) return null; - TopLevelItem item = items.get(name); - if (item==null) - return null; - if (!item.hasPermission(Item.READ)) { - if (item.hasPermission(Item.DISCOVER)) { - throw new AccessDeniedException(""Please login to access job "" + name); - } - return null; - } - return item; - } - - /** - * Gets the item by its path name from the given context - * - *

Path Names

- *

- * If the name starts from '/', like ""/foo/bar/zot"", then it's interpreted as absolute. - * Otherwise, the name should be something like ""foo/bar"" and it's interpreted like - * relative path name in the file system is, against the given context. - * - * @param context - * null is interpreted as {@link Jenkins}. Base 'directory' of the interpretation. - * @since 1.406 - */ - public Item getItem(String pathName, ItemGroup context) { - if (context==null) context = this; - if (pathName==null) return null; - - if (pathName.startsWith(""/"")) // absolute - return getItemByFullName(pathName); - - Object/*Item|ItemGroup*/ ctx = context; - - StringTokenizer tokens = new StringTokenizer(pathName,""/""); - while (tokens.hasMoreTokens()) { - String s = tokens.nextToken(); - if (s.equals("".."")) { - if (ctx instanceof Item) { - ctx = ((Item)ctx).getParent(); - continue; - } - - ctx=null; // can't go up further - break; - } - if (s.equals(""."")) { - continue; - } - - if (ctx instanceof ItemGroup) { - ItemGroup g = (ItemGroup) ctx; - Item i = g.getItem(s); - if (i==null || !i.hasPermission(Item.READ)) { // XXX consider DISCOVER - ctx=null; // can't go up further - break; - } - ctx=i; - } else { - return null; - } - } - - if (ctx instanceof Item) - return (Item)ctx; - - // fall back to the classic interpretation - return getItemByFullName(pathName); - } - - public final Item getItem(String pathName, Item context) { - return getItem(pathName,context!=null?context.getParent():null); - } - - public final T getItem(String pathName, ItemGroup context, Class type) { - Item r = getItem(pathName, context); - if (type.isInstance(r)) - return type.cast(r); - return null; - } - - public final T getItem(String pathName, Item context, Class type) { - return getItem(pathName,context!=null?context.getParent():null,type); - } - - public File getRootDirFor(TopLevelItem child) { - return getRootDirFor(child.getName()); - } - - private File getRootDirFor(String name) { - return new File(new File(getRootDir(),""jobs""), name); - } - - /** - * Gets the {@link Item} object by its full name. - * Full names are like path names, where each name of {@link Item} is - * combined by '/'. - * - * @return - * null if either such {@link Item} doesn't exist under the given full name, - * or it exists but it's no an instance of the given type. - */ - public @CheckForNull T getItemByFullName(String fullName, Class type) { - StringTokenizer tokens = new StringTokenizer(fullName,""/""); - ItemGroup parent = this; - - if(!tokens.hasMoreTokens()) return null; // for example, empty full name. - - while(true) { - Item item = parent.getItem(tokens.nextToken()); - if(!tokens.hasMoreTokens()) { - if(type.isInstance(item)) - return type.cast(item); - else - return null; - } - - if(!(item instanceof ItemGroup)) - return null; // this item can't have any children - - if (!item.hasPermission(Item.READ)) - return null; // XXX consider DISCOVER - - parent = (ItemGroup) item; - } - } - - public @CheckForNull Item getItemByFullName(String fullName) { - return getItemByFullName(fullName,Item.class); - } - - /** - * Gets the user of the given name. - * - * @return the user of the given name, if that person exists or the invoker {@link #hasPermission} on {@link #ADMINISTER}; else null - * @see User#get(String,boolean) - */ - public @CheckForNull User getUser(String name) { - return User.get(name,hasPermission(ADMINISTER)); - } - - public synchronized TopLevelItem createProject( TopLevelItemDescriptor type, String name ) throws IOException { - return createProject(type, name, true); - } - - public synchronized TopLevelItem createProject( TopLevelItemDescriptor type, String name, boolean notify ) throws IOException { - return itemGroupMixIn.createProject(type,name,notify); - } - - /** - * Overwrites the existing item by new one. - * - *

- * This is a short cut for deleting an existing job and adding a new one. - */ - public synchronized void putItem(TopLevelItem item) throws IOException, InterruptedException { - String name = item.getName(); - TopLevelItem old = items.get(name); - if (old ==item) return; // noop - - checkPermission(Item.CREATE); - if (old!=null) - old.delete(); - items.put(name,item); - ItemListener.fireOnCreated(item); - } - - /** - * Creates a new job. - * - *

- * This version infers the descriptor from the type of the top-level item. - * - * @throws IllegalArgumentException - * if the project of the given name already exists. - */ - public synchronized T createProject( Class type, String name ) throws IOException { - return type.cast(createProject((TopLevelItemDescriptor)getDescriptor(type),name)); - } - - /** - * Called by {@link Job#renameTo(String)} to update relevant data structure. - * assumed to be synchronized on Hudson by the caller. - */ - public void onRenamed(TopLevelItem job, String oldName, String newName) throws IOException { - items.remove(oldName); - items.put(newName,job); - - for (View v : views) - v.onJobRenamed(job, oldName, newName); - save(); - } - - /** - * Called in response to {@link Job#doDoDelete(StaplerRequest, StaplerResponse)} - */ - public void onDeleted(TopLevelItem item) throws IOException { - for (ItemListener l : ItemListener.all()) - l.onDeleted(item); - - items.remove(item.getName()); - for (View v : views) - v.onJobRenamed(item, item.getName(), null); - save(); - } - - public FingerprintMap getFingerprintMap() { - return fingerprintMap; - } - - // if no finger print matches, display ""not found page"". - public Object getFingerprint( String md5sum ) throws IOException { - Fingerprint r = fingerprintMap.get(md5sum); - if(r==null) return new NoFingerprintMatch(md5sum); - else return r; - } - - /** - * Gets a {@link Fingerprint} object if it exists. - * Otherwise null. - */ - public Fingerprint _getFingerprint( String md5sum ) throws IOException { - return fingerprintMap.get(md5sum); - } - - /** - * The file we save our configuration. - */ - private XmlFile getConfigFile() { - return new XmlFile(XSTREAM, new File(root,""config.xml"")); - } - - public int getNumExecutors() { - return numExecutors; - } - - public Mode getMode() { - return mode; - } - - public void setMode(Mode m) throws IOException { - this.mode = m; - save(); - } - - public String getLabelString() { - return fixNull(label).trim(); - } - - @Override - public void setLabelString(String label) throws IOException { - this.label = label; - save(); - } - - @Override - public LabelAtom getSelfLabel() { - return getLabelAtom(""master""); - } - - public Computer createComputer() { - return new Hudson.MasterComputer(); - } - - private synchronized TaskBuilder loadTasks() throws IOException { - File projectsDir = new File(root,""jobs""); - if(!projectsDir.getCanonicalFile().isDirectory() && !projectsDir.mkdirs()) { - if(projectsDir.exists()) - throw new IOException(projectsDir+"" is not a directory""); - throw new IOException(""Unable to create ""+projectsDir+""\nPermission issue? Please create this directory manually.""); - } - File[] subdirs = projectsDir.listFiles(new FileFilter() { - public boolean accept(File child) { - return child.isDirectory() && Items.getConfigFile(child).exists(); - } - }); - - TaskGraphBuilder g = new TaskGraphBuilder(); - Handle loadHudson = g.requires(EXTENSIONS_AUGMENTED).attains(JOB_LOADED).add(""Loading global config"", new Executable() { - public void run(Reactor session) throws Exception { - // JENKINS-8043: some slaves (eg. swarm slaves) are not saved into the config file - // and will get overwritten when reloading. Make a backup copy now, and re-add them later - NodeList oldSlaves = slaves; - - XmlFile cfg = getConfigFile(); - if (cfg.exists()) { - // reset some data that may not exist in the disk file - // so that we can take a proper compensation action later. - primaryView = null; - views.clear(); - - // load from disk - cfg.unmarshal(Jenkins.this); - } - - // if we are loading old data that doesn't have this field - if (slaves == null) slaves = new NodeList(); - - clouds.setOwner(Jenkins.this); - items.clear(); - - // JENKINS-8043: re-add the slaves which were not saved into the config file - // and are now missing, but still connected. - if (oldSlaves != null) { - ArrayList newSlaves = new ArrayList(slaves); - for (Node n: oldSlaves) { - if (n instanceof EphemeralNode) { - if(!newSlaves.contains(n)) { - newSlaves.add(n); - } - } - } - setNodes(newSlaves); - } - } - }); - - for (final File subdir : subdirs) { - g.requires(loadHudson).attains(JOB_LOADED).notFatal().add(""Loading job ""+subdir.getName(),new Executable() { - public void run(Reactor session) throws Exception { - TopLevelItem item = (TopLevelItem) Items.load(Jenkins.this, subdir); - items.put(item.getName(), item); - } - }); - } - - g.requires(JOB_LOADED).add(""Finalizing set up"",new Executable() { - public void run(Reactor session) throws Exception { - rebuildDependencyGraph(); - - {// recompute label objects - populates the labels mapping. - for (Node slave : slaves) - // Note that not all labels are visible until the slaves have connected. - slave.getAssignedLabels(); - getAssignedLabels(); - } - - // initialize views by inserting the default view if necessary - // this is both for clean Hudson and for backward compatibility. - if(views.size()==0 || primaryView==null) { - View v = new AllView(Messages.Hudson_ViewName()); - setViewOwner(v); - views.add(0,v); - primaryView = v.getViewName(); - } - - // read in old data that doesn't have the security field set - if(authorizationStrategy==null) { - if(useSecurity==null || !useSecurity) - authorizationStrategy = AuthorizationStrategy.UNSECURED; - else - authorizationStrategy = new LegacyAuthorizationStrategy(); - } - if(securityRealm==null) { - if(useSecurity==null || !useSecurity) - setSecurityRealm(SecurityRealm.NO_AUTHENTICATION); - else - setSecurityRealm(new LegacySecurityRealm()); - } else { - // force the set to proxy - setSecurityRealm(securityRealm); - } - - if(useSecurity!=null && !useSecurity) { - // forced reset to the unsecure mode. - // this works as an escape hatch for people who locked themselves out. - authorizationStrategy = AuthorizationStrategy.UNSECURED; - setSecurityRealm(SecurityRealm.NO_AUTHENTICATION); - } - - // Initialize the filter with the crumb issuer - setCrumbIssuer(crumbIssuer); - - // auto register root actions - for (Action a : getExtensionList(RootAction.class)) - if (!actions.contains(a)) actions.add(a); - } - }); - - return g; - } - - /** - * Save the settings to a file. - */ - public synchronized void save() throws IOException { - if(BulkChange.contains(this)) return; - getConfigFile().write(this); - SaveableListener.fireOnChange(this, getConfigFile()); - } - - - /** - * Called to shut down the system. - */ - @edu.umd.cs.findbugs.annotations.SuppressWarnings(""ST_WRITE_TO_STATIC_FROM_INSTANCE_METHOD"") - public void cleanUp() { - for (ItemListener l : ItemListener.all()) - l.onBeforeShutdown(); - - Set> pending = new HashSet>(); - terminating = true; - for( Computer c : computers.values() ) { - c.interrupt(); - killComputer(c); - pending.add(c.disconnect(null)); - } - if(udpBroadcastThread!=null) - udpBroadcastThread.shutdown(); - if(dnsMultiCast!=null) - dnsMultiCast.close(); - interruptReloadThread(); - Timer timer = Trigger.timer; - if (timer != null) { - timer.cancel(); - } - // TODO: how to wait for the completion of the last job? - Trigger.timer = null; - if(tcpSlaveAgentListener!=null) - tcpSlaveAgentListener.shutdown(); - - if(pluginManager!=null) // be defensive. there could be some ugly timing related issues - pluginManager.stop(); - - if(getRootDir().exists()) - // if we are aborting because we failed to create JENKINS_HOME, - // don't try to save. Issue #536 - getQueue().save(); - - threadPoolForLoad.shutdown(); - for (Future f : pending) - try { - f.get(10, TimeUnit.SECONDS); // if clean up operation didn't complete in time, we fail the test - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - break; // someone wants us to die now. quick! - } catch (ExecutionException e) { - LOGGER.log(Level.WARNING, ""Failed to shut down properly"",e); - } catch (TimeoutException e) { - LOGGER.log(Level.WARNING, ""Failed to shut down properly"",e); - } - - LogFactory.releaseAll(); - - theInstance = null; - } - - public Object getDynamic(String token) { - for (Action a : getActions()) { - String url = a.getUrlName(); - if (url==null) continue; - if (url.equals(token) || url.equals('/' + token)) - return a; - } - for (Action a : getManagementLinks()) - if(a.getUrlName().equals(token)) - return a; - return null; - } - - -// -// -// actions -// -// - /** - * Accepts submission from the configuration page. - */ - public synchronized void doConfigSubmit( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException, FormException { - BulkChange bc = new BulkChange(this); - try { - checkPermission(ADMINISTER); - - JSONObject json = req.getSubmittedForm(); - - workspaceDir = json.getString(""rawWorkspaceDir""); - buildsDir = json.getString(""rawBuildsDir""); - - systemMessage = Util.nullify(req.getParameter(""system_message"")); - - jdks.clear(); - jdks.addAll(req.bindJSONToList(JDK.class,json.get(""jdks""))); - - boolean result = true; - for( Descriptor d : Functions.getSortedDescriptorsForGlobalConfig() ) - result &= configureDescriptor(req,json,d); - - version = VERSION; - - save(); - updateComputerList(); - if(result) - FormApply.success(req.getContextPath()+'/').generateResponse(req, rsp, null); - else - FormApply.success(""configure"").generateResponse(req, rsp, null); // back to config - } finally { - bc.commit(); - } - } - - /** - * Gets the {@link CrumbIssuer} currently in use. - * - * @return null if none is in use. - */ - public CrumbIssuer getCrumbIssuer() { - return crumbIssuer; - } - - public void setCrumbIssuer(CrumbIssuer issuer) { - crumbIssuer = issuer; - } - - public synchronized void doTestPost( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException { - rsp.sendRedirect(""foo""); - } - - private boolean configureDescriptor(StaplerRequest req, JSONObject json, Descriptor d) throws FormException { - // collapse the structure to remain backward compatible with the JSON structure before 1. - String name = d.getJsonSafeClassName(); - JSONObject js = json.has(name) ? json.getJSONObject(name) : new JSONObject(); // if it doesn't have the property, the method returns invalid null object. - json.putAll(js); - return d.configure(req, js); - } - - /** - * Accepts submission from the node configuration page. - */ - public synchronized void doConfigExecutorsSubmit( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException, FormException { - checkPermission(ADMINISTER); - - BulkChange bc = new BulkChange(this); - try { - JSONObject json = req.getSubmittedForm(); - - MasterBuildConfiguration mbc = MasterBuildConfiguration.all().get(MasterBuildConfiguration.class); - if (mbc!=null) - mbc.configure(req,json); - - getNodeProperties().rebuild(req, json.optJSONObject(""nodeProperties""), NodeProperty.all()); - } finally { - bc.commit(); - } - - rsp.sendRedirect(req.getContextPath()+'/'+toComputer().getUrl()); // back to the computer page - } - - /** - * Accepts the new description. - */ - public synchronized void doSubmitDescription( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException { - getPrimaryView().doSubmitDescription(req, rsp); - } - - public synchronized HttpRedirect doQuietDown() throws IOException { - try { - return doQuietDown(false,0); - } catch (InterruptedException e) { - throw new AssertionError(); // impossible - } - } - - @CLIMethod(name=""quiet-down"") - public HttpRedirect doQuietDown( - @Option(name=""-block"",usage=""Block until the system really quiets down and no builds are running"") @QueryParameter boolean block, - @Option(name=""-timeout"",usage=""If non-zero, only block up to the specified number of milliseconds"") @QueryParameter int timeout) throws InterruptedException, IOException { - synchronized (this) { - checkPermission(ADMINISTER); - isQuietingDown = true; - } - if (block) { - if (timeout > 0) timeout += System.currentTimeMillis(); - while (isQuietingDown - && (timeout <= 0 || System.currentTimeMillis() < timeout) - && !RestartListener.isAllReady()) { - Thread.sleep(1000); - } - } - return new HttpRedirect("".""); - } - - @CLIMethod(name=""cancel-quiet-down"") - public synchronized HttpRedirect doCancelQuietDown() { - checkPermission(ADMINISTER); - isQuietingDown = false; - getQueue().scheduleMaintenance(); - return new HttpRedirect("".""); - } - - /** - * Backward compatibility. Redirect to the thread dump. - */ - public void doClassicThreadDump(StaplerResponse rsp) throws IOException, ServletException { - rsp.sendRedirect2(""threadDump""); - } - - /** - * Obtains the thread dump of all slaves (including the master.) - * - *

- * Since this is for diagnostics, it has a built-in precautionary measure against hang slaves. - */ - public Map> getAllThreadDumps() throws IOException, InterruptedException { - checkPermission(ADMINISTER); - - // issue the requests all at once - Map>> future = new HashMap>>(); - - for (Computer c : getComputers()) { - try { - future.put(c.getName(), RemotingDiagnostics.getThreadDumpAsync(c.getChannel())); - } catch(Exception e) { - LOGGER.info(""Failed to get thread dump for node "" + c.getName() + "": "" + e.getMessage()); - } - } - if (toComputer() == null) { - future.put(""master"", RemotingDiagnostics.getThreadDumpAsync(MasterComputer.localChannel)); - } - - // if the result isn't available in 5 sec, ignore that. - // this is a precaution against hang nodes - long endTime = System.currentTimeMillis() + 5000; - - Map> r = new HashMap>(); - for (Entry>> e : future.entrySet()) { - try { - r.put(e.getKey(), e.getValue().get(endTime-System.currentTimeMillis(), TimeUnit.MILLISECONDS)); - } catch (Exception x) { - StringWriter sw = new StringWriter(); - x.printStackTrace(new PrintWriter(sw,true)); - r.put(e.getKey(), Collections.singletonMap(""Failed to retrieve thread dump"",sw.toString())); - } - } - return r; - } - - public synchronized TopLevelItem doCreateItem( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException { - return itemGroupMixIn.createTopLevelItem(req, rsp); - } - - /** - * @since 1.319 - */ - public TopLevelItem createProjectFromXML(String name, InputStream xml) throws IOException { - return itemGroupMixIn.createProjectFromXML(name, xml); - } - - - @SuppressWarnings({""unchecked""}) - public T copy(T src, String name) throws IOException { - return itemGroupMixIn.copy(src, name); - } - - // a little more convenient overloading that assumes the caller gives us the right type - // (or else it will fail with ClassCastException) - public > T copy(T src, String name) throws IOException { - return (T)copy((TopLevelItem)src,name); - } - - public synchronized void doCreateView( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException, FormException { - checkPermission(View.CREATE); - addView(View.create(req,rsp, this)); - } - - /** - * Check if the given name is suitable as a name - * for job, view, etc. - * - * @throws ParseException - * if the given name is not good - */ - public static void checkGoodName(String name) throws Failure { - if(name==null || name.length()==0) - throw new Failure(Messages.Hudson_NoName()); - - for( int i=0; i[]:;"".indexOf(ch)!=-1) - throw new Failure(Messages.Hudson_UnsafeChar(ch)); - } - - // looks good - } - - /** - * Makes sure that the given name is good as a job name. - * @return trimmed name if valid; throws ParseException if not - */ - private String checkJobName(String name) throws Failure { - checkGoodName(name); - name = name.trim(); - projectNamingStrategy.checkName(name); - if(getItem(name)!=null) - throw new Failure(Messages.Hudson_JobAlreadyExists(name)); - // looks good - return name; - } - - private static String toPrintableName(String name) { - StringBuilder printableName = new StringBuilder(); - for( int i=0; i args = new ArrayList(); - while (true) - args.add(new byte[1024*1024]); - } - - private transient final Map duplexChannels = new HashMap(); - - /** - * Handles HTTP requests for duplex channels for CLI. - */ - public void doCli(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException, InterruptedException { - if (!""POST"".equals(req.getMethod())) { - // for GET request, serve _cli.jelly, assuming this is a browser - checkPermission(READ); - req.getView(this,""_cli.jelly"").forward(req,rsp); - return; - } - - // do not require any permission to establish a CLI connection - // the actual authentication for the connecting Channel is done by CLICommand - - UUID uuid = UUID.fromString(req.getHeader(""Session"")); - rsp.setHeader(""Hudson-Duplex"",""""); // set the header so that the client would know - - FullDuplexHttpChannel server; - if(req.getHeader(""Side"").equals(""download"")) { - duplexChannels.put(uuid,server=new FullDuplexHttpChannel(uuid, !hasPermission(ADMINISTER)) { - protected void main(Channel channel) throws IOException, InterruptedException { - // capture the identity given by the transport, since this can be useful for SecurityRealm.createCliAuthenticator() - channel.setProperty(CLICommand.TRANSPORT_AUTHENTICATION,getAuthentication()); - channel.setProperty(CliEntryPoint.class.getName(),new CliManagerImpl(channel)); - } - }); - try { - server.download(req,rsp); - } finally { - duplexChannels.remove(uuid); - } - } else { - duplexChannels.get(uuid).upload(req,rsp); - } - } - - /** - * Binds /userContent/... to $JENKINS_HOME/userContent. - */ - public DirectoryBrowserSupport doUserContent() { - return new DirectoryBrowserSupport(this,getRootPath().child(""userContent""),""User content"",""folder.png"",true); - } - - /** - * Perform a restart of Hudson, if we can. - * - * This first replaces ""app"" to {@link HudsonIsRestarting} - */ - @CLIMethod(name=""restart"") - public void doRestart(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException, RestartNotSupportedException { - checkPermission(ADMINISTER); - if (req != null && req.getMethod().equals(""GET"")) { - req.getView(this,""_restart.jelly"").forward(req,rsp); - return; - } - - restart(); - - if (rsp != null) // null for CLI - rsp.sendRedirect2("".""); - } - - /** - * Queues up a restart of Hudson for when there are no builds running, if we can. - * - * This first replaces ""app"" to {@link HudsonIsRestarting} - * - * @since 1.332 - */ - @CLIMethod(name=""safe-restart"") - public HttpResponse doSafeRestart(StaplerRequest req) throws IOException, ServletException, RestartNotSupportedException { - checkPermission(ADMINISTER); - if (req != null && req.getMethod().equals(""GET"")) - return HttpResponses.forwardToView(this,""_safeRestart.jelly""); - - safeRestart(); - - return HttpResponses.redirectToDot(); - } - - /** - * Performs a restart. - */ - public void restart() throws RestartNotSupportedException { - final Lifecycle lifecycle = Lifecycle.get(); - lifecycle.verifyRestartable(); // verify that Hudson is restartable - servletContext.setAttribute(""app"", new HudsonIsRestarting()); - - new Thread(""restart thread"") { - final String exitUser = getAuthentication().getName(); - @Override - public void run() { - try { - ACL.impersonate(ACL.SYSTEM); - - // give some time for the browser to load the ""reloading"" page - Thread.sleep(5000); - LOGGER.severe(String.format(""Restarting VM as requested by %s"",exitUser)); - for (RestartListener listener : RestartListener.all()) - listener.onRestart(); - lifecycle.restart(); - } catch (InterruptedException e) { - LOGGER.log(Level.WARNING, ""Failed to restart Hudson"",e); - } catch (IOException e) { - LOGGER.log(Level.WARNING, ""Failed to restart Hudson"",e); - } - } - }.start(); - } - - /** - * Queues up a restart to be performed once there are no builds currently running. - * @since 1.332 - */ - public void safeRestart() throws RestartNotSupportedException { - final Lifecycle lifecycle = Lifecycle.get(); - lifecycle.verifyRestartable(); // verify that Hudson is restartable - // Quiet down so that we won't launch new builds. - isQuietingDown = true; - - new Thread(""safe-restart thread"") { - final String exitUser = getAuthentication().getName(); - @Override - public void run() { - try { - ACL.impersonate(ACL.SYSTEM); - - // Wait 'til we have no active executors. - doQuietDown(true, 0); - - // Make sure isQuietingDown is still true. - if (isQuietingDown) { - servletContext.setAttribute(""app"",new HudsonIsRestarting()); - // give some time for the browser to load the ""reloading"" page - LOGGER.info(""Restart in 10 seconds""); - Thread.sleep(10000); - LOGGER.severe(String.format(""Restarting VM as requested by %s"",exitUser)); - for (RestartListener listener : RestartListener.all()) - listener.onRestart(); - lifecycle.restart(); - } else { - LOGGER.info(""Safe-restart mode cancelled""); - } - } catch (InterruptedException e) { - LOGGER.log(Level.WARNING, ""Failed to restart Hudson"",e); - } catch (IOException e) { - LOGGER.log(Level.WARNING, ""Failed to restart Hudson"",e); - } - } - }.start(); - } - - /** - * Shutdown the system. - * @since 1.161 - */ - @CLIMethod(name=""shutdown"") - public void doExit( StaplerRequest req, StaplerResponse rsp ) throws IOException { - checkPermission(ADMINISTER); - LOGGER.severe(String.format(""Shutting down VM as requested by %s from %s"", - getAuthentication().getName(), req!=null?req.getRemoteAddr():""???"")); - if (rsp!=null) { - rsp.setStatus(HttpServletResponse.SC_OK); - rsp.setContentType(""text/plain""); - PrintWriter w = rsp.getWriter(); - w.println(""Shutting down""); - w.close(); - } - - System.exit(0); - } - - - /** - * Shutdown the system safely. - * @since 1.332 - */ - @CLIMethod(name=""safe-shutdown"") - public HttpResponse doSafeExit(StaplerRequest req) throws IOException { - checkPermission(ADMINISTER); - isQuietingDown = true; - final String exitUser = getAuthentication().getName(); - final String exitAddr = req!=null ? req.getRemoteAddr() : ""unknown""; - new Thread(""safe-exit thread"") { - @Override - public void run() { - try { - ACL.impersonate(ACL.SYSTEM); - LOGGER.severe(String.format(""Shutting down VM as requested by %s from %s"", - exitUser, exitAddr)); - // Wait 'til we have no active executors. - while (isQuietingDown - && (overallLoad.computeTotalExecutors() > overallLoad.computeIdleExecutors())) { - Thread.sleep(5000); - } - // Make sure isQuietingDown is still true. - if (isQuietingDown) { - cleanUp(); - System.exit(0); - } - } catch (InterruptedException e) { - LOGGER.log(Level.WARNING, ""Failed to shutdown Hudson"",e); - } - } - }.start(); - - return HttpResponses.plainText(""Shutting down as soon as all jobs are complete""); - } - - /** - * Gets the {@link Authentication} object that represents the user - * associated with the current request. - */ - public static Authentication getAuthentication() { - Authentication a = SecurityContextHolder.getContext().getAuthentication(); - // on Tomcat while serving the login page, this is null despite the fact - // that we have filters. Looking at the stack trace, Tomcat doesn't seem to - // run the request through filters when this is the login request. - // see http://www.nabble.com/Matrix-authorization-problem-tp14602081p14886312.html - if(a==null) - a = ANONYMOUS; - return a; - } - - /** - * For system diagnostics. - * Run arbitrary Groovy script. - */ - public void doScript(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { - doScript(req, rsp, req.getView(this, ""_script.jelly"")); - } - - /** - * Run arbitrary Groovy script and return result as plain text. - */ - public void doScriptText(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { - doScript(req, rsp, req.getView(this, ""_scriptText.jelly"")); - } - - private void doScript(StaplerRequest req, StaplerResponse rsp, RequestDispatcher view) throws IOException, ServletException { - // ability to run arbitrary script is dangerous - checkPermission(RUN_SCRIPTS); - - String text = req.getParameter(""script""); - if (text != null) { - try { - req.setAttribute(""output"", - RemotingDiagnostics.executeGroovy(text, MasterComputer.localChannel)); - } catch (InterruptedException e) { - throw new ServletException(e); - } - } - - view.forward(req, rsp); - } - - /** - * Evaluates the Jelly script submitted by the client. - * - * This is useful for system administration as well as unit testing. - */ - @RequirePOST - public void doEval(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { - checkPermission(ADMINISTER); - - try { - MetaClass mc = WebApp.getCurrent().getMetaClass(getClass()); - Script script = mc.classLoader.loadTearOff(JellyClassLoaderTearOff.class).createContext().compileScript(new InputSource(req.getReader())); - new JellyRequestDispatcher(this,script).forward(req,rsp); - } catch (JellyException e) { - throw new ServletException(e); - } - } - - /** - * Sign up for the user account. - */ - public void doSignup( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException { - req.getView(getSecurityRealm(), ""signup.jelly"").forward(req, rsp); - } - - /** - * Changes the icon size by changing the cookie - */ - public void doIconSize( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException { - String qs = req.getQueryString(); - if(qs==null || !ICON_SIZE.matcher(qs).matches()) - throw new ServletException(); - Cookie cookie = new Cookie(""iconSize"", qs); - cookie.setMaxAge(/* ~4 mo. */9999999); // #762 - rsp.addCookie(cookie); - String ref = req.getHeader(""Referer""); - if(ref==null) ref="".""; - rsp.sendRedirect2(ref); - } - - public void doFingerprintCleanup(StaplerResponse rsp) throws IOException { - FingerprintCleanupThread.invoke(); - rsp.setStatus(HttpServletResponse.SC_OK); - rsp.setContentType(""text/plain""); - rsp.getWriter().println(""Invoked""); - } - - public void doWorkspaceCleanup(StaplerResponse rsp) throws IOException { - WorkspaceCleanupThread.invoke(); - rsp.setStatus(HttpServletResponse.SC_OK); - rsp.setContentType(""text/plain""); - rsp.getWriter().println(""Invoked""); - } - - /** - * If the user chose the default JDK, make sure we got 'java' in PATH. - */ - public FormValidation doDefaultJDKCheck(StaplerRequest request, @QueryParameter String value) { - if(!value.equals(""(Default)"")) - // assume the user configured named ones properly in system config --- - // or else system config should have reported form field validation errors. - return FormValidation.ok(); - - // default JDK selected. Does such java really exist? - if(JDK.isDefaultJDKValid(Jenkins.this)) - return FormValidation.ok(); - else - return FormValidation.errorWithMarkup(Messages.Hudson_NoJavaInPath(request.getContextPath())); - } - - /** - * Makes sure that the given name is good as a job name. - */ - public FormValidation doCheckJobName(@QueryParameter String value) { - // this method can be used to check if a file exists anywhere in the file system, - // so it should be protected. - checkPermission(Item.CREATE); - - if(fixEmpty(value)==null) - return FormValidation.ok(); - - try { - checkJobName(value); - return FormValidation.ok(); - } catch (Failure e) { - return FormValidation.error(e.getMessage()); - } - } - - /** - * Checks if a top-level view with the given name exists. - */ - public FormValidation doViewExistsCheck(@QueryParameter String value) { - checkPermission(View.CREATE); - - String view = fixEmpty(value); - if(view==null) return FormValidation.ok(); - - if(getView(view)==null) - return FormValidation.ok(); - else - return FormValidation.error(Messages.Hudson_ViewAlreadyExists(view)); - } - - /** - * Serves static resources placed along with Jelly view files. - *

- * This method can serve a lot of files, so care needs to be taken - * to make this method secure. It's not clear to me what's the best - * strategy here, though the current implementation is based on - * file extensions. - */ - public void doResources(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { - String path = req.getRestOfPath(); - // cut off the ""..."" portion of /resources/.../path/to/file - // as this is only used to make path unique (which in turn - // allows us to set a long expiration date - path = path.substring(path.indexOf('/',1)+1); - - int idx = path.lastIndexOf('.'); - String extension = path.substring(idx+1); - if(ALLOWED_RESOURCE_EXTENSIONS.contains(extension)) { - URL url = pluginManager.uberClassLoader.getResource(path); - if(url!=null) { - long expires = MetaClass.NO_CACHE ? 0 : 365L * 24 * 60 * 60 * 1000; /*1 year*/ - rsp.serveFile(req,url,expires); - return; - } - } - rsp.sendError(HttpServletResponse.SC_NOT_FOUND); - } - - /** - * Extension list that {@link #doResources(StaplerRequest, StaplerResponse)} can serve. - * This set is mutable to allow plugins to add additional extensions. - */ - public static final Set ALLOWED_RESOURCE_EXTENSIONS = new HashSet(Arrays.asList( - ""js|css|jpeg|jpg|png|gif|html|htm"".split(""\\|"") - )); - - /** - * Checks if container uses UTF-8 to decode URLs. See - * http://wiki.jenkins-ci.org/display/JENKINS/Tomcat#Tomcat-i18n - */ - public FormValidation doCheckURIEncoding(StaplerRequest request) throws IOException { - // expected is non-ASCII String - final String expected = ""\u57f7\u4e8b""; - final String value = fixEmpty(request.getParameter(""value"")); - if (!expected.equals(value)) - return FormValidation.warningWithMarkup(Messages.Hudson_NotUsesUTF8ToDecodeURL()); - return FormValidation.ok(); - } - - /** - * Does not check when system default encoding is ""ISO-8859-1"". - */ - public static boolean isCheckURIEncodingEnabled() { - return !""ISO-8859-1"".equalsIgnoreCase(System.getProperty(""file.encoding"")); - } - - /** - * Rebuilds the dependency map. - */ - public void rebuildDependencyGraph() { - DependencyGraph graph = new DependencyGraph(); - graph.build(); - // volatile acts a as a memory barrier here and therefore guarantees - // that graph is fully build, before it's visible to other threads - dependencyGraph = graph; - } - - public DependencyGraph getDependencyGraph() { - return dependencyGraph; - } - - // for Jelly - public List getManagementLinks() { - return ManagementLink.all(); - } - - /** - * Exposes the current user to /me URL. - */ - public User getMe() { - User u = User.current(); - if (u == null) - throw new AccessDeniedException(""/me is not available when not logged in""); - return u; - } - - /** - * Gets the {@link Widget}s registered on this object. - * - *

- * Plugins who wish to contribute boxes on the side panel can add widgets - * by {@code getWidgets().add(new MyWidget())} from {@link Plugin#start()}. - */ - public List getWidgets() { - return widgets; - } - - public Object getTarget() { - try { - checkPermission(READ); - } catch (AccessDeniedException e) { - String rest = Stapler.getCurrentRequest().getRestOfPath(); - if(rest.startsWith(""/login"") - || rest.startsWith(""/logout"") - || rest.startsWith(""/accessDenied"") - || rest.startsWith(""/adjuncts/"") - || rest.startsWith(""/signup"") - || rest.startsWith(""/tcpSlaveAgentListener"") - || rest.startsWith(""/cli"") - || rest.startsWith(""/federatedLoginService/"") - || rest.startsWith(""/securityRealm"")) - return this; // URLs that are always visible without READ permission - - for (String name : getUnprotectedRootActions()) { - if (rest.startsWith(""/"" + name + ""/"") || rest.equals(""/"" + name)) { - return this; - } - } - - throw e; - } - return this; - } - - /** - * Gets a list of unprotected root actions. - * These URL prefixes should be exempted from access control checks by container-managed security. - * Ideally would be synchronized with {@link #getTarget}. - * @return a list of {@linkplain Action#getUrlName URL names} - * @since 1.495 - */ - public Collection getUnprotectedRootActions() { - Set names = new TreeSet(); - names.add(""jnlpJars""); // XXX cleaner to refactor doJnlpJars into a URA - // XXX consider caching (expiring cache when actions changes) - for (Action a : getActions()) { - if (a instanceof UnprotectedRootAction) { - names.add(a.getUrlName()); - } - } - return names; - } - - /** - * Fallback to the primary view. - */ - public View getStaplerFallback() { - return getPrimaryView(); - } - - /** - * This method checks all existing jobs to see if displayName is - * unique. It does not check the displayName against the displayName of the - * job that the user is configuring though to prevent a validation warning - * if the user sets the displayName to what it currently is. - * @param displayName - * @param currentJobName - * @return - */ - boolean isDisplayNameUnique(String displayName, String currentJobName) { - Collection itemCollection = items.values(); - - // if there are a lot of projects, we'll have to store their - // display names in a HashSet or something for a quick check - for(TopLevelItem item : itemCollection) { - if(item.getName().equals(currentJobName)) { - // we won't compare the candidate displayName against the current - // item. This is to prevent an validation warning if the user - // sets the displayName to what the existing display name is - continue; - } - else if(displayName.equals(item.getDisplayName())) { - return false; - } - } - - return true; - } - - /** - * True if there is no item in Jenkins that has this name - * @param name The name to test - * @param currentJobName The name of the job that the user is configuring - * @return - */ - boolean isNameUnique(String name, String currentJobName) { - Item item = getItem(name); - - if(null==item) { - // the candidate name didn't return any items so the name is unique - return true; - } - else if(item.getName().equals(currentJobName)) { - // the candidate name returned an item, but the item is the item - // that the user is configuring so this is ok - return true; - } - else { - // the candidate name returned an item, so it is not unique - return false; - } - } - - /** - * Checks to see if the candidate displayName collides with any - * existing display names or project names - * @param displayName The display name to test - * @param jobName The name of the job the user is configuring - * @return - */ - public FormValidation doCheckDisplayName(@QueryParameter String displayName, - @QueryParameter String jobName) { - displayName = displayName.trim(); - - if(LOGGER.isLoggable(Level.FINE)) { - LOGGER.log(Level.FINE, ""Current job name is "" + jobName); - } - - if(!isNameUnique(displayName, jobName)) { - return FormValidation.warning(Messages.Jenkins_CheckDisplayName_NameNotUniqueWarning(displayName)); - } - else if(!isDisplayNameUnique(displayName, jobName)){ - return FormValidation.warning(Messages.Jenkins_CheckDisplayName_DisplayNameNotUniqueWarning(displayName)); - } - else { - return FormValidation.ok(); - } - } - - public static class MasterComputer extends Computer { - protected MasterComputer() { - super(Jenkins.getInstance()); - } - - /** - * Returns """" to match with {@link Jenkins#getNodeName()}. - */ - @Override - public String getName() { - return """"; - } - - @Override - public boolean isConnecting() { - return false; - } - - @Override - public String getDisplayName() { - return Messages.Hudson_Computer_DisplayName(); - } - - @Override - public String getCaption() { - return Messages.Hudson_Computer_Caption(); - } - - @Override - public String getUrl() { - return ""computer/(master)/""; - } - - public RetentionStrategy getRetentionStrategy() { - return RetentionStrategy.NOOP; - } - - /** - * Report an error. - */ - @Override - public HttpResponse doDoDelete() throws IOException { - throw HttpResponses.status(SC_BAD_REQUEST); - } - - @Override - public void doConfigSubmit(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException, FormException { - Jenkins.getInstance().doConfigExecutorsSubmit(req, rsp); - } - - @Override - public boolean hasPermission(Permission permission) { - // no one should be allowed to delete the master. - // this hides the ""delete"" link from the /computer/(master) page. - if(permission==Computer.DELETE) - return false; - // Configuration of master node requires ADMINISTER permission - return super.hasPermission(permission==Computer.CONFIGURE ? Jenkins.ADMINISTER : permission); - } - - @Override - public VirtualChannel getChannel() { - return localChannel; - } - - @Override - public Charset getDefaultCharset() { - return Charset.defaultCharset(); - } - - public List getLogRecords() throws IOException, InterruptedException { - return logRecords; - } - - public void doLaunchSlaveAgent(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { - // this computer never returns null from channel, so - // this method shall never be invoked. - rsp.sendError(SC_NOT_FOUND); - } - - protected Future _connect(boolean forceReconnect) { - return Futures.precomputed(null); - } - - /** - * {@link LocalChannel} instance that can be used to execute programs locally. - */ - public static final LocalChannel localChannel = new LocalChannel(threadPoolForRemoting); - } - - /** - * Shortcut for {@code Hudson.getInstance().lookup.get(type)} - */ - public static T lookup(Class type) { - return Jenkins.getInstance().lookup.get(type); - } - - /** - * Live view of recent {@link LogRecord}s produced by Hudson. - */ - public static List logRecords = Collections.emptyList(); // initialized to dummy value to avoid NPE - - /** - * Thread-safe reusable {@link XStream}. - */ - public static final XStream XSTREAM = new XStream2(); - - /** - * Alias to {@link #XSTREAM} so that one can access additional methods on {@link XStream2} more easily. - */ - public static final XStream2 XSTREAM2 = (XStream2)XSTREAM; - - private static final int TWICE_CPU_NUM = Math.max(4, Runtime.getRuntime().availableProcessors() * 2); - - /** - * Thread pool used to load configuration in parallel, to improve the start up time. - *

- * The idea here is to overlap the CPU and I/O, so we want more threads than CPU numbers. - */ - /*package*/ transient final ExecutorService threadPoolForLoad = new ThreadPoolExecutor( - TWICE_CPU_NUM, TWICE_CPU_NUM, - 5L, TimeUnit.SECONDS, new LinkedBlockingQueue(), new DaemonThreadFactory()); - - - private static void computeVersion(ServletContext context) { - // set the version - Properties props = new Properties(); - try { - InputStream is = Jenkins.class.getResourceAsStream(""jenkins-version.properties""); - if(is!=null) - props.load(is); - } catch (IOException e) { - e.printStackTrace(); // if the version properties is missing, that's OK. - } - String ver = props.getProperty(""version""); - if(ver==null) ver=""?""; - VERSION = ver; - context.setAttribute(""version"",ver); - - VERSION_HASH = Util.getDigestOf(ver).substring(0, 8); - SESSION_HASH = Util.getDigestOf(ver+System.currentTimeMillis()).substring(0, 8); - - if(ver.equals(""?"") || Boolean.getBoolean(""hudson.script.noCache"")) - RESOURCE_PATH = """"; - else - RESOURCE_PATH = ""/static/""+SESSION_HASH; - - VIEW_RESOURCE_PATH = ""/resources/""+ SESSION_HASH; - } - - /** - * Version number of this Hudson. - */ - public static String VERSION=""?""; - - /** - * Parses {@link #VERSION} into {@link VersionNumber}, or null if it's not parseable as a version number - * (such as when Hudson is run with ""mvn hudson-dev:run"") - */ - public static VersionNumber getVersion() { - try { - return new VersionNumber(VERSION); - } catch (NumberFormatException e) { - try { - // for non-released version of Hudson, this looks like ""1.345 (private-foobar), so try to approximate. - int idx = VERSION.indexOf(' '); - if (idx>0) - return new VersionNumber(VERSION.substring(0,idx)); - } catch (NumberFormatException _) { - // fall through - } - - // totally unparseable - return null; - } catch (IllegalArgumentException e) { - // totally unparseable - return null; - } - } - - /** - * Hash of {@link #VERSION}. - */ - public static String VERSION_HASH; - - /** - * Unique random token that identifies the current session. - * Used to make {@link #RESOURCE_PATH} unique so that we can set long ""Expires"" header. - * - * We used to use {@link #VERSION_HASH}, but making this session local allows us to - * reuse the same {@link #RESOURCE_PATH} for static resources in plugins. - */ - public static String SESSION_HASH; - - /** - * Prefix to static resources like images and javascripts in the war file. - * Either """" or strings like ""/static/VERSION"", which avoids Hudson to pick up - * stale cache when the user upgrades to a different version. - *

- * Value computed in {@link WebAppMain}. - */ - public static String RESOURCE_PATH = """"; - - /** - * Prefix to resources alongside view scripts. - * Strings like ""/resources/VERSION"", which avoids Hudson to pick up - * stale cache when the user upgrades to a different version. - *

- * Value computed in {@link WebAppMain}. - */ - public static String VIEW_RESOURCE_PATH = ""/resources/TBD""; - - public static boolean PARALLEL_LOAD = Configuration.getBooleanConfigParameter(""parallelLoad"", true); - public static boolean KILL_AFTER_LOAD = Configuration.getBooleanConfigParameter(""killAfterLoad"", false); - /** - * Enabled by default as of 1.337. Will keep it for a while just in case we have some serious problems. - */ - public static boolean FLYWEIGHT_SUPPORT = Configuration.getBooleanConfigParameter(""flyweightSupport"", true); - - /** - * Tentative switch to activate the concurrent build behavior. - * When we merge this back to the trunk, this allows us to keep - * this feature hidden for a while until we iron out the kinks. - * @see AbstractProject#isConcurrentBuild() - * @deprecated as of 1.464 - * This flag will have no effect. - */ - @Restricted(NoExternalUse.class) - public static boolean CONCURRENT_BUILD = true; - - /** - * Switch to enable people to use a shorter workspace name. - */ - private static final String WORKSPACE_DIRNAME = Configuration.getStringConfigParameter(""workspaceDirName"", ""workspace""); - - /** - * Automatically try to launch a slave when Jenkins is initialized or a new slave is created. - */ - public static boolean AUTOMATIC_SLAVE_LAUNCH = true; - - private static final Logger LOGGER = Logger.getLogger(Jenkins.class.getName()); - - private static final Pattern ICON_SIZE = Pattern.compile(""\\d+x\\d+""); - - public static final PermissionGroup PERMISSIONS = Permission.HUDSON_PERMISSIONS; - public static final Permission ADMINISTER = Permission.HUDSON_ADMINISTER; - public static final Permission READ = new Permission(PERMISSIONS,""Read"",Messages._Hudson_ReadPermission_Description(),Permission.READ,PermissionScope.JENKINS); - public static final Permission RUN_SCRIPTS = new Permission(PERMISSIONS, ""RunScripts"", Messages._Hudson_RunScriptsPermission_Description(),ADMINISTER,PermissionScope.JENKINS); - - /** - * {@link Authentication} object that represents the anonymous user. - * Because Acegi creates its own {@link AnonymousAuthenticationToken} instances, the code must not - * expect the singleton semantics. This is just a convenient instance. - * - * @since 1.343 - */ - public static final Authentication ANONYMOUS = new AnonymousAuthenticationToken( - ""anonymous"",""anonymous"",new GrantedAuthority[]{new GrantedAuthorityImpl(""anonymous"")}); - - static { - XSTREAM.alias(""jenkins"",Jenkins.class); - XSTREAM.alias(""slave"", DumbSlave.class); - XSTREAM.alias(""jdk"",JDK.class); - // for backward compatibility with <1.75, recognize the tag name ""view"" as well. - XSTREAM.alias(""view"", ListView.class); - XSTREAM.alias(""listView"", ListView.class); - // this seems to be necessary to force registration of converter early enough - Mode.class.getEnumConstants(); - - // double check that initialization order didn't do any harm - assert PERMISSIONS!=null; - assert ADMINISTER!=null; - } - -} -" -287,1," Object getValue(Object parent); - - /** - * Returns the name of this cascadable element. - * - * @return The name of this cascadable element. - */ -" -288,1," public String getInfo() { - - return (info); - - } - - - -" -289,1," protected boolean addInputFilter(InputFilter[] inputFilters, - String encodingName) { - if (encodingName.equals(""identity"")) { - // Skip - } else if (encodingName.equals(""chunked"")) { - inputBuffer.addActiveFilter - (inputFilters[Constants.CHUNKED_FILTER]); - contentDelimitation = true; - } else { - for (int i = 2; i < inputFilters.length; i++) { - if (inputFilters[i].getEncodingName() - .toString().equals(encodingName)) { - inputBuffer.addActiveFilter(inputFilters[i]); - return true; - } - } - return false; - } - return true; - } - - - /** - * Specialized utility method: find a sequence of lower case bytes inside - * a ByteChunk. - */ -" -290,1," public void changePassword_Resets_Session() throws Exception { - ScimUser user = createUser(); - - MockHttpSession session = new MockHttpSession(); - MockHttpSession afterLoginSession = (MockHttpSession) getMockMvc().perform(post(""/login.do"") - .session(session) - .accept(TEXT_HTML_VALUE) - .param(""username"", user.getUserName()) - .param(""password"", ""secr3T"")) - .andExpect(status().isFound()) - .andExpect(redirectedUrl(""/"")) - .andReturn().getRequest().getSession(false); - - assertTrue(session.isInvalid()); - assertNotNull(afterLoginSession); - assertNotNull(afterLoginSession.getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY)); - - MockHttpSession afterPasswordChange = (MockHttpSession) getMockMvc().perform(post(""/change_password.do"") - .session(afterLoginSession) - .with(csrf()) - .accept(TEXT_HTML_VALUE) - .param(""current_password"", ""secr3T"") - .param(""new_password"", ""secr3T1"") - .param(""confirm_password"", ""secr3T1"")) - .andExpect(status().isFound()) - .andExpect(redirectedUrl(""profile"")) - .andReturn().getRequest().getSession(false); - - assertTrue(afterLoginSession.isInvalid()); - assertNotNull(afterPasswordChange); - assertNotNull(afterPasswordChange.getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY)); - assertNotSame(afterLoginSession, afterPasswordChange); - - } - -" -291,1," public String changePassword( - Model model, - @RequestParam(""current_password"") String currentPassword, - @RequestParam(""new_password"") String newPassword, - @RequestParam(""confirm_password"") String confirmPassword, - HttpServletResponse response, - HttpServletRequest request) { - - PasswordConfirmationValidation validation = new PasswordConfirmationValidation(newPassword, confirmPassword); - if (!validation.valid()) { - model.addAttribute(""message_code"", validation.getMessageCode()); - response.setStatus(HttpStatus.UNPROCESSABLE_ENTITY.value()); - return ""change_password""; - } - - SecurityContext securityContext = SecurityContextHolder.getContext(); - Authentication authentication = securityContext.getAuthentication(); - String username = authentication.getName(); - - try { - changePasswordService.changePassword(username, currentPassword, newPassword); - request.getSession().invalidate(); - request.getSession(true); - securityContext.setAuthentication(authentication); - return ""redirect:profile""; - } catch (BadCredentialsException e) { - model.addAttribute(""message_code"", ""unauthorized""); - } catch (InvalidPasswordException e) { - model.addAttribute(""message"", e.getMessagesAsOneString()); - } - response.setStatus(HttpStatus.UNPROCESSABLE_ENTITY.value()); - return ""change_password""; - } -" -292,1," private XPathEvaluator createEvaluator(String xpath2) { - try { - return (XPathEvaluator)EVALUATOR_CONSTRUCTOR.newInstance(new Object[] {xpath}); - } catch (InvocationTargetException e) { - Throwable cause = e.getCause(); - if (cause instanceof RuntimeException) { - throw (RuntimeException)cause; - } - throw new RuntimeException(""Invalid XPath Expression: "" + xpath + "" reason: "" + e.getMessage(), e); - } catch (Throwable e) { - throw new RuntimeException(""Invalid XPath Expression: "" + xpath + "" reason: "" + e.getMessage(), e); - } - } - -" -293,1," protected RequestEntity createRequestEntity(Exchange exchange) throws CamelExchangeException { - Message in = exchange.getIn(); - if (in.getBody() == null) { - return null; - } - - RequestEntity answer = in.getBody(RequestEntity.class); - if (answer == null) { - try { - Object data = in.getBody(); - if (data != null) { - String contentType = ExchangeHelper.getContentType(exchange); - - if (contentType != null && HttpConstants.CONTENT_TYPE_JAVA_SERIALIZED_OBJECT.equals(contentType)) { - // serialized java object - Serializable obj = in.getMandatoryBody(Serializable.class); - // write object to output stream - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - HttpHelper.writeObjectToStream(bos, obj); - answer = new ByteArrayRequestEntity(bos.toByteArray(), HttpConstants.CONTENT_TYPE_JAVA_SERIALIZED_OBJECT); - IOHelper.close(bos); - } else if (data instanceof File || data instanceof GenericFile) { - // file based (could potentially also be a FTP file etc) - File file = in.getBody(File.class); - if (file != null) { - answer = new FileRequestEntity(file, contentType); - } - } else if (data instanceof String) { - // be a bit careful with String as any type can most likely be converted to String - // so we only do an instanceof check and accept String if the body is really a String - // do not fallback to use the default charset as it can influence the request - // (for example application/x-www-form-urlencoded forms being sent) - String charset = IOHelper.getCharsetName(exchange, false); - answer = new StringRequestEntity((String) data, contentType, charset); - } - // fallback as input stream - if (answer == null) { - // force the body as an input stream since this is the fallback - InputStream is = in.getMandatoryBody(InputStream.class); - answer = new InputStreamRequestEntity(is, contentType); - } - } - } catch (UnsupportedEncodingException e) { - throw new CamelExchangeException(""Error creating RequestEntity from message body"", exchange, e); - } catch (IOException e) { - throw new CamelExchangeException(""Error serializing message body"", exchange, e); - } - } - return answer; - } - -" -294,1," public void execute(String key, ActionMapping mapping) { - String location = key.substring(REDIRECT_ACTION_PREFIX - .length()); - ServletRedirectResult redirect = new ServletRedirectResult(); - container.inject(redirect); - String extension = getDefaultExtension(); - if (extension != null && extension.length() > 0) { - location += ""."" + extension; - } - redirect.setLocation(location); - mapping.setResult(redirect); - } - }); - } - }; - } - - /** - * Adds a parameter action. Should only be called during initialization - * - * @param prefix The string prefix to trigger the action - * @param parameterAction The parameter action to execute - * @since 2.1.0 - */ -" -295,1," private void findConstructor() { - try { - iConstructor = iClassToInstantiate.getConstructor(iParamTypes); - } catch (final NoSuchMethodException ex) { - throw new IllegalArgumentException(""InstantiateFactory: The constructor must exist and be public ""); - } - } - - /** - * Creates an object using the stored constructor. - * - * @return the new object - */ -" -296,1," private void checkParams() - throws Exception - { - if (vi == null) - { - throw new Exception(""no layers defined.""); - } - if (vi.length > 1) - { - for (int i = 0; i < vi.length - 1; i++) - { - if (vi[i] >= vi[i + 1]) - { - throw new Exception( - ""v[i] has to be smaller than v[i+1]""); - } - } - } - else - { - throw new Exception( - ""Rainbow needs at least 1 layer, such that v1 < v2.""); - } - } - - /** - * Getter for the number of layers - * - * @return the number of layers - */ -" -297,1," public boolean isTransferException() { - return transferException; - } - - /** - * If enabled and an Exchange failed processing on the consumer side, and if the caused Exception was send back serialized - * in the response as a application/x-java-serialized-object content type (for example using Jetty or Servlet Camel components). - * On the producer side the exception will be deserialized and thrown as is, instead of the AhcOperationFailedException. - * The caused exception is required to be serialized. - */ -" -298,1," public void setMethods(Set methods) { - this.methods = new HashSet(); - for (String method : methods) { - this.methods.add(method.toUpperCase()); - } - } - - /** - * @param authenticationEntryPoint the authenticationEntryPoint to set - */ -" -299,1," private EnumSet getValidatedExecutableTypes(DefaultValidatedExecutableTypesType validatedExecutables) { - if ( validatedExecutables == null ) { - return null; - } - - EnumSet executableTypes = EnumSet.noneOf( ExecutableType.class ); - executableTypes.addAll( validatedExecutables.getExecutableType() ); - - return executableTypes; - } -" -300,1," public boolean getValidateClientProvidedNewSessionId(); -" -301,1," private File mkdirsE(File dir) throws IOException { - if (dir.exists()) { - return dir; - } - filterNonNull().mkdirs(dir); - return IOUtils.mkdirs(dir); - } - -" -302,1," public static boolean isExpression(Object value) { - String expr = value.toString(); - return expr.startsWith(""%{"") && expr.endsWith(""}""); - } - -" -303,1," protected final GF2Polynomial[] invertMatrix(GF2Polynomial[] matrix) - { - GF2Polynomial[] a = new GF2Polynomial[matrix.length]; - GF2Polynomial[] inv = new GF2Polynomial[matrix.length]; - GF2Polynomial dummy; - int i, j; - // initialize a as a copy of matrix and inv as E(inheitsmatrix) - for (i = 0; i < mDegree; i++) - { - try - { - a[i] = new GF2Polynomial(matrix[i]); - inv[i] = new GF2Polynomial(mDegree); - inv[i].setBit(mDegree - 1 - i); - } - catch (RuntimeException BDNEExc) - { - BDNEExc.printStackTrace(); - } - } - // construct triangle matrix so that for each a[i] the first i bits are - // zero - for (i = 0; i < mDegree - 1; i++) - { - // find column where bit i is set - j = i; - while ((j < mDegree) && !a[j].testBit(mDegree - 1 - i)) - { - j++; - } - if (j >= mDegree) - { - throw new RuntimeException( - ""GF2nField.invertMatrix: Matrix cannot be inverted!""); - } - if (i != j) - { // swap a[i]/a[j] and inv[i]/inv[j] - dummy = a[i]; - a[i] = a[j]; - a[j] = dummy; - dummy = inv[i]; - inv[i] = inv[j]; - inv[j] = dummy; - } - for (j = i + 1; j < mDegree; j++) - { // add column i to all columns>i - // having their i-th bit set - if (a[j].testBit(mDegree - 1 - i)) - { - a[j].addToThis(a[i]); - inv[j].addToThis(inv[i]); - } - } - } - // construct Einheitsmatrix from a - for (i = mDegree - 1; i > 0; i--) - { - for (j = i - 1; j >= 0; j--) - { // eliminate the i-th bit in all - // columns < i - if (a[j].testBit(mDegree - 1 - i)) - { - a[j].addToThis(a[i]); - inv[j].addToThis(inv[i]); - } - } - } - return inv; - } - - /** - * Converts the given element in representation according to this field to a - * new element in representation according to B1 using the change-of-basis - * matrix calculated by computeCOBMatrix. - * - * @param elem the GF2nElement to convert - * @param basis the basis to convert elem to - * @return elem converted to a new element representation - * according to basis - * @see GF2nField#computeCOBMatrix - * @see GF2nField#getRandomRoot - * @see GF2nPolynomial - * @see ""P1363 A.7 p109ff"" - */ -" -304,1," public JDBCTableReader getTableReader(Connection connection, String tableName, ParseContext context) { - return new SQLite3TableReader(connection, tableName, context); - } -" -305,1," public Source getAssociatedStylesheet( - Source source, String media, String title, String charset) - throws TransformerConfigurationException - { - - String baseID; - InputSource isource = null; - Node node = null; - XMLReader reader = null; - - if (source instanceof DOMSource) - { - DOMSource dsource = (DOMSource) source; - - node = dsource.getNode(); - baseID = dsource.getSystemId(); - } - else - { - isource = SAXSource.sourceToInputSource(source); - baseID = isource.getSystemId(); - } - - // What I try to do here is parse until the first startElement - // is found, then throw a special exception in order to terminate - // the parse. - StylesheetPIHandler handler = new StylesheetPIHandler(baseID, media, - title, charset); - - // Use URIResolver. Patch from Dmitri Ilyin - if (m_uriResolver != null) - { - handler.setURIResolver(m_uriResolver); - } - - try - { - if (null != node) - { - TreeWalker walker = new TreeWalker(handler, new org.apache.xml.utils.DOM2Helper(), baseID); - - walker.traverse(node); - } - else - { - - // Use JAXP1.1 ( if possible ) - try - { - javax.xml.parsers.SAXParserFactory factory = - javax.xml.parsers.SAXParserFactory.newInstance(); - - factory.setNamespaceAware(true); - - if (m_isSecureProcessing) - { - try - { - factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); - } - catch (org.xml.sax.SAXException e) {} - } - - javax.xml.parsers.SAXParser jaxpParser = factory.newSAXParser(); - - reader = jaxpParser.getXMLReader(); - } - catch (javax.xml.parsers.ParserConfigurationException ex) - { - throw new org.xml.sax.SAXException(ex); - } - catch (javax.xml.parsers.FactoryConfigurationError ex1) - { - throw new org.xml.sax.SAXException(ex1.toString()); - } - catch (NoSuchMethodError ex2){} - catch (AbstractMethodError ame){} - - if (null == reader) - { - reader = XMLReaderFactory.createXMLReader(); - } - - // Need to set options! - reader.setContentHandler(handler); - reader.parse(isource); - } - } - catch (StopParseException spe) - { - - // OK, good. - } - catch (org.xml.sax.SAXException se) - { - throw new TransformerConfigurationException( - ""getAssociatedStylesheets failed"", se); - } - catch (IOException ioe) - { - throw new TransformerConfigurationException( - ""getAssociatedStylesheets failed"", ioe); - } - - return handler.getAssociatedStylesheet(); - } - - /** - * Create a new Transformer object that performs a copy - * of the source to the result. - * - * @return A Transformer object that may be used to perform a transformation - * in a single thread, never null. - * - * @throws TransformerConfigurationException May throw this during - * the parse when it is constructing the - * Templates object and fails. - */ -" -306,1," public Calendar ceil(Calendar cal) { - Calendar twoYearsFuture = (Calendar) cal.clone(); - twoYearsFuture.add(Calendar.YEAR, 2); - OUTER: - while (true) { - if (cal.compareTo(twoYearsFuture) > 0) { - // we went too far into the future - throw new RareOrImpossibleDateException(); - } - for (CalendarField f : CalendarField.ADJUST_ORDER) { - int cur = f.valueOf(cal); - int next = f.ceil(this,cur); - if (cur==next) continue; // this field is already in a good shape. move on to next - - // we are modifying this field, so clear all the lower level fields - for (CalendarField l=f.lowerField; l!=null; l=l.lowerField) - l.clear(cal); - - if (next<0) { - // we need to roll over to the next field. - f.rollUp(cal, 1); - f.setTo(cal,f.first(this)); - // since higher order field is affected by this, we need to restart from all over - continue OUTER; - } else { - f.setTo(cal,next); - if (f.redoAdjustmentIfModified) - continue OUTER; // when we modify DAY_OF_MONTH and DAY_OF_WEEK, do it all over from the top - } - } - return cal; // all fields adjusted - } - } - - /** - * Computes the nearest past timestamp that matched this cron tab. - *

- * More precisely, given the time 't', computes another smallest time x such that: - * - *

    - *
  • x <= t (inclusive) - *
  • x matches this crontab - *
- * - *

- * Note that if t already matches this cron, it's returned as is. - */ -" -307,1," public void run() { - try { - ObjectInputStream in = new ObjectInputStream(socket.getInputStream()); - while (!closed) { - Message msg = (Message) in.readObject(); - handle(msg); - } - } catch (EOFException eof) { - // Remote side has closed the connection, just cleanup. - try { - close(); - } catch (Exception unused) { - // no-op. - } - } catch (Exception e) { - if (!closed) { - LOG.log(Level.WARNING, ""Error in inbound message handling."", e); - try { - close(); - } catch (Exception unused) { - // no-op. - } - } - } - } - -" -308,1," public void setAllowJavaSerializedObject(boolean allowJavaSerializedObject) { - this.allowJavaSerializedObject = allowJavaSerializedObject; - } -" -309,1," private void updateGraph(ActionRequest actionRequest, - ActionResponse actionResponse) { - DBManager DBase = new DBManager(); - Connection con = DBase.getConnection(); - String graph_id = actionRequest.getParameter(""graph_id""); - actionResponse.setRenderParameter(""graph_id"", graph_id); - - String name = actionRequest.getParameter(""name""); - String description = actionRequest.getParameter(""description""); - String server_id = actionRequest.getParameter(""server_id""); - String xlabel = actionRequest.getParameter(""xlabel""); - String ylabel = actionRequest.getParameter(""ylabel""); - String timeframe = actionRequest.getParameter(""timeframe""); - String mbean = actionRequest.getParameter(""mbean""); - String dataname1 = actionRequest.getParameter(""dataname1""); - String data1operation = actionRequest.getParameter(""data1operation""); - String operation = actionRequest.getParameter(""operation""); - int archive = 0; - if (actionRequest.getParameter(""showArchive"") != null - && actionRequest.getParameter(""showArchive"").equals(""on"")) { - archive = 1; - } - - if (operation.equals(""other"")) { - operation = actionRequest.getParameter(""othermath""); - } - String dataname2 = actionRequest.getParameter(""dataname2""); - String data2operation = actionRequest.getParameter(""data2operation""); - if (data2operation == null) - data2operation = ""A""; - try { - PreparedStatement pStmt = con - .prepareStatement(""UPDATE graphs SET server_id="" - + server_id - + "", name='"" - + name - + ""', description='"" - + description - + ""', timeframe="" - + timeframe - + "", mbean='"" - + mbean - + ""', dataname1='"" - + dataname1 - + ""', xlabel='"" - + xlabel - + ""', ylabel='"" - + ylabel - + ""', data1operation='"" - + data1operation - + ""', operation='"" - + operation - + ""', data2operation='"" - + data2operation - + ""', dataname2='"" - + dataname2 - + ""', warninglevel1=0, warninglevel2=0, modified=CURRENT_TIMESTAMP, archive="" - + archive + "" WHERE graph_id="" + graph_id); - pStmt.executeUpdate(); - con.close(); - actionResponse.setRenderParameter(""message"", - ""Graph "" + name - + "" has been updated.""); - return; - - } catch (Exception e) { - actionResponse.setRenderParameter(""message"", - ""Error editing graph "" - + e.getMessage()); - return; - } - } - -" -310,1," protected void onSuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, Authentication authResult) throws IOException { - super.onSuccessfulAuthentication(request,response,authResult); - // make sure we have a session to store this successful authentication, given that we no longer - // let HttpSessionContextIntegrationFilter2 to create sessions. - // HttpSessionContextIntegrationFilter stores the updated SecurityContext object into this session later - // (either when a redirect is issued, via its HttpResponseWrapper, or when the execution returns to its - // doFilter method. - request.getSession(); - } - - /** - * Leave the information about login failure. - * - *

- * Otherwise it seems like Acegi doesn't really leave the detail of the failure anywhere. - */ - @Override -" -311,1," private Cache verifyCacheExists() { - int timeToWait = 0; - Cache cache = null; - while (timeToWait < TIME_TO_WAIT_FOR_CACHE) { - try { - cache = CacheFactory.getAnyInstance(); - break; - } catch (Exception ignore) { - // keep trying and hope for the best - } - try { - Thread.sleep(250); - } catch (InterruptedException ie) { - Thread.currentThread().interrupt(); - break; - } - timeToWait += 250; - } - - if (cache == null) { - cache = new CacheFactory().create(); - } - - return cache; - } - -" -312,1," public void clientCredentials_byDefault_WillNotLockoutDuringFailedBasicAuthAndFormData() throws Exception { - String clientId = ""testclient"" + generator.generate(); - String scopes = ""space.*.developer,space.*.admin,org.*.reader,org.123*.admin,*.*,*""; - setUpClients(clientId, scopes, scopes, GRANT_TYPES, true); - - String body = null; - for(int i = 0; i < 3; i++){ - body = getMockMvc().perform(post(""/oauth/token"") - .accept(MediaType.APPLICATION_JSON_VALUE) - .header(""Authorization"", ""Basic "" + new String(Base64.encode((clientId + "":"" + BADSECRET).getBytes()))) - .param(""grant_type"", ""client_credentials"") - ) - .andExpect(status().isUnauthorized()) - .andReturn().getResponse().getContentAsString(); - - body = getMockMvc().perform(post(""/oauth/token"") - .accept(MediaType.APPLICATION_JSON_VALUE) - .contentType(MediaType.APPLICATION_FORM_URLENCODED_VALUE) - .param(""grant_type"", ""client_credentials"") - .param(""client_id"", clientId) - .param(""client_secret"", BADSECRET) - ) - .andExpect(status().isUnauthorized()) - .andReturn().getResponse().getContentAsString(); - - } - - body = getMockMvc().perform(post(""/oauth/token"") - .accept(MediaType.APPLICATION_JSON_VALUE) - .header(""Authorization"", ""Basic "" + new String(Base64.encode((clientId + "":"" + SECRET).getBytes()))) - .param(""grant_type"", ""client_credentials"") - ) - .andExpect(status().isOk()) - .andReturn().getResponse().getContentAsString(); - } - - @Test -" -313,1," public String toStringInternal() { - String strValue=null; - try { - if( enc==null ) enc=DEFAULT_CHARACTER_ENCODING; - strValue = new String( buff, start, end-start, enc ); - /* - Does not improve the speed too much on most systems, - it's safer to use the ""clasical"" new String(). - - Most overhead is in creating char[] and copying, - the internal implementation of new String() is very close to - what we do. The decoder is nice for large buffers and if - we don't go to String ( so we can take advantage of reduced GC) - - // Method is commented out, in: - return B2CConverter.decodeString( enc ); - */ - } catch (java.io.UnsupportedEncodingException e) { - // Use the platform encoding in that case; the usage of a bad - // encoding will have been logged elsewhere already - strValue = new String(buff, start, end-start); - } - return strValue; - } - -" -314,1," public void repositoryVerificationTimeoutTest() throws Exception { - Client client = client(); - - Settings settings = ImmutableSettings.settingsBuilder() - .put(""location"", newTempDir(LifecycleScope.SUITE)) - .put(""random_control_io_exception_rate"", 1.0).build(); - logger.info(""--> creating repository that cannot write any files - should fail""); - assertThrows(client.admin().cluster().preparePutRepository(""test-repo-1"") - .setType(MockRepositoryModule.class.getCanonicalName()).setSettings(settings), - RepositoryVerificationException.class); - - logger.info(""--> creating repository that cannot write any files, but suppress verification - should be acked""); - assertAcked(client.admin().cluster().preparePutRepository(""test-repo-1"") - .setType(MockRepositoryModule.class.getCanonicalName()).setSettings(settings).setVerify(false)); - - logger.info(""--> verifying repository""); - assertThrows(client.admin().cluster().prepareVerifyRepository(""test-repo-1""), RepositoryVerificationException.class); - - File location = newTempDir(LifecycleScope.SUITE); - - logger.info(""--> creating repository""); - try { - client.admin().cluster().preparePutRepository(""test-repo-1"") - .setType(MockRepositoryModule.class.getCanonicalName()) - .setSettings(ImmutableSettings.settingsBuilder() - .put(""location"", location) - .put(""localize_location"", true) - ).get(); - fail(""RepositoryVerificationException wasn't generated""); - } catch (RepositoryVerificationException ex) { - assertThat(ex.getMessage(), containsString(""is not shared"")); - } - } - -" -315,1," public void execute(String key, ActionMapping mapping) { - String location = key.substring(REDIRECT_ACTION_PREFIX - .length()); - ServletRedirectResult redirect = new ServletRedirectResult(); - container.inject(redirect); - String extension = getDefaultExtension(); - if (extension != null && extension.length() > 0) { - location += ""."" + extension; - } - redirect.setLocation(location); - mapping.setResult(redirect); - } - }); - } - }; - } - - /** - * Adds a parameter action. Should only be called during initialization - * - * @param prefix The string prefix to trigger the action - * @param parameterAction The parameter action to execute - * @since 2.1.0 - */ -" -316,1," public void noUserSearchCausesUsernameNotFound() throws Exception { - DirContext ctx = mock(DirContext.class); - when(ctx.getNameInNamespace()).thenReturn(""""); - when(ctx.search(any(Name.class), any(String.class), any(Object[].class), any(SearchControls.class))) - .thenReturn(new EmptyEnumeration()); - - provider.contextFactory = createContextFactoryReturning(ctx); - - provider.authenticate(joe); - } - - @SuppressWarnings(""unchecked"") - @Test(expected = IncorrectResultSizeDataAccessException.class) -" -317,1," protected void addEmptyValueMapping(DefaultMapper mapper, String field, Object model) { - ParserContext parserContext = new FluentParserContext().evaluate(model.getClass()); - Expression target = expressionParser.parseExpression(field, parserContext); - try { - Class propertyType = target.getValueType(model); - Expression source = new StaticExpression(getEmptyValue(propertyType)); - DefaultMapping mapping = new DefaultMapping(source, target); - if (logger.isDebugEnabled()) { - logger.debug(""Adding empty value mapping for parameter '"" + field + ""'""); - } - mapper.addMapping(mapping); - } catch (EvaluationException e) { - } - } - - /** - * Adds a {@link DefaultMapping} between the given request parameter name and a matching model field. - * - * @param mapper the mapper to add the mapping to - * @param parameter the request parameter name - * @param model the model - */ -" -318,1," private boolean evaluate(String text) { - try { - InputSource inputSource = new InputSource(new StringReader(text)); - return ((Boolean)expression.evaluate(inputSource, XPathConstants.BOOLEAN)).booleanValue(); - } catch (XPathExpressionException e) { - return false; - } - } - - @Override -"