Unnamed: 0
int64 0
637
| label
int64 0
1
| code
stringlengths 24
8.83k
|
---|---|---|
100 | 0 | public DescriptorExtensionList compute(Class key) {
return DescriptorExtensionList.createDescriptorList(Jenkins.this,key);
}
};
/**
* {@link Computer}s in this Hudson system. Read-only.
*/
|
101 | 0 | public synchronized Throwable fillInStackTrace() {
// This class does not provide a stack trace
return this;
}
}
/** Unexpected end of data. */
private static final IOException EXCEPTION_EOF = new DecodeException("EOF");
/** %xx with not-hex digit */
private static final IOException EXCEPTION_NOT_HEX_DIGIT = new DecodeException(
"isHexDigit");
/** %-encoded slash is forbidden in resource path */
private static final IOException EXCEPTION_SLASH = new DecodeException(
"noSlash");
public UDecoder()
{
}
/** URLDecode, will modify the source. Includes converting
* '+' to ' '.
*/
public void convert( ByteChunk mb )
throws IOException
{
convert(mb, true);
}
/** URLDecode, will modify the source.
*/
public void convert( ByteChunk mb, boolean query )
throws IOException
{
int start=mb.getOffset();
byte buff[]=mb.getBytes();
int end=mb.getEnd();
int idx= ByteChunk.indexOf( buff, start, end, '%' );
int idx2=-1;
if( query ) {
idx2= ByteChunk.indexOf( buff, start, (idx >= 0 ? idx : end), '+' );
}
if( idx<0 && idx2<0 ) {
return;
}
// idx will be the smallest positive index ( first % or + )
if( (idx2 >= 0 && idx2 < idx) || idx < 0 ) {
idx=idx2;
}
boolean noSlash = !(ALLOW_ENCODED_SLASH || query);
for( int j=idx; j<end; j++, idx++ ) {
if( buff[ j ] == '+' && query) {
buff[idx]= (byte)' ' ;
} else if( buff[ j ] != '%' ) {
buff[idx]= buff[j];
} else {
// read next 2 digits
if( j+2 >= end ) {
throw EXCEPTION_EOF;
}
byte b1= buff[j+1];
byte b2=buff[j+2];
if( !isHexDigit( b1 ) || ! isHexDigit(b2 ))
throw EXCEPTION_NOT_HEX_DIGIT;
j+=2;
int res=x2c( b1, b2 );
if (noSlash && (res == '/')) {
throw EXCEPTION_SLASH;
}
buff[idx]=(byte)res;
}
}
mb.setEnd( idx );
return;
}
// -------------------- Additional methods --------------------
// XXX What do we do about charset ????
/** In-buffer processing - the buffer will be modified
* Includes converting '+' to ' '.
*/
public void convert( CharChunk mb )
throws IOException
{
convert(mb, true);
}
/** In-buffer processing - the buffer will be modified
*/
public void convert( CharChunk mb, boolean query )
throws IOException
{
// log( "Converting a char chunk ");
int start=mb.getOffset();
char buff[]=mb.getBuffer();
int cend=mb.getEnd();
int idx= CharChunk.indexOf( buff, start, cend, '%' );
int idx2=-1;
if( query ) {
idx2= CharChunk.indexOf( buff, start, (idx >= 0 ? idx : cend), '+' );
}
if( idx<0 && idx2<0 ) {
return;
}
// idx will be the smallest positive index ( first % or + )
if( (idx2 >= 0 && idx2 < idx) || idx < 0 ) {
idx=idx2;
}
boolean noSlash = !(ALLOW_ENCODED_SLASH || query);
for( int j=idx; j<cend; j++, idx++ ) {
if( buff[ j ] == '+' && query ) {
buff[idx]=( ' ' );
} else if( buff[ j ] != '%' ) {
buff[idx]=buff[j];
} else {
// read next 2 digits
if( j+2 >= cend ) {
// invalid
throw EXCEPTION_EOF;
}
char b1= buff[j+1];
char b2=buff[j+2];
if( !isHexDigit( b1 ) || ! isHexDigit(b2 ))
throw EXCEPTION_NOT_HEX_DIGIT;
j+=2;
int res=x2c( b1, b2 );
if (noSlash && (res == '/')) {
throw EXCEPTION_SLASH;
}
buff[idx]=(char)res;
}
}
mb.setEnd( idx );
}
/** URLDecode, will modify the source
* Includes converting '+' to ' '.
*/
public void convert(MessageBytes mb)
throws IOException
{
convert(mb, true);
}
/** URLDecode, will modify the source
*/
public void convert(MessageBytes mb, boolean query)
throws IOException
{
switch (mb.getType()) {
case MessageBytes.T_STR:
String strValue=mb.toString();
if( strValue==null ) return;
mb.setString( convert( strValue, query ));
break;
case MessageBytes.T_CHARS:
CharChunk charC=mb.getCharChunk();
convert( charC, query );
break;
case MessageBytes.T_BYTES:
ByteChunk bytesC=mb.getByteChunk();
convert( bytesC, query );
break;
}
}
// XXX Old code, needs to be replaced !!!!
//
public final String convert(String str)
{
return convert(str, true);
}
public final String convert(String str, boolean query)
{
if (str == null) return null;
if( (!query || str.indexOf( '+' ) < 0) && str.indexOf( '%' ) < 0 )
return str;
StringBuffer dec = new StringBuffer(); // decoded string output
int strPos = 0;
int strLen = str.length();
dec.ensureCapacity(str.length());
while (strPos < strLen) {
int laPos; // lookahead position
// look ahead to next URLencoded metacharacter, if any
for (laPos = strPos; laPos < strLen; laPos++) {
char laChar = str.charAt(laPos);
if ((laChar == '+' && query) || (laChar == '%')) {
break;
}
}
// if there were non-metacharacters, copy them all as a block
if (laPos > strPos) {
dec.append(str.substring(strPos,laPos));
strPos = laPos;
}
// shortcut out of here if we're at the end of the string
if (strPos >= strLen) {
break;
}
// process next metacharacter
char metaChar = str.charAt(strPos);
if (metaChar == '+') {
dec.append(' ');
strPos++;
continue;
} else if (metaChar == '%') {
// We throw the original exception - the super will deal with
// it
// try {
dec.append((char)Integer.
parseInt(str.substring(strPos + 1, strPos + 3),16));
strPos += 3;
}
}
return dec.toString();
}
private static boolean isHexDigit( int c ) {
return ( ( c>='0' && c<='9' ) ||
( c>='a' && c<='f' ) ||
( c>='A' && c<='F' ));
}
private static int x2c( byte b1, byte b2 ) {
int digit= (b1>='A') ? ( (b1 & 0xDF)-'A') + 10 :
(b1 -'0');
digit*=16;
digit +=(b2>='A') ? ( (b2 & 0xDF)-'A') + 10 :
(b2 -'0');
return digit;
}
private static int x2c( char b1, char b2 ) {
int digit= (b1>='A') ? ( (b1 & 0xDF)-'A') + 10 :
(b1 -'0');
digit*=16;
digit +=(b2>='A') ? ( (b2 & 0xDF)-'A') + 10 :
(b2 -'0');
return digit;
}
|
102 | 0 | private final static int skipSpace(InputAccessor acc, byte b) throws IOException
{
while (true) {
int ch = (int) b & 0xFF;
if (!(ch == ' ' || ch == '\r' || ch == '\n' || ch == '\t')) {
return ch;
}
if (!acc.hasMoreBytes()) {
return -1;
}
b = acc.nextByte();
ch = (int) b & 0xFF;
}
}
|
103 | 0 | public void destroy() {
expiredExchanges.clear();
super.destroy();
}
|
104 | 0 | public ChannelRequestMatcherRegistry requires(String attribute) {
return addAttribute(attribute, requestMatchers);
}
}
} |
105 | 0 | public Builder withIndex(int val)
{
index = val;
return this;
}
|
106 | 0 | void send(final String format, final Object... args);
}
|
107 | 0 | public void beforeHandshake(SocketWrapper<Socket> socket) {
}
}
}
|
108 | 0 | public void fileTest() {
File file = FileUtil.file("d:/aaa", "bbb");
Assert.assertNotNull(file);
//构建目录中出现非子目录抛出异常
FileUtil.file(file, "../ccc");
}
@Test
|
109 | 0 | public String toString()
{
return getValue().toString();
}
|
110 | 0 | private BeanDefinition createSecurityFilterChain(BeanDefinition matcher,
ManagedList<?> filters) {
BeanDefinitionBuilder sfc = BeanDefinitionBuilder
.rootBeanDefinition(DefaultSecurityFilterChain.class);
sfc.addConstructorArgValue(matcher);
sfc.addConstructorArgValue(filters);
return sfc.getBeanDefinition();
}
|
111 | 0 | public String idFromFilename(@Nonnull String filename) {
if (filename.matches("[a-z0-9_. -]+")) {
return filename;
} else {
StringBuilder buf = new StringBuilder(filename.length());
final char[] chars = filename.toCharArray();
for (int i = 0; i < chars.length; i++) {
char c = chars[i];
if ('a' <= c && c <= 'z') {
buf.append(c);
} else if ('0' <= c && c <= '9') {
buf.append(c);
} else if ('_' == c || '.' == c || '-' == c || ' ' == c || '@' == c) {
buf.append(c);
} else if (c == '~') {
i++;
if (i < chars.length) {
buf.append(Character.toUpperCase(chars[i]));
}
} else if (c == '$') {
StringBuilder hex = new StringBuilder(4);
i++;
if (i < chars.length) {
hex.append(chars[i]);
} else {
break;
}
i++;
if (i < chars.length) {
hex.append(chars[i]);
} else {
break;
}
i++;
if (i < chars.length) {
hex.append(chars[i]);
} else {
break;
}
i++;
if (i < chars.length) {
hex.append(chars[i]);
} else {
break;
}
buf.append(Character.valueOf((char)Integer.parseInt(hex.toString(), 16)));
}
}
return buf.toString();
}
}
/**
* {@inheritDoc}
*/
@Override
|
112 | 0 | protected synchronized void stopInternal() throws LifecycleException {
super.stopInternal();
sso = null;
}
|
113 | 0 | public Map<String,WebXml> getFragments() {
return fragments;
}
}
}
|
114 | 0 | private void testModified()
throws Exception
{
KeyFactory kFact = KeyFactory.getInstance("DSA", "BC");
PublicKey pubKey = kFact.generatePublic(PUBLIC_KEY);
Signature sig = Signature.getInstance("DSA", "BC");
for (int i = 0; i != MODIFIED_SIGNATURES.length; i++)
{
sig.initVerify(pubKey);
sig.update(Strings.toByteArray("Hello"));
boolean failed;
try
{
failed = !sig.verify(Hex.decode(MODIFIED_SIGNATURES[i]));
}
catch (SignatureException e)
{
failed = true;
}
isTrue("sig verified when shouldn't", failed);
}
}
|
115 | 0 | public void setUp() throws Exception
{
super.setUp();
_successfulResult = mock(AuthenticationResult.class);
_errorResult = mock(AuthenticationResult.class);
_authenticationProvider = mock(UsernamePasswordAuthenticationProvider.class);
when(_authenticationProvider.authenticate(eq(VALID_USERNAME), eq(VALID_PASSWORD))).thenReturn(_successfulResult);
when(_authenticationProvider.authenticate(eq(VALID_USERNAME), not(eq(VALID_PASSWORD)))).thenReturn(_errorResult);
when(_authenticationProvider.authenticate(not(eq(VALID_USERNAME)), anyString())).thenReturn(_errorResult);
_negotiator = new PlainNegotiator(_authenticationProvider);
}
@Override
|
116 | 0 | protected void doStop() throws Exception {
super.doStop();
// only stop non-shared client
if (!sharedClient && client != null) {
client.stop();
// stop thread pool
Object tp = getClientThreadPool();
if (tp instanceof LifeCycle) {
LOG.debug("Stopping client thread pool {}", tp);
((LifeCycle) tp).stop();
}
}
}
|
117 | 0 | public int doRead(ByteChunk chunk, Request req)
throws IOException {
if (endChunk)
return -1;
if(needCRLFParse) {
needCRLFParse = false;
parseCRLF(false);
}
if (remaining <= 0) {
if (!parseChunkHeader()) {
throw new IOException("Invalid chunk header");
}
if (endChunk) {
parseEndChunk();
return -1;
}
}
int result = 0;
if (pos >= lastValid) {
if (readBytes() < 0) {
throw new IOException(
"Unexpected end of stream whilst reading request body");
}
}
if (remaining > (lastValid - pos)) {
result = lastValid - pos;
remaining = remaining - result;
chunk.setBytes(buf, pos, result);
pos = lastValid;
} else {
result = remaining;
chunk.setBytes(buf, pos, remaining);
pos = pos + remaining;
remaining = 0;
//we need a CRLF
if ((pos+1) >= lastValid) {
//if we call parseCRLF we overrun the buffer here
//so we defer it to the next call BZ 11117
needCRLFParse = true;
} else {
parseCRLF(false); //parse the CRLF immediately
}
}
return result;
}
// ---------------------------------------------------- InputFilter Methods
/**
* Read the content length from the request.
*/
@Override
|
118 | 0 | private static void addUsers(final Set<User> users, final TaskListener listener, @CheckForNull Run<?,?> run, 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) {
try {
Authentication auth = user.impersonate();
if (run != null && !run.getACL().hasPermission(auth, Item.READ)) {
if (SEND_TO_USERS_WITHOUT_READ) {
listener.getLogger().printf("Warning: user %s has no permission to view %s, but sending mail anyway%n", userAddress, run.getFullDisplayName());
} else {
listener.getLogger().printf("Not sending mail to user %s with no permission to view %s", userAddress, run.getFullDisplayName());
continue;
}
}
} catch (UsernameNotFoundException x) {
if (SEND_TO_UNKNOWN_USERS) {
listener.getLogger().printf("Warning: %s is not a recognized user, but sending mail anyway%n", userAddress);
} else {
listener.getLogger().printf("Not sending mail to unregistered user %s%n", userAddress);
continue;
}
}
debug.send("Adding %s with address %s", user.getFullName(), userAddress);
EmailRecipientUtils.addAddressesFromRecipientList(to, cc, bcc, userAddress, env, listener);
} else {
listener.getLogger().println("Failed to send e-mail to "
+ user.getFullName()
+ " because no e-mail address is known, and no default e-mail domain is configured");
}
}
}
}
|
119 | 0 | public String getDisplayName() {
return "Suspects Causing the Build to Begin Failing";
}
}
}
|
120 | 0 | public Object getProperty(String name) {
String repl = name;
if (replacements.get(name) != null) {
repl = (String) replacements.get(name);
}
return IntrospectionUtils.getProperty(protocolHandler, repl);
}
/**
* Set a configured property.
*/
|
121 | 0 | public C anyRequest() {
return requestMatchers(ANY_REQUEST);
}
/**
* Maps a {@link List} of
* {@link org.springframework.security.web.util.matcher.AntPathRequestMatcher}
* instances.
*
* @param method the {@link HttpMethod} to use for any
* {@link HttpMethod}.
*
* @return the object that is chained after creating the {@link RequestMatcher}
*/
|
122 | 0 | protected abstract Log getLog();
/**
* The string manager for this package.
*/
|
123 | 0 | private void assertRecoveryStateWithoutStage(RecoveryState state, int shardId, Type type,
String sourceNode, String targetNode, boolean hasRestoreSource) {
assertThat(state.getShardId().getId(), equalTo(shardId));
assertThat(state.getType(), equalTo(type));
if (sourceNode == null) {
assertNull(state.getSourceNode());
} else {
assertNotNull(state.getSourceNode());
assertThat(state.getSourceNode().getName(), equalTo(sourceNode));
}
if (targetNode == null) {
assertNull(state.getTargetNode());
} else {
assertNotNull(state.getTargetNode());
assertThat(state.getTargetNode().getName(), equalTo(targetNode));
}
if (hasRestoreSource) {
assertNotNull(state.getRestoreSource());
} else {
assertNull(state.getRestoreSource());
}
}
|
124 | 0 | public BeanDefinition parse(Element element, ParserContext parserContext) {
List<Element> interceptUrls = DomUtils.getChildElementsByTagName(element,
"intercept-url");
// Check for attributes that aren't allowed in this context
for (Element elt : interceptUrls) {
if (StringUtils.hasLength(elt
.getAttribute(HttpSecurityBeanDefinitionParser.ATT_REQUIRES_CHANNEL))) {
parserContext.getReaderContext().error(
"The attribute '"
+ HttpSecurityBeanDefinitionParser.ATT_REQUIRES_CHANNEL
+ "' isn't allowed here.", elt);
}
if (StringUtils.hasLength(elt
.getAttribute(HttpSecurityBeanDefinitionParser.ATT_FILTERS))) {
parserContext.getReaderContext().error(
"The attribute '" + HttpSecurityBeanDefinitionParser.ATT_FILTERS
+ "' isn't allowed here.", elt);
}
}
BeanDefinition mds = createSecurityMetadataSource(interceptUrls, false, element,
parserContext);
String id = element.getAttribute(AbstractBeanDefinitionParser.ID_ATTRIBUTE);
if (StringUtils.hasText(id)) {
parserContext.registerComponent(new BeanComponentDefinition(mds, id));
parserContext.getRegistry().registerBeanDefinition(id, mds);
}
return mds;
}
|
125 | 0 | private String getComponentName() {
Class c = getClass();
String name = c.getName();
int dot = name.lastIndexOf('.');
return name.substring(dot + 1).toLowerCase();
}
@Inject(value = StrutsConstants.STRUTS_DEVMODE, required = false)
|
126 | 0 | public void testSecurityAnnotationsSimple() throws Exception {
doTest(DenyAllServlet.class.getName(), false, false, false);
}
|
127 | 0 | public boolean nextRow(ContentHandler handler, ParseContext context) throws IOException, SAXException {
//lazy initialization
if (results == null) {
reset();
}
try {
if (!results.next()) {
return false;
}
} catch (SQLException e) {
throw new IOExceptionWithCause(e);
}
try {
ResultSetMetaData meta = results.getMetaData();
handler.startElement(XHTMLContentHandler.XHTML, "tr", "tr", EMPTY_ATTRIBUTES);
for (int i = 1; i <= meta.getColumnCount(); i++) {
handler.startElement(XHTMLContentHandler.XHTML, "td", "td", EMPTY_ATTRIBUTES);
handleCell(meta, i, handler, context);
handler.endElement(XHTMLContentHandler.XHTML, "td", "td");
}
handler.endElement(XHTMLContentHandler.XHTML, "tr", "tr");
} catch (SQLException e) {
throw new IOExceptionWithCause(e);
}
rows++;
return true;
}
|
128 | 0 | public int getIndex() {
return index;
}
@Override
|
129 | 0 | public EnumSet<MetaData.XContentContext> context() {
return EnumSet.of(MetaData.XContentContext.GATEWAY, MetaData.XContentContext.SNAPSHOT);
}
}
}
}
|
130 | 0 | public static void beforeTests() throws Exception {
initCore("solrconfig.xml","schema.xml");
}
@Override
@Before
|
131 | 0 | public Object create(Context context) throws Exception {
ObjectFactory objFactory = context.getContainer().getInstance(ObjectFactory.class);
try {
return objFactory.buildBean(name, null, true);
} catch (ClassNotFoundException ex) {
throw new ConfigurationException("Unable to load bean "+type.getName()+" ("+name+")");
}
}
}
}
|
132 | 0 | public void changePassword_Returns422UnprocessableEntity_NewPasswordSameAsOld() throws Exception {
Mockito.reset(passwordValidator);
when(expiringCodeStore.retrieveCode("emailed_code"))
.thenReturn(new ExpiringCode("emailed_code", new Timestamp(System.currentTimeMillis()+ UaaResetPasswordService.PASSWORD_RESET_LIFETIME),
"{\"user_id\":\"eyedee\",\"username\":\"[email protected]\",\"passwordModifiedTime\":null,\"client_id\":\"\",\"redirect_uri\":\"\"}",
null));
ScimUser scimUser = new ScimUser("eyedee", "[email protected]", "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("[email protected]");
scimUser.setVerified(true);
when(scimUserProvisioning.retrieve("eyedee")).thenReturn(scimUser);
when(scimUserProvisioning.checkPasswordMatches("eyedee", "new_secret")).thenReturn(true);
MockHttpServletRequestBuilder post = post("/password_change")
.contentType(APPLICATION_JSON)
.content("{\"code\":\"emailed_code\",\"new_password\":\"new_secret\"}")
.accept(APPLICATION_JSON);
SecurityContextHolder.getContext().setAuthentication(new MockAuthentication());
mockMvc.perform(post)
.andExpect(status().isUnprocessableEntity())
.andExpect(content().string(JsonObjectMatcherUtils.matchesJsonObject(new JSONObject().put("error_description", "Your new password cannot be the same as the old password.").put("message", "Your new password cannot be the same as the old password.").put("error", "invalid_password"))));
}
|
133 | 0 | protected void startInternal() throws LifecycleException {
String pathName = getPathname();
try (InputStream is = ConfigFileLoader.getInputStream(pathName)) {
// Load the contents of the database file
if (log.isDebugEnabled()) {
log.debug(sm.getString("memoryRealm.loadPath", pathName));
}
Digester digester = getDigester();
try {
synchronized (digester) {
digester.push(this);
digester.parse(is);
}
} catch (Exception e) {
throw new LifecycleException(sm.getString("memoryRealm.readXml"), e);
} finally {
digester.reset();
}
} catch (IOException ioe) {
throw new LifecycleException(sm.getString("memoryRealm.loadExist", pathName), ioe);
}
super.startInternal();
}
|
134 | 0 | public Container getContainer() {
return (container);
}
/**
* Set the Container with which this Realm has been associated.
*
* @param container The associated Container
*/
@Override
|
135 | 0 | public String getIconFileName() {
return PLUGIN_IMAGES_URL + "icon.png";
}
@Override
|
136 | 0 | public String toString() {
final StringBuilder sb = new StringBuilder();
sb.append( "MetaConstraint" );
sb.append( "{constraintType=" ).append( constraintDescriptor.getAnnotation().annotationType().getName() );
sb.append( ", location=" ).append( location );
sb.append( "}" );
return sb.toString();
}
|
137 | 0 | protected Collection<String> getStandardAttributes() {
Class clz = getClass();
Collection<String> standardAttributes = standardAttributesMap.get(clz);
if (standardAttributes == null) {
Collection<Method> methods = AnnotationUtils.getAnnotatedMethods(clz, StrutsTagAttribute.class);
standardAttributes = new HashSet<>(methods.size());
for(Method m : methods) {
standardAttributes.add(StringUtils.uncapitalize(m.getName().substring(3)));
}
standardAttributesMap.putIfAbsent(clz, standardAttributes);
}
return standardAttributes;
}
|
138 | 0 | public Builder withIndex(long val)
{
index = val;
return this;
}
|
139 | 0 | private Priority getPriority(String severity) {
if (SEVERITY_FATAL.equals(severity) || SEVERITY_ERROR.equals(severity)) {
return Priority.HIGH;
}
if (SEVERITY_INFORMATIONAL.equals(severity)) {
return Priority.LOW;
}
return Priority.NORMAL;
}
|
140 | 0 | public static <E> Closure<E> forClosure(final int count, final Closure<? super E> closure) {
if (count <= 0 || closure == null) {
return NOPClosure.<E>nopClosure();
}
if (count == 1) {
return (Closure<E>) closure;
}
return new ForClosure<E>(count, closure);
}
/**
* Constructor that performs no validation.
* Use <code>forClosure</code> if you want that.
*
* @param count the number of times to execute the closure
* @param closure the closure to execute, not null
*/
|
141 | 0 | public static boolean isWindows() {
return WINDOWS_SEPARATOR == File.separatorChar;
}
/**
* 列出目录文件<br>
* 给定的绝对路径不能是压缩包中的路径
*
* @param path 目录绝对路径或者相对路径
* @return 文件列表(包含目录)
*/
|
142 | 0 | public String getOriginalName() {
return originalName;
}
}
}
|
143 | 0 | protected void engineInitVerify(PublicKey publicKey)
throws InvalidKeyException
{
CipherParameters param = ECUtils.generatePublicKeyParameter(publicKey);
digest.reset();
signer.init(false, param);
}
|
144 | 0 | public void readRequest(HttpServletRequest request, HttpMessage message) {
LOG.trace("readRequest {}", request);
// lets force a parse of the body and headers
message.getBody();
// populate the headers from the request
Map<String, Object> headers = message.getHeaders();
//apply the headerFilterStrategy
Enumeration<?> names = request.getHeaderNames();
while (names.hasMoreElements()) {
String name = (String)names.nextElement();
String value = request.getHeader(name);
// use http helper to extract parameter value as it may contain multiple values
Object extracted = HttpHelper.extractHttpParameterValue(value);
// mapping the content-type
if (name.toLowerCase().equals("content-type")) {
name = Exchange.CONTENT_TYPE;
}
if (headerFilterStrategy != null
&& !headerFilterStrategy.applyFilterToExternalHeaders(name, extracted, message.getExchange())) {
HttpHelper.appendHeader(headers, name, extracted);
}
}
if (request.getCharacterEncoding() != null) {
headers.put(Exchange.HTTP_CHARACTER_ENCODING, request.getCharacterEncoding());
message.getExchange().setProperty(Exchange.CHARSET_NAME, request.getCharacterEncoding());
}
try {
populateRequestParameters(request, message);
} catch (Exception e) {
throw new RuntimeCamelException("Cannot read request parameters due " + e.getMessage(), e);
}
Object body = message.getBody();
// reset the stream cache if the body is the instance of StreamCache
if (body instanceof StreamCache) {
((StreamCache)body).reset();
}
// store the method and query and other info in headers as String types
headers.put(Exchange.HTTP_METHOD, request.getMethod());
headers.put(Exchange.HTTP_QUERY, request.getQueryString());
headers.put(Exchange.HTTP_URL, request.getRequestURL().toString());
headers.put(Exchange.HTTP_URI, request.getRequestURI());
headers.put(Exchange.HTTP_PATH, request.getPathInfo());
headers.put(Exchange.CONTENT_TYPE, request.getContentType());
if (LOG.isTraceEnabled()) {
LOG.trace("HTTP method {}", request.getMethod());
LOG.trace("HTTP query {}", request.getQueryString());
LOG.trace("HTTP url {}", request.getRequestURL());
LOG.trace("HTTP uri {}", request.getRequestURI());
LOG.trace("HTTP path {}", request.getPathInfo());
LOG.trace("HTTP content-type {}", request.getContentType());
}
// if content type is serialized java object, then de-serialize it to a Java object
if (request.getContentType() != null && HttpConstants.CONTENT_TYPE_JAVA_SERIALIZED_OBJECT.equals(request.getContentType())) {
// only deserialize java if allowed
if (allowJavaSerializedObject || isTransferException()) {
try {
InputStream is = message.getExchange().getContext().getTypeConverter().mandatoryConvertTo(InputStream.class, body);
Object object = HttpHelper.deserializeJavaObjectFromStream(is, message.getExchange().getContext());
if (object != null) {
message.setBody(object);
}
} catch (Exception e) {
throw new RuntimeCamelException("Cannot deserialize body to Java object", e);
}
} else {
// set empty body
message.setBody(null);
}
}
populateAttachments(request, message);
}
|
145 | 0 | public void testStripExpression() throws Exception {
// given
ValueStack stack = container.getInstance(ValueStackFactory.class).createValueStack();
String anExpression = "%{foo}";
// when
String actual = ComponentUtils.stripExpressionIfAltSyntax(stack, anExpression);
// then
assertEquals(actual, "foo");
}
|
146 | 0 | public void setMaxExtensionSize(int maxExtensionSize) {
this.maxExtensionSize = maxExtensionSize;
}
/**
* This field indicates if the protocol is treated as if it is secure. This
* normally means https is being used but can be used to fake https e.g
* behind a reverse proxy.
*/
|
147 | 0 | public boolean isStatisticsProvider() {
return false;
}
|
148 | 0 | public void addRecipients(final ExtendedEmailPublisherContext context, final EnvVars env,
final Set<InternetAddress> to, final Set<InternetAddress> cc, final 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 = null;
final Run<?, ?> currentRun = context.getRun();
if (currentRun == null) {
debug.send("currentRun was null");
} else {
if (!Objects.equals(currentRun.getResult(), Result.FAILURE)) {
debug.send("currentBuild did not fail");
} else {
users = new HashSet<>();
debug.send("Collecting builds with suspects...");
final HashSet<Run<?, ?>> buildsWithSuspects = new HashSet<>();
Run<?, ?> firstFailedBuild = currentRun;
Run<?, ?> candidate = currentRun;
while (candidate != null) {
final Result candidateResult = candidate.getResult();
if ( candidateResult == null || !candidateResult.isWorseOrEqualTo(Result.FAILURE) ) {
break;
}
firstFailedBuild = candidate;
candidate = candidate.getPreviousCompletedBuild();
}
if (firstFailedBuild instanceof AbstractBuild) {
buildsWithSuspects.add(firstFailedBuild);
} else {
debug.send(" firstFailedBuild was not an instance of AbstractBuild");
}
debug.send("Collecting suspects...");
users.addAll(RecipientProviderUtilities.getChangeSetAuthors(buildsWithSuspects, debug));
users.addAll(RecipientProviderUtilities.getUsersTriggeringTheBuilds(buildsWithSuspects, debug));
}
}
if (users != null) {
RecipientProviderUtilities.addUsers(users, context, env, to, cc, bcc, debug);
}
}
@Extension
|
149 | 0 | private void filterWithParameterForMethod(String methodParam, String expectedMethod)
throws IOException, ServletException {
MockHttpServletRequest request = new MockHttpServletRequest("POST", "/hotels");
if(methodParam != null) {
request.addParameter("_method", methodParam);
}
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain filterChain = new FilterChain() {
@Override
public void doFilter(ServletRequest filterRequest,
ServletResponse filterResponse) throws IOException, ServletException {
assertEquals("Invalid method", expectedMethod,
((HttpServletRequest) filterRequest).getMethod());
}
};
this.filter.doFilter(request, response, filterChain);
}
|
150 | 0 | public void restorePersistentSettingsTest() throws Exception {
logger.info("--> start 2 nodes");
Settings nodeSettings = settingsBuilder()
.put("discovery.type", "zen")
.put("discovery.zen.ping_timeout", "200ms")
.put("discovery.initial_state_timeout", "500ms")
.build();
internalCluster().startNode(nodeSettings);
Client client = client();
String secondNode = internalCluster().startNode(nodeSettings);
logger.info("--> wait for the second node to join the cluster");
assertThat(client.admin().cluster().prepareHealth().setWaitForNodes("2").get().isTimedOut(), equalTo(false));
int random = randomIntBetween(10, 42);
logger.info("--> set test persistent setting");
client.admin().cluster().prepareUpdateSettings().setPersistentSettings(
ImmutableSettings.settingsBuilder()
.put(ElectMasterService.DISCOVERY_ZEN_MINIMUM_MASTER_NODES, 2)
.put(IndicesTTLService.INDICES_TTL_INTERVAL, random, TimeUnit.MINUTES))
.execute().actionGet();
assertThat(client.admin().cluster().prepareState().setRoutingTable(false).setNodes(false).execute().actionGet().getState()
.getMetaData().persistentSettings().getAsTime(IndicesTTLService.INDICES_TTL_INTERVAL, TimeValue.timeValueMinutes(1)).millis(), equalTo(TimeValue.timeValueMinutes(random).millis()));
assertThat(client.admin().cluster().prepareState().setRoutingTable(false).setNodes(false).execute().actionGet().getState()
.getMetaData().persistentSettings().getAsInt(ElectMasterService.DISCOVERY_ZEN_MINIMUM_MASTER_NODES, -1), equalTo(2));
logger.info("--> create repository");
PutRepositoryResponse putRepositoryResponse = client.admin().cluster().preparePutRepository("test-repo")
.setType("fs").setSettings(ImmutableSettings.settingsBuilder().put("location", randomRepoPath())).execute().actionGet();
assertThat(putRepositoryResponse.isAcknowledged(), equalTo(true));
logger.info("--> start snapshot");
CreateSnapshotResponse createSnapshotResponse = client.admin().cluster().prepareCreateSnapshot("test-repo", "test-snap").setWaitForCompletion(true).execute().actionGet();
assertThat(createSnapshotResponse.getSnapshotInfo().totalShards(), equalTo(0));
assertThat(createSnapshotResponse.getSnapshotInfo().successfulShards(), equalTo(0));
assertThat(client.admin().cluster().prepareGetSnapshots("test-repo").setSnapshots("test-snap").execute().actionGet().getSnapshots().get(0).state(), equalTo(SnapshotState.SUCCESS));
logger.info("--> clean the test persistent setting");
client.admin().cluster().prepareUpdateSettings().setPersistentSettings(
ImmutableSettings.settingsBuilder()
.put(ElectMasterService.DISCOVERY_ZEN_MINIMUM_MASTER_NODES, 1)
.put(IndicesTTLService.INDICES_TTL_INTERVAL, TimeValue.timeValueMinutes(1)))
.execute().actionGet();
assertThat(client.admin().cluster().prepareState().setRoutingTable(false).setNodes(false).execute().actionGet().getState()
.getMetaData().persistentSettings().getAsTime(IndicesTTLService.INDICES_TTL_INTERVAL, TimeValue.timeValueMinutes(1)).millis(), equalTo(TimeValue.timeValueMinutes(1).millis()));
stopNode(secondNode);
assertThat(client.admin().cluster().prepareHealth().setWaitForNodes("1").get().isTimedOut(), equalTo(false));
logger.info("--> restore snapshot");
client.admin().cluster().prepareRestoreSnapshot("test-repo", "test-snap").setRestoreGlobalState(true).setWaitForCompletion(true).execute().actionGet();
assertThat(client.admin().cluster().prepareState().setRoutingTable(false).setNodes(false).execute().actionGet().getState()
.getMetaData().persistentSettings().getAsTime(IndicesTTLService.INDICES_TTL_INTERVAL, TimeValue.timeValueMinutes(1)).millis(), equalTo(TimeValue.timeValueMinutes(random).millis()));
logger.info("--> ensure that zen discovery minimum master nodes wasn't restored");
assertThat(client.admin().cluster().prepareState().setRoutingTable(false).setNodes(false).execute().actionGet().getState()
.getMetaData().persistentSettings().getAsInt(ElectMasterService.DISCOVERY_ZEN_MINIMUM_MASTER_NODES, -1), not(equalTo(2)));
}
@Test
|
151 | 0 | public void init(FilterConfig conf) throws ServletException {
if (conf != null && "zookeeper".equals(conf.getInitParameter("signer.secret.provider"))) {
SolrZkClient zkClient =
(SolrZkClient)conf.getServletContext().getAttribute(KerberosPlugin.DELEGATION_TOKEN_ZK_CLIENT);
try {
conf.getServletContext().setAttribute("signer.secret.provider.zookeeper.curator.client",
getCuratorClient(zkClient));
} catch (InterruptedException | KeeperException e) {
throw new ServletException(e);
}
}
super.init(conf);
}
/**
* Return the ProxyUser Configuration. FilterConfig properties beginning with
* "solr.impersonator.user.name" will be added to the configuration.
*/
@Override
|
152 | 0 | javax.xml.transform.Templates processFromNode(Node node, String systemID)
throws TransformerConfigurationException
{
m_DOMsystemID = systemID;
return processFromNode(node);
}
/**
* Get InputSource specification(s) that are associated with the
* given document specified in the source param,
* via the xml-stylesheet processing instruction
* (see http://www.w3.org/TR/xml-stylesheet/), and that matches
* the given criteria. Note that it is possible to return several stylesheets
* that match the criteria, in which case they are applied as if they were
* a list of imports or cascades.
*
* <p>Note that DOM2 has it's own mechanism for discovering stylesheets.
* Therefore, there isn't a DOM version of this method.</p>
*
*
* @param source The XML source that is to be searched.
* @param media The media attribute to be matched. May be null, in which
* case the prefered templates will be used (i.e. alternate = no).
* @param title The value of the title attribute to match. May be null.
* @param charset The value of the charset attribute to match. May be null.
*
* @return A Source object capable of being used to create a Templates object.
*
* @throws TransformerConfigurationException
*/
|
153 | 0 | protected abstract void handle(Message msg) throws IOException;
@Override
|
154 | 0 | public String[] getRoles(Principal principal) {
if (principal instanceof GenericPrincipal) {
return ((GenericPrincipal) principal).getRoles();
}
String className = principal.getClass().getSimpleName();
throw new IllegalStateException(sm.getString("realmBase.cannotGetRoles", className));
}
|
155 | 0 | public ClassLoader bind(boolean usePrivilegedAction, ClassLoader originalClassLoader) {
Loader loader = getLoader();
ClassLoader webApplicationClassLoader = null;
if (loader != null) {
webApplicationClassLoader = loader.getClassLoader();
}
if (originalClassLoader == null) {
if (usePrivilegedAction) {
PrivilegedAction<ClassLoader> pa = new PrivilegedGetTccl();
originalClassLoader = AccessController.doPrivileged(pa);
} else {
originalClassLoader = Thread.currentThread().getContextClassLoader();
}
}
if (webApplicationClassLoader == null ||
webApplicationClassLoader == originalClassLoader) {
// Not possible or not necessary to switch class loaders. Return
// null to indicate this.
return null;
}
ThreadBindingListener threadBindingListener = getThreadBindingListener();
if (usePrivilegedAction) {
PrivilegedAction<Void> pa = new PrivilegedSetTccl(webApplicationClassLoader);
AccessController.doPrivileged(pa);
} else {
Thread.currentThread().setContextClassLoader(webApplicationClassLoader);
}
if (threadBindingListener != null) {
try {
threadBindingListener.bind();
} catch (Throwable t) {
ExceptionUtils.handleThrowable(t);
log.error(sm.getString(
"standardContext.threadBindingListenerError", getName()), t);
}
}
return originalClassLoader;
}
@Override
|
156 | 0 | public void testInvalidData() throws IOException {
Map<String, String> invalidData = new HashMap();
invalidData.put("foo", "bar");
NamedTemporaryFile tempFile = new NamedTemporaryFile("invalid_parser_data", null);
try (FileOutputStream fos = new FileOutputStream(tempFile.get().toString());
ZipOutputStream zipos = new ZipOutputStream(fos)) {
zipos.putNextEntry(new ZipEntry("parser_data"));
try (ObjectOutputStream oos = new ObjectOutputStream(zipos)) {
oos.writeObject(invalidData);
}
}
ProjectWorkspace workspace =
TestDataHelper.createProjectWorkspaceForScenario(this, "parser_with_cell", tmp);
workspace.setUp();
// Load the invalid parser cache data.
thrown.expect(InvalidClassException.class);
thrown.expectMessage("Can't deserialize this class");
workspace.runBuckCommand("parser-cache", "--load", tempFile.get().toString());
}
|
157 | 0 | public void addSecurityRole(String role) {
securityRoles.add(role);
}
@Override
|
158 | 0 | public boolean contains(Artifact artifact) {
// Note: getLocation(artifact) does an artifact.isResolved() check - no need to do it here.
File location = getLocation(artifact);
return location.canRead() && (location.isFile() || new File(location, "META-INF").isDirectory());
}
|
159 | 0 | public static SVGAttr fromString(String str)
{
// First check cache to see if it is there
SVGAttr attr = cache.get(str);
if (attr != null)
return attr;
// Do the (slow) Enum.valueOf()
if (str.equals("class")) {
cache.put(str, CLASS);
return CLASS;
}
// Check for underscore in attribute - it could potentially confuse us
if (str.indexOf('_') != -1) {
cache.put(str, UNSUPPORTED);
return UNSUPPORTED;
}
try
{
attr = valueOf(str.replace('-', '_'));
if (attr != CLASS) {
cache.put(str, attr);
return attr;
}
}
catch (IllegalArgumentException e)
{
// Do nothing
}
// Unknown attribute name
cache.put(str, UNSUPPORTED);
return UNSUPPORTED;
}
}
// Special attribute keywords
|
160 | 0 | static public void configureLC(LoggerContext lc, String configFile) throws JoranException {
JoranConfigurator configurator = new JoranConfigurator();
lc.reset();
configurator.setContext(lc);
configurator.doConfigure(configFile);
}
|
161 | 0 | public void connect(HttpConsumer consumer) throws Exception {
component.connect(consumer);
}
|
162 | 0 | public static int log2(int n)
{
int log = 0;
while ((n >>= 1) != 0)
{
log++;
}
return log;
}
/**
* Convert int/long to n-byte array.
*
* @param value int/long value.
* @param sizeInByte Size of byte array in byte.
* @return int/long as big-endian byte array of size {@code sizeInByte}.
*/
|
163 | 0 | public String getBindDN()
{
return bindDN.stringValue();
}
/**
* Retrieves the password for this simple bind request, if no password
* provider has been configured.
*
* @return The password for this simple bind request, or {@code null} if a
* password provider will be used to obtain the password.
*/
|
164 | 0 | protected Log getLog() {
return log;
}
@Override
|
165 | 0 | public boolean isReadOnly() {
return false;
}
|
166 | 0 | public void execute(FunctionContext context) {
RegionConfiguration configuration = (RegionConfiguration) context.getArguments();
if (this.cache.getLogger().fineEnabled()) {
StringBuilder builder = new StringBuilder();
builder.append("Function ").append(ID).append(" received request: ").append(configuration);
this.cache.getLogger().fine(builder.toString());
}
// Create or retrieve region
RegionStatus status = createOrRetrieveRegion(configuration);
// Dump XML
if (DUMP_SESSION_CACHE_XML) {
writeCacheXml();
}
// Return status
context.getResultSender().lastResult(status);
}
@Override
|
167 | 0 | public void setSubjectName(String subjectName) {
this.subjectName = subjectName;
}
|
168 | 0 | public void testRejectBindWithDNButNoPasswordAsyncMode()
throws Exception
{
final InMemoryDirectoryServer ds = getTestDS(true, true);
final LDAPConnectionOptions options = new LDAPConnectionOptions();
options.setUseSynchronousMode(false);
final LDAPConnection conn = ds.getConnection(options);
final SimpleBindRequest bindRequest =
new SimpleBindRequest("cn=Directory Manager", "");
try
{
bindRequest.process(conn, 1);
fail("Expected an exception when binding with a DN but no password");
}
catch (LDAPException le)
{
assertEquals(le.getResultCode(), ResultCode.PARAM_ERROR);
}
// Reconfigure the connection so that it will allow binds with a DN but no
// password.
conn.getConnectionOptions().setBindWithDNRequiresPassword(false);
try
{
bindRequest.process(conn, 1);
}
catch (LDAPException le)
{
// The server will still likely reject the operation, but we should at
// least verify that it wasn't a parameter error.
assertFalse(le.getResultCode() == ResultCode.PARAM_ERROR);
}
conn.getConnectionOptions().setBindWithDNRequiresPassword(true);
conn.close();
}
|
169 | 0 | public Collection<ResourcePermission> getRequiredPermissions(String regionName) {
return Collections.singletonList(ResourcePermissions.DATA_MANAGE);
}
|
170 | 0 | public void addRecipients(final ExtendedEmailPublisherContext context, final EnvVars env,
final Set<InternetAddress> to, final Set<InternetAddress> cc, final 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 = null;
final Run<?, ?> currentRun = context.getRun();
if (currentRun == null) {
debug.send("currentRun was null");
} else {
final AbstractTestResultAction<?> testResultAction = currentRun.getAction(AbstractTestResultAction.class);
if (testResultAction == null) {
debug.send("testResultAction was null");
} else {
if (testResultAction.getFailCount() <= 0) {
debug.send("getFailCount() returned <= 0");
} else {
users = new HashSet<>();
debug.send("Collecting builds where a test started failing...");
final HashSet<Run<?, ?>> buildsWhereATestStartedFailing = new HashSet<>();
for (final TestResult caseResult : testResultAction.getFailedTests()) {
final Run<?, ?> runWhereTestStartedFailing = caseResult.getFailedSinceRun();
if (runWhereTestStartedFailing != null) {
debug.send(" runWhereTestStartedFailing: %d", runWhereTestStartedFailing.getNumber());
buildsWhereATestStartedFailing.add(runWhereTestStartedFailing);
} else {
context.getListener().error("getFailedSinceRun returned null for %s", caseResult.getFullDisplayName());
}
}
// For each build where a test started failing, walk backward looking for build results worse than
// UNSTABLE. All of those builds will be used to find suspects.
debug.send("Collecting builds with suspects...");
final HashSet<Run<?, ?>> buildsWithSuspects = new HashSet<>();
for (final Run<?, ?> buildWhereATestStartedFailing : buildsWhereATestStartedFailing) {
debug.send(" buildWhereATestStartedFailing: %d", buildWhereATestStartedFailing.getNumber());
buildsWithSuspects.add(buildWhereATestStartedFailing);
Run<?, ?> previousBuildToCheck = buildWhereATestStartedFailing.getPreviousCompletedBuild();
if (previousBuildToCheck != null) {
debug.send(" previousBuildToCheck: %d", previousBuildToCheck.getNumber());
}
while (previousBuildToCheck != null) {
if (buildsWithSuspects.contains(previousBuildToCheck)) {
// Short-circuit if the build to check has already been checked.
debug.send(" already contained in buildsWithSuspects; stopping search");
break;
}
final Result previousResult = previousBuildToCheck.getResult();
if (previousResult == null) {
debug.send(" previousResult was null");
} else {
debug.send(" previousResult: %s", previousResult.toString());
if (previousResult.isBetterThan(Result.FAILURE)) {
debug.send(" previousResult was better than FAILURE; stopping search");
break;
} else {
debug.send(" previousResult was not better than FAILURE; adding to buildsWithSuspects; continuing search");
buildsWithSuspects.add(previousBuildToCheck);
previousBuildToCheck = previousBuildToCheck.getPreviousCompletedBuild();
if (previousBuildToCheck != null) {
debug.send(" previousBuildToCheck: %d", previousBuildToCheck.getNumber());
}
}
}
}
}
debug.send("Collecting suspects...");
users.addAll(RecipientProviderUtilities.getChangeSetAuthors(buildsWithSuspects, debug));
users.addAll(RecipientProviderUtilities.getUsersTriggeringTheBuilds(buildsWithSuspects, debug));
}
}
}
if (users != null) {
RecipientProviderUtilities.addUsers(users, context, env, to, cc, bcc, debug);
}
}
@Extension
|
171 | 0 | public void doStart() throws Exception {
URI rootURI;
if (serverInfo != null) {
rootURI = serverInfo.resolveServer(configuredDir);
} else {
rootURI = configuredDir;
}
if (!rootURI.getScheme().equals("file")) {
throw new IllegalStateException("FileKeystoreManager must have a root that's a local directory (not " + rootURI + ")");
}
directory = new File(rootURI);
if (!directory.exists() || !directory.isDirectory() || !directory.canRead()) {
throw new IllegalStateException("FileKeystoreManager must have a root that's a valid readable directory (not " + directory.getAbsolutePath() + ")");
}
log.debug("Keystore directory is " + directory.getAbsolutePath());
}
|
172 | 0 | public void setLimit(int limit) {
if (buffered == null) {
buffered = new ByteChunk(4048);
buffered.setLimit(limit);
}
}
// ---------------------------------------------------- InputBuffer Methods
/**
* Reads the request body and buffers it.
*/
|
173 | 0 | public LockoutPolicy getLockoutPolicy() {
if(isEnabled) {
LockoutPolicy res = IdentityZoneHolder.get().getConfig().getClientLockoutPolicy();
return res.getLockoutAfterFailures() != -1 ? res : defaultLockoutPolicy;
} else {
return disabledLockoutPolicy;
}
}
@Override
|
174 | 0 | private static void post(JenkinsRule.WebClient webClient, String relative,
String expectedContentType, Integer expectedStatus) throws IOException {
WebRequest request = new WebRequest(
UrlUtils.toUrlUnsafe(webClient.getContextPath() + relative),
HttpMethod.POST);
try {
Page p = webClient.getPage(request);
if (expectedContentType != null) {
assertThat(p.getWebResponse().getContentType(), is(expectedContentType));
}
} catch (FailingHttpStatusCodeException e) {
if (expectedStatus != null) {
assertEquals(expectedStatus.intValue(), e.getStatusCode());
} else {
throw e;
}
}
}
|
175 | 0 | private void detectJPA() {
// check whether we have Persistence on the classpath
Class<?> persistenceClass;
try {
persistenceClass = run( LoadClass.action( PERSISTENCE_CLASS_NAME, this.getClass() ) );
}
catch ( ValidationException e ) {
log.debugf(
"Cannot find %s on classpath. Assuming non JPA 2 environment. All properties will per default be traversable.",
PERSISTENCE_CLASS_NAME
);
return;
}
// check whether Persistence contains getPersistenceUtil
Method persistenceUtilGetter = run( GetMethod.action( persistenceClass, PERSISTENCE_UTIL_METHOD ) );
if ( persistenceUtilGetter == null ) {
log.debugf(
"Found %s on classpath, but no method '%s'. Assuming JPA 1 environment. All properties will per default be traversable.",
PERSISTENCE_CLASS_NAME,
PERSISTENCE_UTIL_METHOD
);
return;
}
// try to invoke the method to make sure that we are dealing with a complete JPA2 implementation
// unfortunately there are several incomplete implementations out there (see HV-374)
try {
Object persistence = run( NewInstance.action( persistenceClass, "persistence provider" ) );
ReflectionHelper.getValue( persistenceUtilGetter, persistence );
}
catch ( Exception e ) {
log.debugf(
"Unable to invoke %s.%s. Inconsistent JPA environment. All properties will per default be traversable.",
PERSISTENCE_CLASS_NAME,
PERSISTENCE_UTIL_METHOD
);
}
log.debugf(
"Found %s on classpath containing '%s'. Assuming JPA 2 environment. Trying to instantiate JPA aware TraversableResolver",
PERSISTENCE_CLASS_NAME,
PERSISTENCE_UTIL_METHOD
);
try {
@SuppressWarnings("unchecked")
Class<? extends TraversableResolver> jpaAwareResolverClass = (Class<? extends TraversableResolver>)
run( LoadClass.action( JPA_AWARE_TRAVERSABLE_RESOLVER_CLASS_NAME, this.getClass() ) );
jpaTraversableResolver = run( NewInstance.action( jpaAwareResolverClass, "" ) );
log.debugf(
"Instantiated JPA aware TraversableResolver of type %s.", JPA_AWARE_TRAVERSABLE_RESOLVER_CLASS_NAME
);
}
catch ( ValidationException e ) {
log.debugf(
"Unable to load or instantiate JPA aware resolver %s. All properties will per default be traversable.",
JPA_AWARE_TRAVERSABLE_RESOLVER_CLASS_NAME
);
}
}
@Override
|
176 | 0 | public String getName() {
return name;
}
|
177 | 0 | public static <T> Transformer<T, T> cloneTransformer() {
return INSTANCE;
}
/**
* Constructor.
*/
|
178 | 0 | public static ASN1Enumerated getInstance(
ASN1TaggedObject obj,
boolean explicit)
{
ASN1Primitive o = obj.getObject();
if (explicit || o instanceof ASN1Enumerated)
{
return getInstance(o);
}
else
{
return fromOctetString(((ASN1OctetString)o).getOctets());
}
}
/**
* Constructor from int.
*
* @param value the value of this enumerated.
*/
|
179 | 0 | public void servletSecurityAnnotationScan() throws ServletException;
|
180 | 0 | protected AbstractOutputBuffer<Long> getOutputBuffer() {
return outputBuffer;
}
|
181 | 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();
Run<?,?> run = context.getRun();
final Result runResult = run.getResult();
if (run instanceof AbstractBuild) {
Set<User> users = ((AbstractBuild<?,?>)run).getCulprits();
RecipientProviderUtilities.addUsers(users, context, 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, env, to, cc, bcc, debug);
}
}
@Extension
|
182 | 0 | public void process(Exchange exchange) throws Exception {
|
183 | 0 | public void testLauncherServerReuse() throws Exception {
ChildProcAppHandle handle1 = null;
ChildProcAppHandle handle2 = null;
ChildProcAppHandle handle3 = null;
try {
handle1 = LauncherServer.newAppHandle();
handle2 = LauncherServer.newAppHandle();
LauncherServer server1 = handle1.getServer();
assertSame(server1, handle2.getServer());
handle1.kill();
handle2.kill();
handle3 = LauncherServer.newAppHandle();
assertNotSame(server1, handle3.getServer());
handle3.kill();
assertNull(LauncherServer.getServerInstance());
} finally {
kill(handle1);
kill(handle2);
kill(handle3);
}
}
@Test
|
184 | 0 | void set(String format, Hash hash) throws ANTLRException {
set(format,1,hash);
}
/**
* Returns true if n-th bit is on.
*/
|
185 | 0 | private static int getNumberOfIterations(int bits, int certainty)
{
/*
* NOTE: We enforce a minimum 'certainty' of 100 for bits >= 1024 (else 80). Where the
* certainty is higher than the FIPS 186-4 tables (C.2/C.3) cater to, extra iterations
* are added at the "worst case rate" for the excess.
*/
if (bits >= 1536)
{
return certainty <= 100 ? 3
: certainty <= 128 ? 4
: 4 + (certainty - 128 + 1) / 2;
}
else if (bits >= 1024)
{
return certainty <= 100 ? 4
: certainty <= 112 ? 5
: 5 + (certainty - 112 + 1) / 2;
}
else if (bits >= 512)
{
return certainty <= 80 ? 5
: certainty <= 100 ? 7
: 7 + (certainty - 100 + 1) / 2;
}
else
{
return certainty <= 80 ? 40
: 40 + (certainty - 80 + 1) / 2;
}
}
|
186 | 0 | public void setMaxSize(String maxSize) {
this.maxSize = Long.parseLong(maxSize);
}
@Inject
|
187 | 0 | public <T> T postProcess(T object) {
throw new IllegalStateException(
ObjectPostProcessor.class.getName()
+ " is a required bean. Ensure you have used @EnableWebSecurity and @Configuration");
}
};
|
188 | 0 | public String path() {
return "path";
}
}
}
public void loadConfig(Class<?>... configs) {
this.context = new AnnotationConfigWebApplicationContext();
this.context.register(configs);
this.context.setServletContext(new MockServletContext());
this.context.refresh();
this.context.getAutowireCapableBeanFactory().autowireBean(this);
}
} |
189 | 0 | public boolean timedOut() {
return timedOut;
}
}
}
|
190 | 0 | public void destroy() {
// NOOP
}
/**
* Initialize this servlet.
*/
@Override
|
191 | 0 | public void testBadColorSpace() {
TesseractOCRConfig config = new TesseractOCRConfig();
config.setColorspace("someth!ng");
}
|
192 | 0 | private File getFileParameterFolderUnderBuild(AbstractBuild<?, ?> build){
return new File(build.getRootDir(), FOLDER_NAME);
}
/**
* Default implementation from {@link File}.
*/
|
193 | 0 | public void nextBytes(byte[] bytes)
{
if (first)
{
super.nextBytes(bytes);
first = false;
}
else
{
bytes[bytes.length - 1] = 2;
}
}
}
}
|
194 | 0 | protected Timestamp getPasswordLastModifiedTimestamp(Timestamp t) {
Calendar cal = new GregorianCalendar();
cal.set(Calendar.MILLISECOND, 0);
return new Timestamp(cal.getTimeInMillis());
}
@Override
|
195 | 0 | public static <T> Factory<T> instantiateFactory(final Class<T> classToInstantiate,
final Class<?>[] paramTypes,
final Object[] args) {
if (classToInstantiate == null) {
throw new NullPointerException("Class to instantiate must not be null");
}
if (paramTypes == null && args != null
|| paramTypes != null && args == null
|| paramTypes != null && args != null && paramTypes.length != args.length) {
throw new IllegalArgumentException("Parameter types must match the arguments");
}
if (paramTypes == null || paramTypes.length == 0) {
return new InstantiateFactory<T>(classToInstantiate);
}
return new InstantiateFactory<T>(classToInstantiate, paramTypes, args);
}
/**
* Constructor that performs no validation.
* Use <code>instantiateFactory</code> if you want that.
*
* @param classToInstantiate the class to instantiate
*/
|
196 | 0 | public Object evaluate(MessageEvaluationContext message) throws JMSException {
try {
if (message.isDropped()) {
return null;
}
return evaluator.evaluate(message.getMessage()) ? Boolean.TRUE : Boolean.FALSE;
} catch (IOException e) {
throw JMSExceptionSupport.create(e);
}
}
|
197 | 0 | private boolean shutdownDB(String dbName) {
boolean ok = true;
boolean gotSQLExc = false;
try {
DerbyConnectionUtil.getDerbyConnection(dbName,
DerbyConnectionUtil.SHUTDOWN_DB_PROP);
} catch (SQLException se) {
gotSQLExc = true;
}
if (!gotSQLExc) {
ok = false;
}
return ok;
}
|
198 | 0 | public DeserializerFactory withConfig(DeserializerFactoryConfig config)
{
if (_factoryConfig == config) {
return this;
}
/* 22-Nov-2010, tatu: Handling of subtypes is tricky if we do immutable-with-copy-ctor;
* and we pretty much have to here either choose between losing subtype instance
* when registering additional deserializers, or losing deserializers.
* Instead, let's actually just throw an error if this method is called when subtype
* has not properly overridden this method; this to indicate problem as soon as possible.
*/
if (getClass() != BeanDeserializerFactory.class) {
throw new IllegalStateException("Subtype of BeanDeserializerFactory ("+getClass().getName()
+") has not properly overridden method 'withAdditionalDeserializers': can not instantiate subtype with "
+"additional deserializer definitions");
}
return new BeanDeserializerFactory(config);
}
/*
/**********************************************************
/* DeserializerFactory API implementation
/**********************************************************
*/
/**
* Method that {@link DeserializerCache}s call to create a new
* deserializer for types other than Collections, Maps, arrays and
* enums.
*/
@Override
|
199 | 0 | public void setTransferException(boolean transferException) {
this.transferException = transferException;
}
|