Unnamed: 0
int64 0
637
| label
int64 0
1
| code
stringlengths 24
8.83k
|
---|---|---|
400 | 0 | public Collection<ResourcePermission> 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<Group> 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<InputStream> 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<String> 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<ConstrainedField> constrainedFields = ConstrainedFieldBuilder.buildConstrainedFields(
bean.getField(),
beanClass,
defaultPackage,
constraintHelper,
annotationProcessingOptions
);
addConstrainedElements( beanClass, constrainedFields );
Set<ConstrainedExecutable> constrainedGetters = ConstrainedGetterBuilder.buildConstrainedGetters(
bean.getGetter(),
beanClass,
defaultPackage,
constraintHelper,
annotationProcessingOptions
);
addConstrainedElements( beanClass, constrainedGetters );
Set<ConstrainedExecutable> constrainedConstructors = ConstrainedExecutableBuilder.buildConstructorConstrainedExecutable(
bean.getConstructor(),
beanClass,
defaultPackage,
parameterNameProvider,
constraintHelper,
annotationProcessingOptions
);
addConstrainedElements( beanClass, constrainedConstructors );
Set<ConstrainedExecutable> 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<InternetAddress> to, Set<InternetAddress> cc, Set<InternetAddress> bcc) {
final class Debug implements RecipientProviderUtilities.IDebug {
private final ExtendedEmailPublisherDescriptor descriptor
= Jenkins.getActiveInstance().getDescriptorByType(ExtendedEmailPublisherDescriptor.class);
private final PrintStream logger = context.getListener().getLogger();
public void send(final String format, final Object... args) {
descriptor.debug(logger, format, args);
}
}
final Debug debug = new Debug();
Set<User> users = RecipientProviderUtilities.getChangeSetAuthors(Collections.<Run<?, ?>>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<Path>() {
@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 <T> Factory<T> prototypeFactory(final T prototype) {
if (prototype == null) {
return ConstantFactory.<T>constantFactory(null);
}
try {
final Method method = prototype.getClass().getMethod("clone", (Class[]) null);
return new PrototypeCloneFactory<T>(prototype, method);
} catch (final NoSuchMethodException ex) {
try {
prototype.getClass().getConstructor(new Class<?>[] { prototype.getClass() });
return new InstantiateFactory<T>(
(Class<T>) prototype.getClass(),
new Class<?>[] { prototype.getClass() },
new Object[] { prototype });
} catch (final NoSuchMethodException ex2) {
if (prototype instanceof Serializable) {
return (Factory<T>) new PrototypeSerializationFactory<Serializable>((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<BeanDefinition, BeanDefinition> parseInterceptUrlsForFilterInvocationRequestMap(
MatcherType matcherType, List<Element> urlElts, boolean useExpressions,
boolean addAuthenticatedAll, ParserContext parserContext) {
ManagedMap<BeanDefinition, BeanDefinition> filterInvocationDefinitionMap = new ManagedMap<BeanDefinition, BeanDefinition>();
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<ACL> getAclForPath(String path) {
List<ACL> 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<H> 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<String, String> headers = redirectionResponse.getHeaders();
if (!headers.isEmpty()) {
for (Entry<String, String> 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> T run(PrivilegedAction<T> action) {
return System.getSecurityManager() != null ? AccessController.doPrivileged( action ) : action.run();
}
|
445 | 1 | public void execute(FunctionContext context) {
ResultSender<Object> resultSender = context.getResultSender();
Cache cache = context.getCache();
String memberNameOrId = context.getMemberName();
RegionFunctionArgs regionCreateArgs = (RegionFunctionArgs) context.getArguments();
if (regionCreateArgs.isSkipIfExists()) {
Region<Object, Object> 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<Transform> transformList = new ArrayList<Transform>();
transformList.add(XML_SIGNATURE_FACTORY.newTransform(Transform.ENVELOPED, (TransformParameterSpec)null));
transformList.add(XML_SIGNATURE_FACTORY.newCanonicalizationMethod(CanonicalizationMethod.EXCLUSIVE,
(C14NMethodParameterSpec)null));
// Create a Reference to the enveloped document (in this case,
// you are signing the whole document, so a URI of "" signifies
// that, and also specify the SHA1 digest algorithm and
// the ENVELOPED Transform.
Reference ref = XML_SIGNATURE_FACTORY.newReference(
"#" + referenceID,
XML_SIGNATURE_FACTORY.newDigestMethod(DigestMethod.SHA1, null),
transformList,
null, null);
// Create the SignedInfo.
SignedInfo si = XML_SIGNATURE_FACTORY.newSignedInfo(
XML_SIGNATURE_FACTORY.newCanonicalizationMethod(
CanonicalizationMethod.EXCLUSIVE, (C14NMethodParameterSpec)null),
XML_SIGNATURE_FACTORY.newSignatureMethod(
signatureMethod, null), Collections.singletonList(ref));
// step 2
// Load the KeyStore and get the signing key and certificate.
PrivateKey keyEntry = crypto.getPrivateKey(keyAlias, keyPassword);
// Create the KeyInfo containing the X509Data.
KeyInfoFactory kif = XML_SIGNATURE_FACTORY.getKeyInfoFactory();
List<Object> x509Content = new ArrayList<Object>();
x509Content.add(cert.getSubjectX500Principal().getName());
x509Content.add(cert);
X509Data xd = kif.newX509Data(x509Content);
KeyInfo ki = kif.newKeyInfo(Collections.singletonList(xd));
// step3
// 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<File> 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<String> keys = (Set<String>) rfc.getFilter();
// Get local (primary) data for the context
Region primaryDataSet = PartitionRegionHelper.getLocalDataForContext(rfc);
if (this.cache.getLogger().fineEnabled()) {
StringBuilder builder = new StringBuilder();
builder.append("Function ").append(ID).append(" received request to touch ")
.append(primaryDataSet.getFullPath()).append("->").append(keys);
this.cache.getLogger().fine(builder.toString());
}
// Retrieve each value to update the lastAccessedTime.
// Note: getAll is not supported on LocalDataSet.
for (String key : keys) {
primaryDataSet.get(key);
}
// Return result to get around NPE in LocalResultCollectorImpl
context.getResultSender().lastResult(true);
}
|
451 | 1 | private static void unzip(final ZipFile zip, final Path targetDir) throws IOException {
final Enumeration<? extends ZipEntry> 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<RuntimeBeanReference> filterChain = new ManagedList<RuntimeBeanReference>(
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<String> 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<BeanMetadataElement> securityFilterChains = new ManagedList<BeanMetadataElement>();
Element elt = (Element) node;
MatcherType matcherType = MatcherType.fromElement(elt);
List<Element> 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> T run(PrivilegedAction<T> 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 =
"<random>" +
" <document>" +
" <node name=\"id\" value=\"12345\"/>" +
" <node name=\"name\" value=\"kitten\"/>" +
" <node name=\"text\" enhance=\"3\" value=\"some other day\"/>" +
" <node name=\"title\" enhance=\"4\" value=\"A story\"/>" +
" <node name=\"timestamp\" enhance=\"5\" value=\"2011-07-01T10:31:57.140Z\"/>" +
" </document>" +
"</random>";
Map<String,String> args = new HashMap<String, String>();
args.put(CommonParams.TR, "xsl-update-handler-test.xsl");
SolrCore core = h.getCore();
LocalSolrQueryRequest req = new LocalSolrQueryRequest( core, new MapSolrParams( args) );
ArrayList<ContentStream> streams = new ArrayList<ContentStream>();
streams.add(new ContentStreamBase.StringStream(xml));
req.setContentStreams(streams);
SolrQueryResponse rsp = new SolrQueryResponse();
UpdateRequestHandler handler = new UpdateRequestHandler();
handler.init(new NamedList<String>());
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<ContainerProvider> 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.
*
* <p>
* 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);
}
}
/**
* <p>Initialize the servlet mapping under which our controller servlet
* is being accessed. This will be used in the <code>&html:form></code>
* tag to generate correct destination URLs for form submissions.</p>
*
* @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<BeanDefinition, BeanDefinition> parseInterceptUrlsForChannelSecurity() {
ManagedMap<BeanDefinition, BeanDefinition> channelRequestMap = new ManagedMap<BeanDefinition, BeanDefinition>();
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.
* <p/>
* The default range is <tt>200-299</tt>
*/
|
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<Integer> 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> 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<User> users = ((AbstractBuild<?,?>)run).getCulprits();
RecipientProviderUtilities.addUsers(users, context.getListener(), env, to, cc, bcc, debug);
} else if (runResult != null) {
List<Run<?, ?>> 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<User> 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<InternetAddress> to, Set<InternetAddress> cc, Set<InternetAddress> bcc) {
final class Debug implements RecipientProviderUtilities.IDebug {
private final ExtendedEmailPublisherDescriptor descriptor
= Jenkins.getActiveInstance().getDescriptorByType(ExtendedEmailPublisherDescriptor.class);
private final PrintStream logger = context.getListener().getLogger();
public void send(final String format, final Object... args) {
descriptor.debug(logger, format, args);
}
}
final Debug debug = new Debug();
// 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<NioChannel> 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<User> users, final TaskListener listener, final EnvVars env,
final Set<InternetAddress> to, final Set<InternetAddress> cc, final Set<InternetAddress> 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.
* <p>
* <b>Limitations:</b> 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.
* </p>
*
* @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<String> 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"))));
}
|