Unnamed: 0
int64 0
637
| label
int64 0
1
| code
stringlengths 24
8.83k
|
---|---|---|
600 | 1 | public void testTrustedMethodPrevention() {
Response response = WebClient.create(endPoint + TIKA_PATH)
.type("application/pdf")
.accept("text/plain")
.header(TikaResource.X_TIKA_OCR_HEADER_PREFIX +
"trustedPageSeparator",
"\u0010")
.put(ClassLoader.getSystemResourceAsStream("testOCR.pdf"));
assertEquals(500, response.getStatus());
}
|
601 | 1 | public void performTest()
throws Exception
{
testCompat();
testNONEwithDSA();
testDSAsha3(NISTObjectIdentifiers.id_dsa_with_sha3_224, 224, new BigInteger("613202af2a7f77e02b11b5c3a5311cf6b412192bc0032aac3ec127faebfc6bd0", 16));
testDSAsha3(NISTObjectIdentifiers.id_dsa_with_sha3_256, 256, new BigInteger("2450755c5e15a691b121bc833b97864e34a61ee025ecec89289c949c1858091e", 16));
testDSAsha3(NISTObjectIdentifiers.id_dsa_with_sha3_384, 384, new BigInteger("7aad97c0b71bb1e1a6483b6948a03bbe952e4780b0cee699a11731f90d84ddd1", 16));
testDSAsha3(NISTObjectIdentifiers.id_dsa_with_sha3_512, 512, new BigInteger("725ad64d923c668e64e7c3898b5efde484cab49ce7f98c2885d2a13a9e355ad4", 16));
testECDSA239bitPrime();
testNONEwithECDSA239bitPrime();
testECDSA239bitBinary();
testECDSA239bitBinary("RIPEMD160withECDSA", TeleTrusTObjectIdentifiers.ecSignWithRipemd160);
testECDSA239bitBinary("SHA1withECDSA", TeleTrusTObjectIdentifiers.ecSignWithSha1);
testECDSA239bitBinary("SHA224withECDSA", X9ObjectIdentifiers.ecdsa_with_SHA224);
testECDSA239bitBinary("SHA256withECDSA", X9ObjectIdentifiers.ecdsa_with_SHA256);
testECDSA239bitBinary("SHA384withECDSA", X9ObjectIdentifiers.ecdsa_with_SHA384);
testECDSA239bitBinary("SHA512withECDSA", X9ObjectIdentifiers.ecdsa_with_SHA512);
testECDSA239bitBinary("SHA1withCVC-ECDSA", EACObjectIdentifiers.id_TA_ECDSA_SHA_1);
testECDSA239bitBinary("SHA224withCVC-ECDSA", EACObjectIdentifiers.id_TA_ECDSA_SHA_224);
testECDSA239bitBinary("SHA256withCVC-ECDSA", EACObjectIdentifiers.id_TA_ECDSA_SHA_256);
testECDSA239bitBinary("SHA384withCVC-ECDSA", EACObjectIdentifiers.id_TA_ECDSA_SHA_384);
testECDSA239bitBinary("SHA512withCVC-ECDSA", EACObjectIdentifiers.id_TA_ECDSA_SHA_512);
testECDSAP256sha3(NISTObjectIdentifiers.id_ecdsa_with_sha3_224, 224, new BigInteger("84d7d8e68e405064109cd9fc3e3026d74d278aada14ce6b7a9dd0380c154dc94", 16));
testECDSAP256sha3(NISTObjectIdentifiers.id_ecdsa_with_sha3_256, 256, new BigInteger("99a43bdab4af989aaf2899079375642f2bae2dce05bcd8b72ec8c4a8d9a143f", 16));
testECDSAP256sha3(NISTObjectIdentifiers.id_ecdsa_with_sha3_384, 384, new BigInteger("aa27726509c37aaf601de6f7e01e11c19add99530c9848381c23365dc505b11a", 16));
testECDSAP256sha3(NISTObjectIdentifiers.id_ecdsa_with_sha3_512, 512, new BigInteger("f8306b57a1f5068bf12e53aabaae39e2658db39bc56747eaefb479995130ad16", 16));
testGeneration();
testParameters();
testDSA2Parameters();
testNullParameters();
testValidate();
testModified();
}
|
602 | 1 | public void snapshotRecoveryTest() throws Exception {
logger.info("--> start node A");
String nodeA = internalCluster().startNode(settingsBuilder().put("gateway.type", "local"));
logger.info("--> create repository");
assertAcked(client().admin().cluster().preparePutRepository(REPO_NAME)
.setType("fs").setSettings(ImmutableSettings.settingsBuilder()
.put("location", newTempDir(LifecycleScope.SUITE))
.put("compress", false)
).get());
ensureGreen();
logger.info("--> create index on node: {}", nodeA);
createAndPopulateIndex(INDEX_NAME, 1, SHARD_COUNT, REPLICA_COUNT);
logger.info("--> snapshot");
CreateSnapshotResponse createSnapshotResponse = client().admin().cluster().prepareCreateSnapshot(REPO_NAME, SNAP_NAME)
.setWaitForCompletion(true).setIndices(INDEX_NAME).get();
assertThat(createSnapshotResponse.getSnapshotInfo().successfulShards(), greaterThan(0));
assertThat(createSnapshotResponse.getSnapshotInfo().successfulShards(), equalTo(createSnapshotResponse.getSnapshotInfo().totalShards()));
assertThat(client().admin().cluster().prepareGetSnapshots(REPO_NAME).setSnapshots(SNAP_NAME).get()
.getSnapshots().get(0).state(), equalTo(SnapshotState.SUCCESS));
client().admin().indices().prepareClose(INDEX_NAME).execute().actionGet();
logger.info("--> restore");
RestoreSnapshotResponse restoreSnapshotResponse = client().admin().cluster()
.prepareRestoreSnapshot(REPO_NAME, SNAP_NAME).setWaitForCompletion(true).execute().actionGet();
int totalShards = restoreSnapshotResponse.getRestoreInfo().totalShards();
assertThat(totalShards, greaterThan(0));
ensureGreen();
logger.info("--> request recoveries");
RecoveryResponse response = client().admin().indices().prepareRecoveries(INDEX_NAME).execute().actionGet();
for (Map.Entry<String, List<ShardRecoveryResponse>> shardRecoveryResponse : response.shardResponses().entrySet()) {
assertThat(shardRecoveryResponse.getKey(), equalTo(INDEX_NAME));
List<ShardRecoveryResponse> shardRecoveryResponses = shardRecoveryResponse.getValue();
assertThat(shardRecoveryResponses.size(), equalTo(totalShards));
for (ShardRecoveryResponse shardResponse : shardRecoveryResponses) {
assertRecoveryState(shardResponse.recoveryState(), 0, Type.SNAPSHOT, Stage.DONE, null, nodeA, true);
validateIndexRecoveryState(shardResponse.recoveryState().getIndex());
}
}
}
|
603 | 1 | public synchronized Principal authenticate(Connection dbConnection,
String username,
String credentials) {
// No user or no credentials
// Can't possibly authenticate, don't bother the database then
if (username == null || credentials == null) {
if (containerLog.isTraceEnabled())
containerLog.trace(sm.getString("jdbcRealm.authenticateFailure",
username));
return null;
}
// Look up the user's credentials
String dbCredentials = getPassword(username);
if (dbCredentials == null) {
// User was not found in the database.
if (containerLog.isTraceEnabled())
containerLog.trace(sm.getString("jdbcRealm.authenticateFailure",
username));
return null;
}
// Validate the user's credentials
boolean validated = getCredentialHandler().matches(credentials, dbCredentials);
if (validated) {
if (containerLog.isTraceEnabled())
containerLog.trace(sm.getString("jdbcRealm.authenticateSuccess",
username));
} else {
if (containerLog.isTraceEnabled())
containerLog.trace(sm.getString("jdbcRealm.authenticateFailure",
username));
return null;
}
ArrayList<String> roles = getRoles(username);
// Create and return a suitable Principal for this user
return (new GenericPrincipal(username, credentials, roles));
}
/**
* Close the specified database connection.
*
* @param dbConnection The connection to be closed
*/
|
604 | 1 | public void performTest()
throws Exception
{
byte[] testIv = { 1, 2, 3, 4, 5, 6, 7, 8 };
ASN1Encodable[] values = {
new CAST5CBCParameters(testIv, 128),
new NetscapeCertType(NetscapeCertType.smime),
new VerisignCzagExtension(new DERIA5String("hello")),
new IDEACBCPar(testIv),
new NetscapeRevocationURL(new DERIA5String("http://test"))
};
byte[] data = Base64.decode("MA4ECAECAwQFBgcIAgIAgAMCBSAWBWhlbGxvMAoECAECAwQFBgcIFgtodHRwOi8vdGVzdA==");
ByteArrayOutputStream bOut = new ByteArrayOutputStream();
ASN1OutputStream aOut = new ASN1OutputStream(bOut);
for (int i = 0; i != values.length; i++)
{
aOut.writeObject(values[i]);
}
ASN1Primitive[] readValues = new ASN1Primitive[values.length];
if (!isSameAs(bOut.toByteArray(), data))
{
fail("Failed data check");
}
ByteArrayInputStream bIn = new ByteArrayInputStream(bOut.toByteArray());
ASN1InputStream aIn = new ASN1InputStream(bIn);
for (int i = 0; i != values.length; i++)
{
ASN1Primitive o = aIn.readObject();
if (!values[i].equals(o))
{
fail("Failed equality test for " + o);
}
if (o.hashCode() != values[i].hashCode())
{
fail("Failed hashCode test for " + o);
}
}
shouldFailOnExtraData();
}
|
605 | 1 | public void setEncoding( String enc ) {
if( !byteC.isNull() ) {
// if the encoding changes we need to reset the converion results
charC.recycle();
hasStrValue=false;
}
byteC.setEncoding(enc);
}
/**
* Sets the content to be a char[]
*
* @param c the bytes
* @param off the start offset of the bytes
* @param len the length of the bytes
*/
|
606 | 1 | protected String buildErrorMessage(Throwable e, Object[] args) {
String errorKey = "struts.messages.upload.error." + e.getClass().getSimpleName();
if (LOG.isDebugEnabled()) {
LOG.debug("Preparing error message for key: [#0]", errorKey);
}
return LocalizedTextUtil.findText(this.getClass(), errorKey, defaultLocale, e.getMessage(), args);
}
|
607 | 1 | private BigInteger[] derDecode(
byte[] encoding)
throws IOException
{
ASN1Sequence s = (ASN1Sequence)ASN1Primitive.fromByteArray(encoding);
if (s.size() != 2)
{
throw new IOException("malformed signature");
}
return new BigInteger[]{
((ASN1Integer)s.getObjectAt(0)).getValue(),
((ASN1Integer)s.getObjectAt(1)).getValue()
};
}
|
608 | 1 | public String encodeCharacter( char[] immune, Character c )
{
String cStr = String.valueOf(c.charValue());
byte[] bytes;
StringBuilder sb;
if(UNENCODED_SET.contains(c))
return cStr;
bytes = toUtf8Bytes(cStr);
sb = new StringBuilder(bytes.length * 3);
for(byte b : bytes)
appendTwoUpperHex(sb.append('%'), b);
return sb.toString();
}
/**
* {@inheritDoc}
*
* Formats all are legal both upper/lower case:
* %hh;
*
* @param input
* encoded character using percent characters (such as URL encoding)
*/
|
609 | 1 | protected void setAuthenticateHeader(Request request,
Response response,
LoginConfig config,
String nOnce) {
// Get the realm name
String realmName = config.getRealmName();
if (realmName == null)
realmName = REALM_NAME;
byte[] buffer = null;
synchronized (md5Helper) {
buffer = md5Helper.digest(nOnce.getBytes());
}
String authenticateHeader = "Digest realm=\"" + realmName + "\", "
+ "qop=\"auth\", nonce=\"" + nOnce + "\", " + "opaque=\""
+ md5Encoder.encode(buffer) + "\"";
response.setHeader("WWW-Authenticate", authenticateHeader);
}
|
610 | 1 | private Foo writeAndRead(Foo foo) throws IOException, ClassNotFoundException {
writeObject(oos, foo);
ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
inputStream = new ObjectInputStream(bis);
Foo fooBack = readFooObject(inputStream);
inputStream.close();
return fooBack;
}
|
611 | 1 | private static void processHeaderConfig(MultivaluedMap<String, String> httpHeaders, Object object, String key, String prefix) {
try {
String property = StringUtils.removeStart(key, prefix);
Field field = null;
try {
object.getClass().getDeclaredField(StringUtils.uncapitalize(property));
} catch (NoSuchFieldException e) {
//swallow
}
String setter = property;
setter = "set"+setter.substring(0,1).toUpperCase(Locale.US)+setter.substring(1);
//default assume string class
//if there's a more specific type, e.g. double, int, boolean
//try that.
Class clazz = String.class;
if (field != null) {
if (field.getType() == int.class) {
clazz = int.class;
} else if (field.getType() == double.class) {
clazz = double.class;
} else if (field.getType() == boolean.class) {
clazz = boolean.class;
}
}
Method m = tryToGetMethod(object, setter, clazz);
//if you couldn't find more specific setter, back off
//to string setter and try that.
if (m == null && clazz != String.class) {
m = tryToGetMethod(object, setter, String.class);
}
if (m != null) {
String val = httpHeaders.getFirst(key);
val = val.trim();
if (clazz == String.class) {
checkTrustWorthy(setter, val);
m.invoke(object, val);
} else if (clazz == int.class) {
m.invoke(object, Integer.parseInt(val));
} else if (clazz == double.class) {
m.invoke(object, Double.parseDouble(val));
} else if (clazz == boolean.class) {
m.invoke(object, Boolean.parseBoolean(val));
} else {
throw new IllegalArgumentException("setter must be String, int, double or boolean...for now");
}
} else {
throw new NoSuchMethodException("Couldn't find: "+setter);
}
} catch (Throwable ex) {
throw new WebApplicationException(String.format(Locale.ROOT,
"%s is an invalid %s header", key, X_TIKA_OCR_HEADER_PREFIX));
}
}
|
612 | 1 | public KeystoreInstance createKeystore(String name, char[] password, String keystoreType) throws KeystoreException {
File test = new File(directory, name);
if(test.exists()) {
throw new IllegalArgumentException("Keystore already exists "+test.getAbsolutePath()+"!");
}
try {
KeyStore keystore = KeyStore.getInstance(keystoreType);
keystore.load(null, password);
OutputStream out = new BufferedOutputStream(new FileOutputStream(test));
keystore.store(out, password);
out.flush();
out.close();
return getKeystore(name, keystoreType);
} catch (KeyStoreException e) {
throw new KeystoreException("Unable to create keystore", e);
} catch (IOException e) {
throw new KeystoreException("Unable to create keystore", e);
} catch (NoSuchAlgorithmException e) {
throw new KeystoreException("Unable to create keystore", e);
} catch (CertificateException e) {
throw new KeystoreException("Unable to create keystore", e);
}
}
|
613 | 1 | public void setDefaultLockoutPolicy(LockoutPolicy defaultLockoutPolicy) {
this.defaultLockoutPolicy = defaultLockoutPolicy;
}
|
614 | 1 | protected void initializeFilters(int maxTrailerSize) {
// Create and add the identity filters.
getInputBuffer().addFilter(new IdentityInputFilter());
getOutputBuffer().addFilter(new IdentityOutputFilter());
// Create and add the chunked filters.
getInputBuffer().addFilter(new ChunkedInputFilter(maxTrailerSize));
getOutputBuffer().addFilter(new ChunkedOutputFilter());
// Create and add the void filters.
getInputBuffer().addFilter(new VoidInputFilter());
getOutputBuffer().addFilter(new VoidOutputFilter());
// Create and add buffered input filter
getInputBuffer().addFilter(new BufferedInputFilter());
// Create and add the chunked filters.
//getInputBuffer().addFilter(new GzipInputFilter());
getOutputBuffer().addFilter(new GzipOutputFilter());
pluggableFilterIndex = getInputBuffer().getFilters().length;
}
/**
* Add an input filter to the current request.
*
* @return false if the encoding was not found (which would mean it is
* unsupported)
*/
|
615 | 1 | private BeanReference createSecurityFilterChainBean(Element element,
ParserContext pc, List<?> filterChain) {
BeanMetadataElement filterChainMatcher;
String requestMatcherRef = element.getAttribute(ATT_REQUEST_MATCHER_REF);
String filterChainPattern = element.getAttribute(ATT_PATH_PATTERN);
if (StringUtils.hasText(requestMatcherRef)) {
if (StringUtils.hasText(filterChainPattern)) {
pc.getReaderContext().error(
"You can't define a pattern and a request-matcher-ref for the "
+ "same filter chain", pc.extractSource(element));
}
filterChainMatcher = new RuntimeBeanReference(requestMatcherRef);
}
else if (StringUtils.hasText(filterChainPattern)) {
filterChainMatcher = MatcherType.fromElement(element).createMatcher(
filterChainPattern, null);
}
else {
filterChainMatcher = new RootBeanDefinition(AnyRequestMatcher.class);
}
BeanDefinitionBuilder filterChainBldr = BeanDefinitionBuilder
.rootBeanDefinition(DefaultSecurityFilterChain.class);
filterChainBldr.addConstructorArgValue(filterChainMatcher);
filterChainBldr.addConstructorArgValue(filterChain);
BeanDefinition filterChainBean = filterChainBldr.getBeanDefinition();
String id = element.getAttribute("name");
if (!StringUtils.hasText(id)) {
id = element.getAttribute("id");
if (!StringUtils.hasText(id)) {
id = pc.getReaderContext().generateBeanName(filterChainBean);
}
}
pc.registerBeanComponent(new BeanComponentDefinition(filterChainBean, id));
return new RuntimeBeanReference(id);
}
|
616 | 1 | public boolean check(String path, Resource resource)
{
int slash = path.lastIndexOf('/');
if (slash<0)
return false;
String suffix=path.substring(slash);
return resource.getAlias().toString().endsWith(suffix);
}
}
}
|
617 | 1 | public Mapper getMapper() {
return (mapper);
}
/**
* Return the maximum size of a POST which will be automatically
* parsed by the container.
*/
|
618 | 1 | public Object getValue(Object parent) {
return ( (Object[]) parent )[index];
}
@Override
|
619 | 1 | public String createDB(String dbName) {
String result = DB_CREATED_MSG + ": " + dbName;
Connection conn = null;
try {
conn = DerbyConnectionUtil.getDerbyConnection(dbName,
DerbyConnectionUtil.CREATE_DB_PROP);
} catch (Throwable e) {
if (e instanceof SQLException) {
result = getSQLError((SQLException) e);
} else {
result = e.getMessage();
}
} finally {
// close DB connection
try {
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
result = "Problem closing DB connection";
}
}
return result;
}
|
620 | 1 | public URL resolveConfig(String path) throws FailedToResolveConfigException {
String origPath = path;
// first, try it as a path on the file system
File f1 = new File(path);
if (f1.exists()) {
try {
return f1.toURI().toURL();
} catch (MalformedURLException e) {
throw new FailedToResolveConfigException("Failed to resolve path [" + f1 + "]", e);
}
}
if (path.startsWith("/")) {
path = path.substring(1);
}
// next, try it relative to the config location
File f2 = new File(configFile, path);
if (f2.exists()) {
try {
return f2.toURI().toURL();
} catch (MalformedURLException e) {
throw new FailedToResolveConfigException("Failed to resolve path [" + f2 + "]", e);
}
}
// try and load it from the classpath directly
URL resource = settings.getClassLoader().getResource(path);
if (resource != null) {
return resource;
}
// try and load it from the classpath with config/ prefix
if (!path.startsWith("config/")) {
resource = settings.getClassLoader().getResource("config/" + path);
if (resource != null) {
return resource;
}
}
throw new FailedToResolveConfigException("Failed to resolve config path [" + origPath + "], tried file path [" + f1 + "], path file [" + f2 + "], and classpath");
}
|
621 | 1 | public static boolean normalize(MessageBytes uriMB) {
ByteChunk uriBC = uriMB.getByteChunk();
byte[] b = uriBC.getBytes();
int start = uriBC.getStart();
int end = uriBC.getEnd();
// URL * is acceptable
if ((end - start == 1) && b[start] == (byte) '*')
return true;
int pos = 0;
int index = 0;
// Replace '\' with '/'
// Check for null byte
for (pos = start; pos < end; pos++) {
if (b[pos] == (byte) '\\')
b[pos] = (byte) '/';
if (b[pos] == (byte) 0)
return false;
}
// The URL must start with '/'
if (b[start] != (byte) '/') {
return false;
}
// Replace "//" with "/"
for (pos = start; pos < (end - 1); pos++) {
if (b[pos] == (byte) '/') {
while ((pos + 1 < end) && (b[pos + 1] == (byte) '/')) {
copyBytes(b, pos, pos + 1, end - pos - 1);
end--;
}
}
}
// If the URI ends with "/." or "/..", then we append an extra "/"
// Note: It is possible to extend the URI by 1 without any side effect
// as the next character is a non-significant WS.
if (((end - start) >= 2) && (b[end - 1] == (byte) '.')) {
if ((b[end - 2] == (byte) '/')
|| ((b[end - 2] == (byte) '.')
&& (b[end - 3] == (byte) '/'))) {
b[end] = (byte) '/';
end++;
}
}
uriBC.setEnd(end);
index = 0;
// Resolve occurrences of "/./" in the normalized path
while (true) {
index = uriBC.indexOf("/./", 0, 3, index);
if (index < 0)
break;
copyBytes(b, start + index, start + index + 2,
end - start - index - 2);
end = end - 2;
uriBC.setEnd(end);
}
index = 0;
// Resolve occurrences of "/../" in the normalized path
while (true) {
index = uriBC.indexOf("/../", 0, 4, index);
if (index < 0)
break;
// Prevent from going outside our context
if (index == 0)
return false;
int index2 = -1;
for (pos = start + index - 1; (pos >= 0) && (index2 < 0); pos --) {
if (b[pos] == (byte) '/') {
index2 = pos;
}
}
copyBytes(b, start + index2, start + index + 3,
end - start - index - 3);
end = end + index2 - index - 3;
uriBC.setEnd(end);
index = index2;
}
uriBC.setBytes(b, start, end);
return true;
}
// ------------------------------------------------------ Protected Methods
/**
* Copy an array of bytes to a different position. Used during
* normalization.
*/
|
622 | 1 | protected void handShake() throws IOException {
ssl.setNeedClientAuth(true);
ssl.startHandshake();
}
/**
* Copied from <code>org.apache.catalina.valves.CertificateValve</code>
*/
|
623 | 1 | public void testIssue1599() throws Exception
{
final String JSON = aposToQuotes(
"{'id': 124,\n"
+" 'obj':[ 'com.sun.org.apache.xalan.internal.xsltc.trax.TemplatesImpl',\n"
+" {\n"
+" 'transletBytecodes' : [ 'AAIAZQ==' ],\n"
+" 'transletName' : 'a.b',\n"
+" 'outputProperties' : { }\n"
+" }\n"
+" ]\n"
+"}"
);
ObjectMapper mapper = new ObjectMapper();
mapper.enableDefaultTyping();
try {
mapper.readValue(JSON, Bean1599.class);
fail("Should not pass");
} catch (JsonMappingException e) {
verifyException(e, "Illegal type");
verifyException(e, "to deserialize");
verifyException(e, "prevented for security reasons");
}
}
|
624 | 1 | public void testWildcardBehaviour_snapshotRestore() throws Exception {
createIndex("foobar");
ensureGreen("foobar");
waitForRelocation();
PutRepositoryResponse putRepositoryResponse = client().admin().cluster().preparePutRepository("dummy-repo")
.setType("fs").setSettings(ImmutableSettings.settingsBuilder().put("location", newTempDir())).get();
assertThat(putRepositoryResponse.isAcknowledged(), equalTo(true));
client().admin().cluster().prepareCreateSnapshot("dummy-repo", "snap1").setWaitForCompletion(true).get();
IndicesOptions options = IndicesOptions.fromOptions(false, false, true, false);
verify(snapshot("snap2", "foo*", "bar*").setIndicesOptions(options), true);
verify(restore("snap1", "foo*", "bar*").setIndicesOptions(options), true);
options = IndicesOptions.strictExpandOpen();
verify(snapshot("snap2", "foo*", "bar*").setIndicesOptions(options), false);
verify(restore("snap2", "foo*", "bar*").setIndicesOptions(options), false);
assertAcked(prepareCreate("barbaz"));
//TODO: temporary work-around for #5531
ensureGreen("barbaz");
waitForRelocation();
options = IndicesOptions.fromOptions(false, false, true, false);
verify(snapshot("snap3", "foo*", "bar*").setIndicesOptions(options), false);
verify(restore("snap3", "foo*", "bar*").setIndicesOptions(options), false);
options = IndicesOptions.fromOptions(false, false, true, false);
verify(snapshot("snap4", "foo*", "baz*").setIndicesOptions(options), true);
verify(restore("snap3", "foo*", "baz*").setIndicesOptions(options), true);
}
@Test
|
625 | 1 | public synchronized JettyHttpBinding getJettyBinding(HttpClient httpClient) {
if (jettyBinding == null) {
jettyBinding = new DefaultJettyHttpBinding();
jettyBinding.setHeaderFilterStrategy(getHeaderFilterStrategy());
jettyBinding.setThrowExceptionOnFailure(isThrowExceptionOnFailure());
jettyBinding.setTransferException(isTransferException());
jettyBinding.setOkStatusCodeRange(getOkStatusCodeRange());
}
return jettyBinding;
}
|
626 | 1 | protected final String getWindowOpenJavaScript()
{
AppendingStringBuffer buffer = new AppendingStringBuffer(500);
if (isCustomComponent() == true)
{
buffer.append("var element = document.getElementById(\"");
buffer.append(getContentMarkupId());
buffer.append("\");\n");
}
buffer.append("var settings = new Object();\n");
appendAssignment(buffer, "settings.minWidth", getMinimalWidth());
appendAssignment(buffer, "settings.minHeight", getMinimalHeight());
appendAssignment(buffer, "settings.className", getCssClassName());
appendAssignment(buffer, "settings.width", getInitialWidth());
if ((isUseInitialHeight() == true) || (isCustomComponent() == false))
{
appendAssignment(buffer, "settings.height", getInitialHeight());
}
else
{
buffer.append("settings.height=null;\n");
}
appendAssignment(buffer, "settings.resizable", isResizable());
if (isResizable() == false)
{
appendAssignment(buffer, "settings.widthUnit", getWidthUnit());
appendAssignment(buffer, "settings.heightUnit", getHeightUnit());
}
if (isCustomComponent() == false)
{
Page page = createPage();
if (page == null)
{
throw new WicketRuntimeException("Error creating page for modal dialog.");
}
CharSequence pageUrl;
RequestCycle requestCycle = RequestCycle.get();
page.getSession().getPageManager().touchPage(page);
if (page.isPageStateless())
{
pageUrl = requestCycle.urlFor(page.getClass(), page.getPageParameters());
}
else
{
IRequestHandler handler = new RenderPageRequestHandler(new PageProvider(page));
pageUrl = requestCycle.urlFor(handler);
}
appendAssignment(buffer, "settings.src", pageUrl);
}
else
{
buffer.append("settings.element=element;\n");
}
if (getCookieName() != null)
{
appendAssignment(buffer, "settings.cookieId", getCookieName());
}
Object title = getTitle() != null ? getTitle().getObject() : null;
if (title != null)
{
appendAssignment(buffer, "settings.title", escapeQuotes(title.toString()));
}
if (getMaskType() == MaskType.TRANSPARENT)
{
buffer.append("settings.mask=\"transparent\";\n");
}
else if (getMaskType() == MaskType.SEMI_TRANSPARENT)
{
buffer.append("settings.mask=\"semi-transparent\";\n");
}
appendAssignment(buffer, "settings.autoSize", autoSize);
appendAssignment(buffer, "settings.unloadConfirmation", showUnloadConfirmation());
// set true if we set a windowclosedcallback
boolean haveCloseCallback = false;
// in case user is interested in window close callback or we have a pagemap to clean attach
// notification request
if (windowClosedCallback != null)
{
WindowClosedBehavior behavior = getBehaviors(WindowClosedBehavior.class).get(0);
buffer.append("settings.onClose = function() { ");
buffer.append(behavior.getCallbackScript());
buffer.append(" };\n");
haveCloseCallback = true;
}
// in case we didn't set windowclosecallback, we need at least callback on close button, to
// close window property (thus cleaning the shown flag)
if ((closeButtonCallback != null) || (haveCloseCallback == false))
{
CloseButtonBehavior behavior = getBehaviors(CloseButtonBehavior.class).get(0);
buffer.append("settings.onCloseButton = function() { ");
buffer.append(behavior.getCallbackScript());
buffer.append(";return false;};\n");
}
postProcessSettings(buffer);
buffer.append(getShowJavaScript());
return buffer.toString();
}
/**
*
* @param buffer
* @param key
* @param value
*/
|
627 | 1 | private void addUserFromChangeSet(ChangeLogSet.Entry change, Set<InternetAddress> to, Set<InternetAddress> cc, Set<InternetAddress> bcc, EnvVars env, TaskListener listener, RecipientProviderUtilities.IDebug debug) {
User user = change.getAuthor();
RecipientProviderUtilities.addUsers(Collections.singleton(user), listener, env, to, cc, bcc, debug);
}
@Extension
|
628 | 1 | public final void parse(Set<InputStream> mappingStreams) {
try {
JAXBContext jc = JAXBContext.newInstance( 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 );
}
}
|
629 | 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();
Set<User> users = RecipientProviderUtilities.getChangeSetAuthors(Collections.<Run<?, ?>>singleton(context.getRun()), debug);
RecipientProviderUtilities.addUsers(users, context.getListener(), env, to, cc, bcc, debug);
}
@Extension
|
630 | 1 | private boolean evaluate(String text) {
try {
InputSource inputSource = new InputSource(new StringReader(text));
return ((Boolean)expression.evaluate(inputSource, XPathConstants.BOOLEAN)).booleanValue();
} catch (XPathExpressionException e) {
return false;
}
}
@Override
|
631 | 1 | public void basicWorkFlowTest() throws Exception {
Client client = client();
logger.info("--> creating repository");
assertAcked(client.admin().cluster().preparePutRepository("test-repo")
.setType("fs").setSettings(ImmutableSettings.settingsBuilder()
.put("location", newTempDir())
.put("compress", randomBoolean())
.put("chunk_size", randomIntBetween(100, 1000))));
createIndex("test-idx-1", "test-idx-2", "test-idx-3");
ensureGreen();
logger.info("--> indexing some data");
for (int i = 0; i < 100; i++) {
index("test-idx-1", "doc", Integer.toString(i), "foo", "bar" + i);
index("test-idx-2", "doc", Integer.toString(i), "foo", "baz" + i);
index("test-idx-3", "doc", Integer.toString(i), "foo", "baz" + i);
}
refresh();
assertHitCount(client.prepareCount("test-idx-1").get(), 100L);
assertHitCount(client.prepareCount("test-idx-2").get(), 100L);
assertHitCount(client.prepareCount("test-idx-3").get(), 100L);
ListenableActionFuture<FlushResponse> flushResponseFuture = null;
if (randomBoolean()) {
ArrayList<String> indicesToFlush = newArrayList();
for (int i = 1; i < 4; i++) {
if (randomBoolean()) {
indicesToFlush.add("test-idx-" + i);
}
}
if (!indicesToFlush.isEmpty()) {
String[] indices = indicesToFlush.toArray(new String[indicesToFlush.size()]);
logger.info("--> starting asynchronous flush for indices {}", Arrays.toString(indices));
flushResponseFuture = client.admin().indices().prepareFlush(indices).execute();
}
}
logger.info("--> snapshot");
CreateSnapshotResponse createSnapshotResponse = client.admin().cluster().prepareCreateSnapshot("test-repo", "test-snap").setWaitForCompletion(true).setIndices("test-idx-*", "-test-idx-3").get();
assertThat(createSnapshotResponse.getSnapshotInfo().successfulShards(), greaterThan(0));
assertThat(createSnapshotResponse.getSnapshotInfo().successfulShards(), equalTo(createSnapshotResponse.getSnapshotInfo().totalShards()));
assertThat(client.admin().cluster().prepareGetSnapshots("test-repo").setSnapshots("test-snap").get().getSnapshots().get(0).state(), equalTo(SnapshotState.SUCCESS));
logger.info("--> delete some data");
for (int i = 0; i < 50; i++) {
client.prepareDelete("test-idx-1", "doc", Integer.toString(i)).get();
}
for (int i = 50; i < 100; i++) {
client.prepareDelete("test-idx-2", "doc", Integer.toString(i)).get();
}
for (int i = 0; i < 100; i += 2) {
client.prepareDelete("test-idx-3", "doc", Integer.toString(i)).get();
}
refresh();
assertHitCount(client.prepareCount("test-idx-1").get(), 50L);
assertHitCount(client.prepareCount("test-idx-2").get(), 50L);
assertHitCount(client.prepareCount("test-idx-3").get(), 50L);
logger.info("--> close indices");
client.admin().indices().prepareClose("test-idx-1", "test-idx-2").get();
logger.info("--> restore all indices from the snapshot");
RestoreSnapshotResponse restoreSnapshotResponse = client.admin().cluster().prepareRestoreSnapshot("test-repo", "test-snap").setWaitForCompletion(true).execute().actionGet();
assertThat(restoreSnapshotResponse.getRestoreInfo().totalShards(), greaterThan(0));
ensureGreen();
for (int i=0; i<5; i++) {
assertHitCount(client.prepareCount("test-idx-1").get(), 100L);
assertHitCount(client.prepareCount("test-idx-2").get(), 100L);
assertHitCount(client.prepareCount("test-idx-3").get(), 50L);
}
// Test restore after index deletion
logger.info("--> delete indices");
cluster().wipeIndices("test-idx-1", "test-idx-2");
logger.info("--> restore one index after deletion");
restoreSnapshotResponse = client.admin().cluster().prepareRestoreSnapshot("test-repo", "test-snap").setWaitForCompletion(true).setIndices("test-idx-*", "-test-idx-2").execute().actionGet();
assertThat(restoreSnapshotResponse.getRestoreInfo().totalShards(), greaterThan(0));
ensureGreen();
for (int i=0; i<5; i++) {
assertHitCount(client.prepareCount("test-idx-1").get(), 100L);
}
ClusterState clusterState = client.admin().cluster().prepareState().get().getState();
assertThat(clusterState.getMetaData().hasIndex("test-idx-1"), equalTo(true));
assertThat(clusterState.getMetaData().hasIndex("test-idx-2"), equalTo(false));
if (flushResponseFuture != null) {
// Finish flush
flushResponseFuture.actionGet();
}
}
@Test
|
632 | 1 | public Object getValue(Object parent) {
return parent;
}
@Override
|
633 | 1 | public void handshake(Socket sock) throws IOException {
((SSLSocket)sock).startHandshake();
}
/*
* Determines the SSL cipher suites to be enabled.
*
* @param requestedCiphers Comma-separated list of requested ciphers
* @param supportedCiphers Array of supported ciphers
*
* @return Array of SSL cipher suites to be enabled, or null if none of the
* requested ciphers are supported
*/
|
634 | 1 | ValidationException getErrorParsingMappingFileException(@Cause JAXBException e);
@Message(id = 116, value = "%s")
|
635 | 1 | private static ManagedMap<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(path, method);
BeanDefinitionBuilder attributeBuilder = BeanDefinitionBuilder
.rootBeanDefinition(SecurityConfig.class);
if (useExpressions) {
logger.info("Creating access control expression attribute '" + access
+ "' for " + path);
// The single expression will be parsed later by the
// ExpressionFilterInvocationSecurityMetadataSource
attributeBuilder.addConstructorArgValue(new String[] { access });
attributeBuilder.setFactoryMethod("createList");
}
else {
attributeBuilder.addConstructorArgValue(access);
attributeBuilder.setFactoryMethod("createListFromCommaDelimitedString");
}
if (filterInvocationDefinitionMap.containsKey(matcher)) {
logger.warn("Duplicate URL defined: " + path
+ ". The original attribute values will be overwritten");
}
filterInvocationDefinitionMap.put(matcher,
attributeBuilder.getBeanDefinition());
}
if (addAuthenticatedAll && filterInvocationDefinitionMap.isEmpty()) {
BeanDefinition matcher = matcherType.createMatcher("/**", null);
BeanDefinitionBuilder attributeBuilder = BeanDefinitionBuilder
.rootBeanDefinition(SecurityConfig.class);
attributeBuilder.addConstructorArgValue(new String[] { "authenticated" });
attributeBuilder.setFactoryMethod("createList");
filterInvocationDefinitionMap.put(matcher,
attributeBuilder.getBeanDefinition());
}
return filterInvocationDefinitionMap;
}
|
636 | 1 | public void setApplicationContext(ApplicationContext applicationContext)
throws BeansException {
defaultWebSecurityExpressionHandler.setApplicationContext(applicationContext);
}
|
637 | 1 | public void testDoEnable() throws Exception{
FreeStyleProject project = j.createFreeStyleProject("project");
GlobalMatrixAuthorizationStrategy auth = new GlobalMatrixAuthorizationStrategy();
j.jenkins.setAuthorizationStrategy(auth);
j.jenkins.setCrumbIssuer(null);
HudsonPrivateSecurityRealm realm = new HudsonPrivateSecurityRealm(false);
j.jenkins.setSecurityRealm(realm);
User user = realm.createAccount("John Smith", "password");
SecurityContextHolder.getContext().setAuthentication(user.impersonate());
project.disable();
try{
project.doEnable();
fail("User should not have permission to build project");
}
catch(Exception e){
if(!(e.getClass().isAssignableFrom(AccessDeniedException2.class))){
fail("AccessDeniedException should be thrown.");
}
}
auth.add(Job.READ, user.getId());
auth.add(Job.CONFIGURE, user.getId());
auth.add(Jenkins.READ, user.getId());
List<HtmlForm> forms = j.createWebClient().login(user.getId(), "password").goTo(project.getUrl()).getForms();
for(HtmlForm form:forms){
if("enable".equals(form.getAttribute("action"))){
j.submit(form);
}
}
assertFalse("Project should be enabled.", project.isDisabled());
}
/**
* Job is un-restricted (no nabel), this is submitted to queue, which spawns an on demand slave
* @throws Exception
*/
@Test
|