content_type
stringclasses
8 values
main_lang
stringclasses
7 values
message
stringlengths
1
50
sha
stringlengths
40
40
patch
stringlengths
52
962k
file_count
int64
1
300
Text
Text
add link to n-api tutorial website
cb315d2dd36d5ef1a9f7354662ee7e2e1e8fa696
<ide><path>doc/api/n-api.md <ide> it still gets the benefits of the ABI stability provided by the C API. <ide> When using `node-addon-api` instead of the C APIs, start with the API [docs][] <ide> for `node-addon-api`. <ide> <add>The [N-API Resource](https://nodejs.github.io/node-addon-examples/) offers an <add>excellent orientation and tips for developers just getting started with N-API <add>and node-addon-api. <add> <ide> ## Implications of ABI stability <ide> <ide> Although N-API provides an ABI stability guarantee, other parts of Node.js do
1
Python
Python
add enum validation for [webserver]analytics_tool
7c7dbfe186773fdbe2d791667e7e97b8e00f771f
<ide><path>airflow/configuration.py <ide> class AirflowConfigParser(ConfigParser): <ide> ("logging", "fab_logging_level"): _available_logging_levels, <ide> # celery_logging_level can be empty, which uses logging_level as fallback <ide> ("logging", "celery_logging_level"): _available_logging_levels + [''], <add> ("webserver", "analytical_tool"): ['google_analytics', 'metarouter', 'segment', ''], <ide> } <ide> <ide> upgraded_values: Dict[Tuple[str, str], str]
1
Javascript
Javascript
add test-npm-install to parallel tests suite
061ebb39c94eea22d34d20c6936787310f7bf9b0
<ide><path>test/parallel/test-npm-install.js <add>'use strict'; <add>const common = require('../common'); <add> <add>const path = require('path'); <add>const spawn = require('child_process').spawn; <add>const assert = require('assert'); <add>const fs = require('fs'); <add> <add>common.refreshTmpDir(); <add> <add>const npmPath = path.join( <add> common.testDir, <add> '..', <add> 'deps', <add> 'npm', <add> 'bin', <add> 'npm-cli.js' <add>); <add> <add>const args = [ <add> npmPath, <add> 'install' <add>]; <add> <add>const pkgContent = '{}'; <add> <add>const pkgPath = path.join(common.tmpDir, 'package.json'); <add> <add>fs.writeFileSync(pkgPath, pkgContent); <add> <add>const proc = spawn(process.execPath, args, { <add> cwd: common.tmpDir <add>}); <add> <add>function handleExit(code, signalCode) { <add> assert.equal(code, 0, 'npm install should run without an error'); <add> assert.ok(signalCode === null, 'signalCode should be null'); <add>} <add> <add>proc.on('exit', common.mustCall(handleExit));
1
Python
Python
fix triggerer --capacity parameter
9076b67c05cdba23e8fa51ebe5ad7f7d53e1c2ba
<ide><path>airflow/cli/cli_parser.py <ide> def _check(value): <ide> # triggerer <ide> ARG_CAPACITY = Arg( <ide> ("--capacity",), <del> type=str, <add> type=positive_int(allow_zero=False), <ide> help="The maximum number of triggers that a Triggerer will run at one time.", <ide> ) <ide>
1
Text
Text
add support for 15.04, add systemd note for 15.04
9847c0c8b0409d85a1f79a8d7316ba48d6a3ef9a
<ide><path>docs/installation/ubuntulinux.md <ide> parent = "smn_linux" <ide> <ide> Docker is supported on these Ubuntu operating systems: <ide> <add>- Ubuntu Vivid 15.04 <ide> - Ubuntu Trusty 14.04 (LTS) <ide> - Ubuntu Precise 12.04 (LTS) <ide> - Ubuntu Saucy 13.10 <ide> your kernel version: <ide> >version. <ide> <ide> <add>### For Vivid 15.04 <add> <add>There are no prerequisites for this version. <add> <ide> ### For Trusty 14.04 <ide> <ide> There are no prerequisites for this version. <ide> better with Docker. <ide> * [Adjust memory and swap accounting](#adjust-memory-and-swap-accounting) <ide> * [Enable UFW forwarding](#enable-ufw-forwarding) <ide> * [Configure a DNS server for use by Docker](#configure-a-dns-server-for-docker) <add>* [Configure Docker to start on boot](#configure-docker-to-start-on-boot) <ide> <ide> ### Create a Docker group <ide> <ide> NetworkManager (this might slow your network). <ide> <ide> $ sudo restart network-manager $ sudo restart docker <ide> <add>### Configure Docker to start on boot <add> <add>Ubuntu uses `systemd` as its boot and service manager `15.04` onwards and `upstart` <add>for versions `14.10` and below. <add> <add>For `15.04` and up, to configure the `docker` daemon to start on boot, run <add> <add> $ sudo systemctl enable docker <add> <add>&nbsp; <add> <add>For `14.10` and below the above installation method automatically configures `upstart` <add>to start the docker daemon on boot <ide> <ide> ## Upgrade Docker <ide>
1
Javascript
Javascript
fix api linting
0ccd0a6f77795cc2fb8047456ae6ab13497f7315
<ide><path>api-server/common/utils/index.js <ide> export const fixCompletedChallengeItem = obj => <ide> 'solution', <ide> 'githubLink', <ide> 'challengeType', <del> 'files', <add> 'files' <ide> ]); <ide><path>api-server/server/boot/authentication.js <ide> import { check } from 'express-validator/check'; <ide> <ide> import { homeLocation } from '../../../config/env'; <ide> import { createCookieConfig } from '../utils/cookieConfig'; <del>import { <add>import { <ide> createPassportCallbackAuthenticator, <ide> saveResponseAuthCookies, <ide> loginRedirect <ide><path>api-server/server/boot/certificate.js <ide> function createShowCert(app) { <ide> messages: [ <ide> { <ide> type: 'info', <del> message: `We could not find a user with the username "${username}"` <add> message: `We could not find a user with the username "${ <add> username <add> }"` <ide> } <ide> ] <ide> }); <ide><path>api-server/server/middlewares/csurf.js <ide> export default function() { <ide> return function csrf(req, res, next) { <ide> <ide> const path = req.path.split('/')[1]; <del> if (/(^api$|^unauthenticated$|^internal$|^p$)/.test(path)) { <add> if ((/(^api$|^unauthenticated$|^internal$|^p$)/).test(path)) { <ide> return next(); <ide> } <ide> return protection(req, res, next); <ide><path>api-server/server/rss/lybsyn.js <ide> export function getLybsynFeed() { <ide> } catch (err) { <ide> return reject(err); <ide> } <del> const items = feed.map( <del> item => _.pick(item, [ <del> 'full_item_url', <del> 'item_title', <del> 'release_date', <del> 'item_body_short' <del> ]) <del> ) <del> /* eslint-disable camelcase */ <del> .map(({ full_item_url, item_title, release_date, item_body_short}) => ({ <del> title: item_title, <del> extract: item_body_short, <del> isoDate: new Date(release_date).toISOString(), <del> link: full_item_url <del> })); <add> const items = feed <add> .map(item => <add> _.pick(item, [ <add> 'full_item_url', <add> 'item_title', <add> 'release_date', <add> 'item_body_short' <add> ]) <add> ) <add> /* eslint-disable camelcase */ <add> .map( <add> ({ full_item_url, item_title, release_date, item_body_short }) => ({ <add> title: item_title, <add> extract: item_body_short, <add> isoDate: new Date(release_date).toISOString(), <add> link: full_item_url <add> }) <add> ); <ide> /* eslint-enable camelcase */ <ide> return resolve(items); <ide> }); <del> <ide> }); <del> <ide> }); <ide> } <ide><path>api-server/server/utils/getDynamicPropsForUser.js <ide> export default function populateUser(db, user) { <ide> db.collection('user') <ide> .aggregate([ <ide> { $match: { _id: user.id } }, <del> { $project: { points: { $size: '$progressTimestamps' } } }, <add> { $project: { points: { $size: '$progressTimestamps' } } } <ide> ]) <ide> .get(function(err, [{ points = 1 } = {}]) { <ide> if (err) {
6
Ruby
Ruby
remove unused require
bb7b8348e6f307fb9b7279bbab4ea19e9313a45e
<ide><path>test/service/s3_service_test.rb <ide> require "service/shared_service_tests" <ide> require "httparty" <del>require "uri" <ide> <ide> if SERVICE_CONFIGURATIONS[:s3] <ide> class ActiveStorage::Service::S3ServiceTest < ActiveSupport::TestCase
1
Java
Java
fix nullability warnings
0aa3205e3865c34ee98a5d14eeca03abf8f871d4
<ide><path>spring-messaging/src/main/java/org/springframework/messaging/handler/invocation/reactive/AbstractEncoderMethodReturnValueHandler.java <ide> <ide> package org.springframework.messaging.handler.invocation.reactive; <ide> <add>import java.lang.reflect.Method; <ide> import java.util.Collections; <ide> import java.util.List; <ide> import java.util.Map; <ide> public Mono<Void> handleReturnValue( <ide> handleEncodedContent(Flux.from(publisher), returnType, message)); <ide> } <ide> <del> @SuppressWarnings("unchecked") <ide> private Flux<DataBuffer> encodeContent( <ide> @Nullable Object content, MethodParameter returnType, DataBufferFactory bufferFactory, <ide> @Nullable MimeType mimeType, Map<String, Object> hints) { <ide> private Flux<DataBuffer> encodeContent( <ide> ResolvableType elementType; <ide> if (adapter != null) { <ide> publisher = adapter.toPublisher(content); <del> boolean isUnwrapped = KotlinDetector.isSuspendingFunction(returnType.getMethod()) && <del> !COROUTINES_FLOW_CLASS_NAME.equals(returnValueType.toClass().getName()); <del> ResolvableType genericType = isUnwrapped ? returnValueType : returnValueType.getGeneric(); <add> Method method = returnType.getMethod(); <add> boolean isUnwrapped = (method != null && KotlinDetector.isSuspendingFunction(method) && <add> !COROUTINES_FLOW_CLASS_NAME.equals(returnValueType.toClass().getName())); <add> ResolvableType genericType = (isUnwrapped ? returnValueType : returnValueType.getGeneric()); <ide> elementType = getElementType(adapter, genericType); <ide> } <ide> else { <ide><path>spring-test/src/main/java/org/springframework/test/context/TestContextAnnotationUtils.java <ide> public abstract class TestContextAnnotationUtils { <ide> private static final ConcurrentLruCache<Class<?>, EnclosingConfiguration> cachedEnclosingConfigurationModes = <ide> new ConcurrentLruCache<>(32, TestContextAnnotationUtils::lookUpEnclosingConfiguration); <ide> <add> @Nullable <ide> private static volatile EnclosingConfiguration defaultEnclosingConfigurationMode; <ide> <add> <ide> /** <ide> * Find the first annotation of the specified {@code annotationType} within <ide> * the annotation hierarchy <em>above</em> the supplied class, merge that <ide> private static EnclosingConfiguration lookUpEnclosingConfiguration(Class<?> claz <ide> } <ide> <ide> private static EnclosingConfiguration getDefaultEnclosingConfigurationMode() { <del> if (defaultEnclosingConfigurationMode == null) { <add> EnclosingConfiguration defaultConfigurationMode = defaultEnclosingConfigurationMode; <add> if (defaultConfigurationMode == null) { <ide> String value = SpringProperties.getProperty(NestedTestConfiguration.ENCLOSING_CONFIGURATION_PROPERTY_NAME); <ide> EnclosingConfiguration enclosingConfigurationMode = EnclosingConfiguration.from(value); <del> defaultEnclosingConfigurationMode = <add> defaultConfigurationMode = <ide> (enclosingConfigurationMode != null ? enclosingConfigurationMode : EnclosingConfiguration.INHERIT); <add> defaultEnclosingConfigurationMode = defaultConfigurationMode; <ide> } <del> return defaultEnclosingConfigurationMode; <add> return defaultConfigurationMode; <ide> } <ide> <ide> private static void assertNonEmptyAnnotationTypeArray(Class<?>[] annotationTypes, String message) { <ide> private static void assertNonEmptyAnnotationTypeArray(Class<?>[] annotationTypes <ide> this.declaringClass = declaringClass; <ide> this.composedAnnotation = composedAnnotation; <ide> this.annotation = annotation; <del> this.annotationAttributes = AnnotatedElementUtils.findMergedAnnotationAttributes( <add> AnnotationAttributes attributes = AnnotatedElementUtils.findMergedAnnotationAttributes( <ide> rootDeclaringClass, annotation.annotationType().getName(), false, false); <del> Assert.state(this.annotationAttributes != null, "No annotation attributes"); <add> Assert.state(attributes != null, "No annotation attributes"); <add> this.annotationAttributes = attributes; <ide> } <ide> <ide> public Class<?> getRootDeclaringClass() { <ide><path>spring-test/src/main/java/org/springframework/test/context/support/TestPropertySourceUtils.java <ide> else if (!duplicationDetected(currentAttributes, previousAttributes)) { <ide> } <ide> <ide> private static boolean duplicationDetected(TestPropertySourceAttributes currentAttributes, <del> TestPropertySourceAttributes previousAttributes) { <add> @Nullable TestPropertySourceAttributes previousAttributes) { <ide> <ide> boolean duplicationDetected = <ide> (currentAttributes.equals(previousAttributes) && !currentAttributes.isEmpty()); <ide> <ide> if (duplicationDetected && logger.isDebugEnabled()) { <del> logger.debug(String.format("Ignoring duplicate %s declaration on %s, " <del> + "since it is also declared on %s.", currentAttributes, <del> previousAttributes.getDeclaringClass().getName(), <del> currentAttributes.getDeclaringClass().getName())); <add> logger.debug(String.format("Ignoring duplicate %s declaration on %s since it is also declared on %s", <add> currentAttributes, currentAttributes.getDeclaringClass().getName(), <add> previousAttributes.getDeclaringClass().getName())); <ide> } <ide> <ide> return duplicationDetected; <ide><path>spring-tx/src/main/java/org/springframework/transaction/interceptor/TransactionAspectSupport.java <ide> private static Object asFlow(Publisher<?> publisher) { <ide> } <ide> <ide> @SuppressWarnings("unchecked") <add> @Nullable <ide> private static Object awaitSingleOrNull(Publisher<?> publisher, Object continuation) { <ide> return AwaitKt.awaitSingleOrNull(publisher, (Continuation<Object>) continuation); <ide> }
4
Javascript
Javascript
make sure pages bundles are served correctly
963695820f2189cc2031c8789bad5385f36f6062
<ide><path>lib/page-loader.js <del>/* global window, document, __NEXT_DATA__ */ <add>/* global window, document */ <ide> import EventEmitter from './EventEmitter' <ide> <ide> const webpackModule = module <ide> export default class PageLoader { <ide> <ide> loadScript (route) { <ide> route = this.normalizeRoute(route) <del> let scriptRoute = route <del> <del> if (__NEXT_DATA__.nextExport) { <del> scriptRoute = route === '/' ? '/index.js' : `${route}.js` <del> } <add> const scriptRoute = route === '/' ? '/index.js' : `${route}.js` <ide> <ide> const script = document.createElement('script') <ide> const url = `${this.assetPrefix}/_next/${encodeURIComponent(this.buildId)}/page${scriptRoute}` <ide><path>server/index.js <ide> export default class Server { <ide> await this.serveStatic(req, res, p) <ide> }, <ide> <del> '/_next/:buildId/page/:path*': async (req, res, params) => { <add> '/_next/:buildId/page/:path*.js': async (req, res, params) => { <ide> const paths = params.path || [''] <ide> // URL is asks for ${page}.js (to support loading assets from static dirs) <ide> // But there's no .js in the actual page. <ide> // So, we need to remove .js to get the page name. <del> const page = `/${paths.join('/')}`.replace('.js', '') <add> const page = `/${paths.join('/')}` <ide> <ide> if (!this.handleBuildId(params.buildId, res)) { <ide> const error = new Error('INVALID_BUILD_ID') <ide> export default class Server { <ide> } <ide> } <ide> <del> const p = join(this.dir, this.dist, 'bundles', 'pages', paths.join('/')) <del> await this.serveStatic(req, res, p) <add> let p = join(this.dir, this.dist, 'bundles', 'pages', paths.join('/')) <add> if (!fs.existsSync(`${p}.js`)) { <add> p = join(p, 'index') // It's possible to have index.js in a subfolder <add> } <add> await this.serveStatic(req, res, `${p}.js`) <ide> }, <ide> <ide> // It's very important keep this route's param optional.
2
Ruby
Ruby
fix incorrect formula name from file name
330015ffbdd766b1af260ae4eb3efa41e6e8c19b
<ide><path>Library/Homebrew/dev-cmd/extract.rb <ide> def extract <ide> <ide> # The class name has to be renamed to match the new filename, <ide> # e.g. Foo version 1.2.3 becomes FooAT123 and resides in Foo@1.2.3.rb. <del> class_name = name.capitalize <add> class_name = Formulary.class_s(name.to_s) <ide> versioned_name = Formulary.class_s("#{class_name}@#{version}") <ide> result.gsub!("class #{class_name} < Formula", "class #{versioned_name} < Formula") <ide>
1
Javascript
Javascript
add throughput benchmark
2b46959075062c410d9e4f69f4decaef3dc5abd9
<ide><path>benchmark/throughput-child.js <add>var net = require('net'); <add>var received = 0; <add>var start = new Date(); <add>var socket = net.connect(8000); <add> <add>socket.on('data', function(d) { <add> received += d.length; <add>}); <add> <add>var interval = setInterval(function() { <add> // After 1 gigabyte shutdown. <add> if (received > 10 * 1024 * 1024 * 1024) { <add> socket.destroy(); <add> clearInterval(interval); <add> process.exit(0); <add> } else { <add> // Otherwise print some stats. <add> var now = new Date(); <add> var gigabytes = received / (1024 * 1024 * 1024); <add> var gigabits = gigabytes * 8.0; <add> var millisec = now - start; <add> var sec = millisec / 1000; <add> console.log((gigabits / sec) + " gbit/sec") <add> } <add>}, 1000); <ide><path>benchmark/throughput.js <add>var fork = require('child_process').fork; <add>var net = require('net'); <add>var buffer = new Buffer(1024 * 1024); <add> <add>function write(socket) { <add> if (!socket.writable) return; <add> <add> socket.write(buffer, function() { <add> write(socket); <add> }); <add>} <add> <add>var server = net.createServer(function(socket) { <add> server.close(); <add> write(socket); <add>}); <add> <add>server.listen(8000, function() { <add> fork(__dirname + '/throughput-child.js'); <add>}); <add>
2
PHP
PHP
fix issue match only app_key in replace
bafd2c423dca3b88d721b55f2f7f83acc4591321
<ide><path>src/Illuminate/Foundation/Console/KeyGenerateCommand.php <ide> public function fire() <ide> */ <ide> protected function setKeyInEnvironmentFile($key) <ide> { <del> file_put_contents($this->laravel->environmentFilePath(), str_replace( <del> 'APP_KEY='.$this->laravel['config']['app.key'], <add> file_put_contents($this->laravel->environmentFilePath(), preg_replace( <add> $this->getAppKeyPattern(), <ide> 'APP_KEY='.$key, <ide> file_get_contents($this->laravel->environmentFilePath()) <ide> )); <ide> protected function generateRandomKey() <ide> $this->laravel['config']['app.cipher'] == 'AES-128-CBC' ? 16 : 32 <ide> )); <ide> } <add> <add> /** <add> * Get a regex pattern that will match env APP_KEY with any random key <add> * <add> * @return string <add> */ <add> protected function getAppKeyPattern() <add> { <add> $escapedKey = preg_quote('='.$this->laravel['config']['app.key'], '/'); <add> <add> return "/^APP_KEY$escapedKey/m"; <add> } <ide> }
1
Javascript
Javascript
fix the build of with-material-ui-next
b253479a94091bb79ea30d759b73532d7a29849a
<ide><path>examples/with-material-ui-next/styles/createDefaultContext.js <ide> import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider' <ide> import createPalette from 'material-ui/styles/palette' <ide> import createMuiTheme from 'material-ui/styles/theme' <del>import { purple, green } from 'material-ui/styles/colors' <add>import { purple, green } from 'material-ui/colors' <ide> <ide> const createDefaultContext = () => <ide> MuiThemeProvider.createDefaultContext({
1
Go
Go
use correct fn for resizing tty
3260ddb10bff8d1b5cabe547ecb77e19d379a3c6
<ide><path>api/client/utils.go <ide> func (cli *DockerCli) resizeTty(id string, isExec bool) { <ide> } <ide> <ide> var err error <del> if !isExec { <add> if isExec { <ide> err = cli.client.ContainerExecResize(options) <ide> } else { <ide> err = cli.client.ContainerResize(options)
1
Javascript
Javascript
remove content property
e9980412296b6469f39605f48ea527776d7ac718
<ide><path>src/core/ReactDOMIDOperations.js <ide> var invariant = require('invariant'); <ide> * @private <ide> */ <ide> var INVALID_PROPERTY_ERRORS = { <del> content: '`content` must be set using `updateTextContentByID()`.', <ide> dangerouslySetInnerHTML: <ide> '`dangerouslySetInnerHTML` must be set using `updateInnerHTMLByID()`.', <ide> style: '`style` must be set using `updateStylesByID()`.' <ide><path>src/core/ReactNativeComponent.js <ide> var registrationNames = ReactEventEmitter.registrationNames; <ide> // For quickly matching children type, to test if can be treated as content. <ide> var CONTENT_TYPES = {'string': true, 'number': true}; <ide> <del>var CONTENT = keyOf({content: null}); <ide> var DANGEROUSLY_SET_INNER_HTML = keyOf({dangerouslySetInnerHTML: null}); <ide> var STYLE = keyOf({style: null}); <ide> <ide> function assertValidProps(props) { <ide> if (!props) { <ide> return; <ide> } <del> // Note the use of `!=` which checks for null or undefined. <del> var hasChildren = props.children != null ? 1 : 0; <del> var hasContent = props.content != null ? 1 : 0; <del> var hasInnerHTML = props.dangerouslySetInnerHTML != null ? 1 : 0; <add> // Note the use of `==` which checks for null or undefined. <ide> invariant( <del> hasChildren + hasContent + hasInnerHTML <= 1, <del> 'Can only set one of `children`, `props.content`, or ' + <del> '`props.dangerouslySetInnerHTML`.' <add> props.children == null || props.dangerouslySetInnerHTML == null, <add> 'Can only set one of `children` or `props.dangerouslySetInnerHTML`.' <ide> ); <ide> invariant( <ide> props.style == null || typeof props.style === 'object', <ide> ReactNativeComponent.Mixin = { <ide> return innerHTML.__html; <ide> } <ide> } else { <del> var contentToUse = this.props.content != null ? this.props.content : <add> var contentToUse = <ide> CONTENT_TYPES[typeof this.props.children] ? this.props.children : null; <ide> var childrenToUse = contentToUse != null ? null : this.props.children; <ide> if (contentToUse != null) { <ide> ReactNativeComponent.Mixin = { <ide> styleUpdates[styleName] = ''; <ide> } <ide> } <del> } else if (propKey === DANGEROUSLY_SET_INNER_HTML || <del> propKey === CONTENT) { <add> } else if (propKey === DANGEROUSLY_SET_INNER_HTML) { <add> // http://jsperf.com/emptying-speed <ide> ReactComponent.DOMIDOperations.updateTextContentByID( <ide> this._rootNodeID, <ide> '' <ide> ReactNativeComponent.Mixin = { <ide> nextProp <ide> ); <ide> } <del> } else if (propKey === CONTENT) { <del> ReactComponent.DOMIDOperations.updateTextContentByID( <del> this._rootNodeID, <del> '' + nextProp <del> ); <ide> } else if (registrationNames[propKey]) { <ide> putListener(this._rootNodeID, propKey, nextProp); <ide> } else { <ide> ReactNativeComponent.Mixin = { <ide> * @param {ReactReconcileTransaction} transaction <ide> */ <ide> _updateDOMChildren: function(nextProps, transaction) { <del> var thisPropsContentType = typeof this.props.content; <del> var thisPropsContentEmpty = <del> this.props.content == null || thisPropsContentType === 'boolean'; <del> var nextPropsContentType = typeof nextProps.content; <del> var nextPropsContentEmpty = <del> nextProps.content == null || nextPropsContentType === 'boolean'; <del> <del> var lastUsedContent = !thisPropsContentEmpty ? this.props.content : <add> var lastUsedContent = <ide> CONTENT_TYPES[typeof this.props.children] ? this.props.children : null; <ide> <del> var contentToUse = !nextPropsContentEmpty ? nextProps.content : <add> var contentToUse = <ide> CONTENT_TYPES[typeof nextProps.children] ? nextProps.children : null; <ide> <ide> // Note the use of `!=` which checks for null or undefined. <ide><path>src/core/__tests__/ReactDOMIDOperations-test.js <ide> describe('ReactDOMIDOperations', function() { <ide> expect(function() { <ide> ReactDOMIDOperations.updatePropertyByID( <ide> 'testID', <del> keyOf({content: null}), <del> 'testContent' <add> keyOf({dangerouslySetInnerHTML: null}), <add> {__html: 'testContent'} <ide> ); <ide> }).toThrow(); <ide> <ide><path>src/core/__tests__/ReactMultiChildText-test.js <ide> var assertSingleChild = function(instance, text) { <ide> }; <ide> <ide> // Helpers <del>var renderSingleContentChild = function(text) { <del> var d = ReactTestUtils.renderIntoDocument(<div content={text} />); <del> return d; <del>}; <ide> var renderSingleTextChild = function(text) { <ide> var d = ReactTestUtils.renderIntoDocument(<div>{text}</div>); <ide> return d; <ide> describe('ReactMultiChildText', function() { <ide> assertMultiChild(d, 'hello', 'goodbye'); <ide> }); <ide> <del> it('should render content to single text node', function() { <del> var d = renderSingleContentChild('hello'); <del> assertNodeText(d, 'hello'); <del> }); <del> <ide> it('should render a single text child to a single text node', function() { <ide> var d = renderSingleTextChild('hello'); <ide> assertNodeText(d, 'hello'); <ide> describe('ReactMultiChildText', function() { <ide> assertNodeText(d, '0'); <ide> }); <ide> <del> it('should render content number zero as text node', function() { <del> var d = renderSingleContentChild(0); <del> // false should act exactly as a null child <del> assertNodeText(d, '0'); <del> }); <del> <ide> it('should render zero string as string child', function() { <ide> var d = renderMultipleTextChildren('0', 234.2); <ide> // false should act exactly as a null child <ide> describe('ReactMultiChildText', function() { <ide> var d = renderMultipleTextChildren('0', 234.2); <ide> // false should act exactly as a null child <ide> assertMultiChild(d, '0', '234.2'); <del> d.replaceProps({content: '0'}); <add> d.replaceProps({children: '0'}); <ide> assertNodeText(d, '0'); <ide> }); <ide> <ide> it('should render zero number as string child then text node', function() { <ide> var d = renderMultipleTextChildren(0, 234.2); <ide> // false should act exactly as a null child <ide> assertMultiChild(d, '0', '234.2'); <del> d.replaceProps({content: 0}); <add> d.replaceProps({children: 0}); <ide> // BELOW REVEALS A BUG IN JSDOM <ide> // assertNodeText(d, '0'); // This works in the browser. <ide> }); <ide> <ide> it('should render multiple children then switch to inline', function() { <ide> var d = renderMultipleTextChildren('hello', 'goodbye'); <ide> assertMultiChild(d, 'hello', 'goodbye'); <del> d.replaceProps({content: 'hello'}); <add> d.replaceProps({children: 'hello'}); <ide> assertNodeText(d, 'hello'); <ide> }); <ide> <ide> describe('ReactMultiChildText', function() { <ide> assertMultiChild(d, 'hello', 'goodbye'); <ide> }); <ide> <del> it('should render content, then switch to text components ', function() { <del> var d = renderSingleContentChild('hello'); <del> assertNodeText(d, 'hello'); <del> d.replaceProps({children: ['hello', 'goodbye']}); <del> assertMultiChild(d, 'hello', 'goodbye'); <del> }); <del> <ide> it('should render inline child, then switch to composite', function() { <ide> var d = renderSingleTextChild('hello'); <ide> assertNodeText(d, 'hello'); <ide> describe('ReactMultiChildText', function() { <ide> .toBeCompositeComponentWithType(TestCompositeComponent); <ide> }); <ide> <del> it('should throw if rendering both content and children', function() { <add> it('should throw if rendering both HTML and children', function() { <ide> expect(function() { <del> ReactTestUtils.renderIntoDocument(<div content="asdf">ghjkl</div>); <add> ReactTestUtils.renderIntoDocument( <add> <div dangerouslySetInnerHTML={{_html: 'abcdef'}}>ghjkl</div> <add> ); <ide> }).toThrow(); <ide> }); <ide> }); <ide><path>src/core/__tests__/ReactNativeComponent-test.js <ide> describe('ReactNativeComponent', function() { <ide> }); <ide> <ide> it("should validate against multiple children props", function() { <del> expect(function() { <del> mountComponent({ content: '', children: '' }); <del> }).toThrow( <del> 'Invariant Violation: Can only set one of `children`, ' + <del> '`props.content`, or `props.dangerouslySetInnerHTML`.' <del> ); <del> <del> expect(function() { <del> mountComponent({ content: '', dangerouslySetInnerHTML: '' }); <del> }).toThrow( <del> 'Invariant Violation: Can only set one of `children`, ' + <del> '`props.content`, or `props.dangerouslySetInnerHTML`.' <del> ); <del> <ide> expect(function() { <ide> mountComponent({ children: '', dangerouslySetInnerHTML: '' }); <ide> }).toThrow( <del> 'Invariant Violation: Can only set one of `children`, ' + <del> '`props.content`, or `props.dangerouslySetInnerHTML`.' <add> 'Invariant Violation: Can only set one of `children` or ' + <add> '`props.dangerouslySetInnerHTML`.' <ide> ); <ide> }); <ide>
5
Python
Python
fix description, update classifiers
1d2fb0e448fc5c877e2a0e1a49302ebc7c932223
<ide><path>setup.py <ide> def run(self): <ide> name='apache-libcloud', <ide> version=read_version_string(), <ide> description='A standard Python library that abstracts away differences' + <del> 'among multiple cloud provider APIs', <add> ' among multiple cloud provider APIs', <ide> author='Apache Software Foundation', <ide> author_email='dev@libcloud.apache.org', <ide> requires=([], ['ssl', 'simplejson'],)[pre_python26], <ide> def run(self): <ide> 'Programming Language :: Python :: 3', <ide> 'Programming Language :: Python :: 3.0', <ide> 'Programming Language :: Python :: 3.1', <del> 'Programming Language :: Python :: 3.2']) <add> 'Programming Language :: Python :: 3.2', <add> 'Programming Language :: Python :: Implementation :: PyPy'])
1
Python
Python
add glossary entry for _sp
9cc3dc2b67ef41963b78c0d553cfd7175d998d66
<ide><path>spacy/glossary.py <ide> def explain(term): <ide> "XX": "unknown", <ide> "BES": 'auxiliary "be"', <ide> "HVS": 'forms of "have"', <add> "_SP": "whitespace", <ide> # POS Tags (German) <ide> # TIGER Treebank <ide> # http://www.ims.uni-stuttgart.de/forschung/ressourcen/korpora/TIGERCorpus/annotation/tiger_introduction.pdf
1
Javascript
Javascript
fix the illegal syntax in a module for test
4098d29d011d96e8a0f4241011bd8cd205746df7
<ide><path>test/cases/parsing/harmony-export-precedence/a.js <ide> export function a() { return "a1"; } <del>export { a, b } from "./b"; <add>export { b } from "./b"; <ide> export * from "./c"; <del>export { d, e } from "./b"; <add>export { d } from "./b"; <ide> export var e = "e1";
1
Ruby
Ruby
use double quotes for setting path
0d898edc3761dd2675d86c436a589be49407d55b
<ide><path>Library/Homebrew/cmd/doctor.rb <ide> def check_user_path_1 <ide> <ide> Consider setting your PATH so that #{HOMEBREW_PREFIX}/bin <ide> occurs before /usr/bin. Here is a one-liner: <del> echo export PATH='#{HOMEBREW_PREFIX}/bin:$PATH' >> ~/.bash_profile <add> echo export PATH="#{HOMEBREW_PREFIX}/bin:$PATH" >> ~/.bash_profile <ide> EOS <ide> end <ide> end <ide> def check_user_path_2 <ide> <<-EOS.undent <ide> Homebrew's bin was not found in your PATH. <ide> Consider setting the PATH for example like so <del> echo export PATH='#{HOMEBREW_PREFIX}/bin:$PATH' >> ~/.bash_profile <add> echo export PATH="#{HOMEBREW_PREFIX}/bin:$PATH" >> ~/.bash_profile <ide> EOS <ide> end <ide> end <ide> def check_user_path_3 <ide> Homebrew's sbin was not found in your PATH but you have installed <ide> formulae that put executables in #{HOMEBREW_PREFIX}/sbin. <ide> Consider setting the PATH for example like so <del> echo export PATH='#{HOMEBREW_PREFIX}/sbin:$PATH' >> ~/.bash_profile <add> echo export PATH="#{HOMEBREW_PREFIX}/sbin:$PATH" >> ~/.bash_profile <ide> EOS <ide> end <ide> end
1
PHP
PHP
unskip remaining tests
67b3f60b87081f2bd4cc96061fa0e0ff3b217e04
<ide><path>tests/TestCase/Console/Command/Task/ViewTaskTest.php <ide> public function testExecuteWithControllerAndAdminFlag() { <ide> * @return void <ide> */ <ide> public function testExecuteWithAlternateTemplates() { <del> $this->markTestIncomplete('Model baking will not work as models do not work.'); <add> $this->_setupTask(['in', 'err', 'createFile', 'bake', '_stop']); <add> <ide> $this->Task->connection = 'test'; <del> $this->Task->args = array('ViewTaskComments', 'index', 'list'); <del> $this->Task->params = array(); <add> $this->Task->args = ['ViewTaskComments', 'index', 'list']; <add> $this->Task->params = []; <ide> <del> $this->Task->expects($this->once())->method('createFile') <del> ->with( <del> TMP . 'ViewTaskComments/list.ctp', <del> $this->stringContains('ViewTaskComment') <del> ); <add> $this->Task->expects($this->once()) <add> ->method('bake') <add> ->with('list', true); <ide> $this->Task->execute(); <ide> } <ide>
1
Python
Python
fix concatenation in iob2json converter
31681d20e038fb0b318a9479856da473b0e0e926
<ide><path>spacy/cli/converters/iob2json.py <ide> # coding: utf8 <ide> from __future__ import unicode_literals <add>from cytoolz import partition_all, concat <ide> <ide> from ...compat import json_dumps, path2str <ide> from ...util import prints <ide> def iob2json(input_path, output_path, n_sents=10, *a, **k): <ide> """ <ide> Convert IOB files into JSON format for use with train cli. <ide> """ <del> # TODO: This isn't complete yet -- need to map from IOB to <del> # BILUO <ide> with input_path.open('r', encoding='utf8') as file_: <del> docs = read_iob(file_) <add> if n_sents: <add> lines = [' '.join(para) for para in partition_all(n_sents, file_)] <add> else: <add> lines = file_ <add> sentences = read_iob(lines) <ide> <ide> output_filename = input_path.parts[-1].replace(".iob", ".json") <ide> output_file = output_path / output_filename <ide> with output_file.open('w', encoding='utf-8') as f: <del> f.write(json_dumps(docs)) <del> prints("Created %d documents" % len(docs), <add> f.write(json_dumps(sentences)) <add> prints("Created %d documents" % len(sentences), <ide> title="Generated output file %s" % path2str(output_file)) <ide> <ide> <del>def read_iob(file_): <add>def read_iob(raw_sents): <ide> sentences = [] <del> for line in file_: <add> for line in raw_sents: <ide> if not line.strip(): <ide> continue <ide> tokens = [t.split('|') for t in line.split()]
1
Ruby
Ruby
use hash#fetch to eliminate conditional
9cbb6d2b20a8e3352bedd791fafe3c58f8bef328
<ide><path>activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb <ide> def transaction(options = {}) <ide> options.assert_valid_keys :requires_new, :joinable <ide> <ide> last_transaction_joinable = @transaction_joinable <del> if options.has_key?(:joinable) <del> @transaction_joinable = options[:joinable] <del> else <del> @transaction_joinable = true <del> end <del> requires_new = options[:requires_new] || !last_transaction_joinable <del> <del> transaction_open = false <add> @transaction_joinable = options.fetch(:joinable, true) <add> requires_new = options[:requires_new] || !last_transaction_joinable <add> transaction_open = false <ide> <ide> begin <ide> if requires_new || open_transactions == 0
1
Python
Python
fix handling of bindvars with no parameters
a8c6451e6196be64469a99247a4e75d6095b5470
<ide><path>airflow/providers/oracle/hooks/oracle.py <ide> def callproc( <ide> sql = f"BEGIN {identifier}({args}); END;" <ide> <ide> def handler(cursor): <add> if cursor.bindvars is None: <add> return <add> <ide> if isinstance(cursor.bindvars, list): <ide> return [v.getvalue() for v in cursor.bindvars] <ide> <ide><path>tests/providers/oracle/hooks/test_oracle.py <ide> def test_bulk_insert_rows_no_rows(self): <ide> with pytest.raises(ValueError): <ide> self.db_hook.bulk_insert_rows('table', rows) <ide> <add> def test_callproc_none(self): <add> parameters = None <add> <add> class bindvar(int): <add> def getvalue(self): <add> return self <add> <add> self.cur.bindvars = None <add> result = self.db_hook.callproc('proc', True, parameters) <add> assert self.cur.execute.mock_calls == [mock.call('BEGIN proc(); END;')] <add> assert result == parameters <add> <ide> def test_callproc_dict(self): <ide> parameters = {"a": 1, "b": 2, "c": 3} <ide>
2
Javascript
Javascript
run `yarn prettier` to format code
8802c20c22ecef9273c61d10ebb23ac858edb33f
<ide><path>src/renderers/shared/fiber/ReactFiberUpdateQueue.js <ide> <ide> 'use strict'; <ide> <del>import type { Fiber } from 'ReactFiber'; <add>import type {Fiber} from 'ReactFiber'; <ide> import type {PriorityLevel} from 'ReactPriorityLevel'; <ide> <ide> const {
1
Ruby
Ruby
correct the actioncachetest from [7346]
0fc77b3928546c09bd1fac40402289fd3730840b
<ide><path>actionpack/test/controller/caching_test.rb <ide> def test_xml_version_of_resource_is_treated_as_different_cache <ide> end <ide> <ide> def test_correct_content_type_is_returned_for_cache_hit <add> # run it twice to cache it the first time <add> get :index, :id => 'content-type.xml' <ide> get :index, :id => 'content-type.xml' <ide> assert_equal 'application/xml', @response.content_type <ide> end
1
Ruby
Ruby
fix the build
344ea048659f2ba47012f0330183ea4a96752732
<ide><path>actionpack/lib/action_view.rb <ide> #++ <ide> <ide> require 'active_support' <del>require 'active_support/lazy_load_hooks' <ide> require 'action_pack' <ide> <ide> module ActionView <ide><path>activemodel/lib/active_model.rb <ide> #++ <ide> <ide> require 'active_support' <del>require 'active_support/lazy_load_hooks' <ide> require 'active_model/version' <ide> <ide> module ActiveModel <ide><path>activerecord/lib/active_record.rb <ide> #++ <ide> <ide> require 'active_support' <del>require 'active_support/lazy_load_hooks' <ide> require 'active_model' <ide> require 'arel' <ide> require 'active_record_deprecated_finders' <ide><path>activesupport/lib/active_support.rb <ide> require "active_support/dependencies/autoload" <ide> require "active_support/version" <ide> require "active_support/logger" <add>require "active_support/lazy_load_hooks" <ide> <ide> module ActiveSupport <ide> extend ActiveSupport::Autoload
4
Ruby
Ruby
fix start_revision for travis
b37a28514126ac46e06cc1f5c8cc124a0fdff7f1
<ide><path>Library/Homebrew/cmd/test-bot.rb <ide> def brew_update <ide> # Use Travis CI Git variables for master or branch jobs. <ide> elsif ENV["TRAVIS_COMMIT_RANGE"] <ide> diff_start_sha1, diff_end_sha1 = ENV["TRAVIS_COMMIT_RANGE"].split "..." <add> diff_start_sha1 = git("merge-base", diff_start_sha1, diff_end_sha1).strip <ide> # Otherwise just use the current SHA-1 (which may be overriden later) <ide> else <ide> diff_end_sha1 = diff_start_sha1 = current_sha1
1
Ruby
Ruby
use block syntax to avoid code duplication
014da68634c59a7df1950dd7b838fd0ba5181969
<ide><path>actionpack/lib/action_view/helpers/form_helper.rb <ide> def form_for(record, options = {}, &proc) <ide> builder = options[:parent_builder] = instantiate_builder(object_name, object, options, &proc) <ide> fields_for = fields_for(object_name, object, options, &proc) <ide> default_options = builder.multipart? ? { :multipart => true } : {} <del> output = form_tag(options.delete(:url) || {}, default_options.merge!(options.delete(:html))) <del> output << fields_for <del> output.safe_concat('</form>') <add> default_options.merge!(options.delete(:html)) <add> <add> form_tag(options.delete(:url) || {}, default_options) { fields_for } <ide> end <ide> <ide> def apply_form_for_options!(record, object, options) #:nodoc:
1
Python
Python
remove all the casts of y_true to y_pred data type
6bc2571241a600681f8a157c20e29858c2e1546a
<ide><path>keras/losses.py <ide> def mean_squared_error(y_true, y_pred): <ide> Mean squared error values. shape = `[batch_size, d0, .. dN-1]`. <ide> """ <ide> y_pred = tf.convert_to_tensor(y_pred) <del> y_true = tf.cast(y_true, y_pred.dtype) <add> <ide> return backend.mean(tf.math.squared_difference(y_pred, y_true), axis=-1) <ide> <ide> <ide> def mean_absolute_error(y_true, y_pred): <ide> Mean absolute error values. shape = `[batch_size, d0, .. dN-1]`. <ide> """ <ide> y_pred = tf.convert_to_tensor(y_pred) <del> y_true = tf.cast(y_true, y_pred.dtype) <add> <ide> return backend.mean(tf.abs(y_pred - y_true), axis=-1) <ide> <ide> <ide> def mean_squared_logarithmic_error(y_true, y_pred): <ide> Mean squared logarithmic error values. shape = `[batch_size, d0, .. dN-1]`. <ide> """ <ide> y_pred = tf.convert_to_tensor(y_pred) <del> y_true = tf.cast(y_true, y_pred.dtype) <add> <ide> first_log = tf.math.log(backend.maximum(y_pred, backend.epsilon()) + 1.) <ide> second_log = tf.math.log(backend.maximum(y_true, backend.epsilon()) + 1.) <ide> return backend.mean( <ide> def squared_hinge(y_true, y_pred): <ide> Squared hinge loss values. shape = `[batch_size, d0, .. dN-1]`. <ide> """ <ide> y_pred = tf.convert_to_tensor(y_pred) <del> y_true = tf.cast(y_true, y_pred.dtype) <add> <ide> y_true = _maybe_convert_labels(y_true) <ide> return backend.mean( <ide> tf.square(tf.maximum(1. - y_true * y_pred, 0.)), axis=-1) <ide> def hinge(y_true, y_pred): <ide> Hinge loss values. shape = `[batch_size, d0, .. dN-1]`. <ide> """ <ide> y_pred = tf.convert_to_tensor(y_pred) <del> y_true = tf.cast(y_true, y_pred.dtype) <add> <ide> y_true = _maybe_convert_labels(y_true) <ide> return backend.mean(tf.maximum(1. - y_true * y_pred, 0.), axis=-1) <ide> <ide> def categorical_hinge(y_true, y_pred): <ide> Categorical hinge loss values. <ide> """ <ide> y_pred = tf.convert_to_tensor(y_pred) <del> y_true = tf.cast(y_true, y_pred.dtype) <add> <ide> pos = tf.reduce_sum(y_true * y_pred, axis=-1) <ide> neg = tf.reduce_max((1. - y_true) * y_pred, axis=-1) <ide> zero = tf.cast(0., y_pred.dtype) <ide> def log_cosh(y_true, y_pred): <ide> Logcosh error values. shape = `[batch_size, d0, .. dN-1]`. <ide> """ <ide> y_pred = tf.convert_to_tensor(y_pred) <del> y_true = tf.cast(y_true, y_pred.dtype) <add> <ide> <ide> def _logcosh(x): <ide> return x + tf.math.softplus(-2. * x) - tf.cast( <ide> def categorical_crossentropy(y_true, <ide> Categorical crossentropy loss value. <ide> """ <ide> y_pred = tf.convert_to_tensor(y_pred) <del> y_true = tf.cast(y_true, y_pred.dtype) <add> <ide> label_smoothing = tf.convert_to_tensor( <ide> label_smoothing, dtype=backend.floatx()) <ide> <ide> def sparse_categorical_crossentropy(y_true, y_pred, from_logits=False, axis=-1): <ide> Sparse categorical crossentropy loss value. <ide> """ <ide> y_pred = tf.convert_to_tensor(y_pred) <del> y_true = tf.cast(y_true, y_pred.dtype) <add> <ide> return backend.sparse_categorical_crossentropy( <ide> y_true, y_pred, from_logits=from_logits, axis=axis) <ide> <ide> def binary_crossentropy(y_true, <ide> Binary crossentropy loss value. shape = `[batch_size, d0, .. dN-1]`. <ide> """ <ide> y_pred = tf.convert_to_tensor(y_pred) <del> y_true = tf.cast(y_true, y_pred.dtype) <add> <ide> label_smoothing = tf.convert_to_tensor( <ide> label_smoothing, dtype=backend.floatx()) <ide> <ide> def kl_divergence(y_true, y_pred): <ide> TypeError: If `y_true` cannot be cast to the `y_pred.dtype`. <ide> """ <ide> y_pred = tf.convert_to_tensor(y_pred) <del> y_true = tf.cast(y_true, y_pred.dtype) <add> <ide> y_true = backend.clip(y_true, backend.epsilon(), 1) <ide> y_pred = backend.clip(y_pred, backend.epsilon(), 1) <ide> return tf.reduce_sum(y_true * tf.math.log(y_true / y_pred), axis=-1) <ide> def poisson(y_true, y_pred): <ide> InvalidArgumentError: If `y_true` and `y_pred` have incompatible shapes. <ide> """ <ide> y_pred = tf.convert_to_tensor(y_pred) <del> y_true = tf.cast(y_true, y_pred.dtype) <add> <ide> return backend.mean( <ide> y_pred - y_true * tf.math.log(y_pred + backend.epsilon()), axis=-1) <ide>
1
Go
Go
fix broken json support in cli/command/formatter
26013fcdd64221c858022392a1430a6c43eaaa26
<ide><path>cli/command/formatter/disk_usage.go <ide> type diskUsageImagesContext struct { <ide> images []*types.ImageSummary <ide> } <ide> <add>func (c *diskUsageImagesContext) MarshalJSON() ([]byte, error) { <add> return marshalJSON(c) <add>} <add> <ide> func (c *diskUsageImagesContext) Type() string { <ide> c.AddHeader(typeHeader) <ide> return "Images" <ide> type diskUsageContainersContext struct { <ide> containers []*types.Container <ide> } <ide> <add>func (c *diskUsageContainersContext) MarshalJSON() ([]byte, error) { <add> return marshalJSON(c) <add>} <add> <ide> func (c *diskUsageContainersContext) Type() string { <ide> c.AddHeader(typeHeader) <ide> return "Containers" <ide> type diskUsageVolumesContext struct { <ide> volumes []*types.Volume <ide> } <ide> <add>func (c *diskUsageVolumesContext) MarshalJSON() ([]byte, error) { <add> return marshalJSON(c) <add>} <add> <ide> func (c *diskUsageVolumesContext) Type() string { <ide> c.AddHeader(typeHeader) <ide> return "Local Volumes" <ide><path>cli/command/formatter/image.go <ide> type imageContext struct { <ide> digest string <ide> } <ide> <add>func (c *imageContext) MarshalJSON() ([]byte, error) { <add> return marshalJSON(c) <add>} <add> <ide> func (c *imageContext) ID() string { <ide> c.AddHeader(imageIDHeader) <ide> if c.trunc { <ide><path>cli/command/formatter/stats.go <ide> type containerStatsContext struct { <ide> s StatsEntry <ide> } <ide> <add>func (c *containerStatsContext) MarshalJSON() ([]byte, error) { <add> return marshalJSON(c) <add>} <add> <ide> func (c *containerStatsContext) Container() string { <ide> c.AddHeader(containerHeader) <ide> return c.s.Container
3
Java
Java
improve regex for parsing query params
0721146b14e3df3bde3e6e8f2a871bb0b995ef4f
<ide><path>spring-web/src/main/java/org/springframework/web/util/UriComponentsBuilder.java <ide> */ <ide> public class UriComponentsBuilder { <ide> <del> private static final Pattern QUERY_PARAM_PATTERN = Pattern.compile("([^&=]+)=?([^&=]+)?"); <add> private static final Pattern QUERY_PARAM_PATTERN = Pattern.compile("([^&=]+)=?([^&]+)?"); <ide> <ide> private static final String SCHEME_PATTERN = "([^:/?#]+):"; <ide> <ide><path>spring-web/src/test/java/org/springframework/web/util/UriComponentsBuilderTests.java <ide> public void fromUriString() { <ide> assertEquals("28", result.getFragment()); <ide> } <ide> <add> // SPR-9832 <add> <add> @Test <add> public void fromUriStringQueryParamWithReservedCharInValue() throws URISyntaxException { <add> String uri = "http://www.google.com/ig/calculator?q=1USD=?EUR"; <add> UriComponents result = UriComponentsBuilder.fromUriString(uri).build(); <add> <add> assertEquals("q=1USD=?EUR", result.getQuery()); <add> assertEquals("1USD=?EUR", result.getQueryParams().getFirst("q")); <add> } <ide> <ide> @Test <ide> public void path() throws URISyntaxException {
2
Python
Python
prevent docker-ci to test closing prs
53a07d547554adc61b82f3ff794c0c9c0686be73
<ide><path>hack/infrastructure/docker-ci/buildbot/github.py <ide> def getChanges(request, options = None): <ide> fname = str(datetime.datetime.now()).replace(' ','_').replace(':','-')[:19] <ide> open('github_{0}.json'.format(fname),'w').write(json.dumps(json.loads(urllib.unquote(request.args['payload'][0])), sort_keys = True, indent = 2)) <ide> <del> if 'pull_request' in payload: <del> user = payload['pull_request']['user']['login'] <del> repo = payload['pull_request']['head']['repo']['name'] <del> repo_url = payload['pull_request']['head']['repo']['html_url'] <del> else: <del> user = payload['repository']['owner']['name'] <add> if 'pull_request' in payload: <add> user = payload['pull_request']['user']['login'] <add> repo = payload['pull_request']['head']['repo']['name'] <add> repo_url = payload['pull_request']['head']['repo']['html_url'] <add> else: <add> user = payload['repository']['owner']['name'] <ide> repo = payload['repository']['name'] <ide> repo_url = payload['repository']['url'] <ide> project = request.args.get('project', None) <ide> def process_change(payload, user, repo, repo_url, project): <ide> Hook. <ide> """ <ide> changes = [] <del> <add> <ide> newrev = payload['after'] if 'after' in payload else payload['pull_request']['head']['sha'] <ide> refname = payload['ref'] if 'ref' in payload else payload['pull_request']['head']['ref'] <ide> <ide> def process_change(payload, user, repo, repo_url, project): <ide> log.msg("Branch `%s' deleted, ignoring" % branch) <ide> return [] <ide> else: <del> if 'pull_request' in payload: <del> changes = [{ <del> 'category' : 'github_pullrequest', <add> if 'pull_request' in payload: <add> if payload['action'] == 'closed': <add> log.msg("PR#{} closed, ignoring".format(payload['number'])) <add> return [] <add> changes = [{ <add> 'category' : 'github_pullrequest', <ide> 'who' : '{0} - PR#{1}'.format(user,payload['number']), <ide> 'files' : [], <ide> 'comments' : payload['pull_request']['title'], <ide> def process_change(payload, user, repo, repo_url, project): <ide> 'revlink' : '{0}/commit/{1}'.format(repo_url,newrev), <ide> 'repository' : repo_url, <ide> 'project' : project }] <del> return changes <add> return changes <ide> for commit in payload['commits']: <ide> files = [] <ide> if 'added' in commit: <ide> def process_change(payload, user, repo, repo_url, project): <ide> project = project) <ide> changes.append(chdict) <ide> return changes <del>
1
Text
Text
tweak some formatting of example index.ios.js
47f3a77227b6b2402e457fa025abde9e911eaa87
<ide><path>docs/EmbeddedApp.md <ide> $ mkdir ReactComponent <ide> $ touch index.ios.js <ide> ``` <ide> <del>Copy & paste following starter code for **index.ios.js**. <add>Copy & paste following starter code for `index.ios.js` – it’s a barebones React Native app: <ide> <ide> ``` <ide> 'use strict'; <ide> var styles = React.StyleSheet.create({ <ide> <ide> class SimpleApp extends React.Component { <ide> render() { <del> return <View style={styles.container}> <add> return ( <add> <View style={styles.container}> <ide> <Text>This is a simple application.</Text> <del> </View>; <add> </View> <add> ) <ide> } <ide> } <ide>
1
Javascript
Javascript
fix use of "dx" in examples
7155ffa9e317c94f99134ae5fac256dd51806b89
<ide><path>examples/bundle/bundle-radial.js <ide> d3.json("../data/flare-imports.json", function(classes) { <ide> .attr("class", "node") <ide> .attr("transform", function(d) { return "rotate(" + (d.x - 90) + ")translate(" + d.y + ")"; }) <ide> .append("text") <del> .attr("dx", function(d) { return d.x < 180 ? 8 : -8; }) <ide> .attr("dy", ".31em") <ide> .attr("text-anchor", function(d) { return d.x < 180 ? "start" : "end"; }) <del> .attr("transform", function(d) { return d.x < 180 ? null : "rotate(180)"; }) <add> .attr("transform", function(d) { return d.x < 180 ? "translate(8)" : "rotate(180)translate(-8)"; }) <ide> .text(function(d) { return d.key; }); <ide> }); <ide> <ide><path>examples/cluster/cluster-radial.js <ide> d3.json("../data/flare.json", function(json) { <ide> .attr("r", 4.5); <ide> <ide> node.append("text") <del> .attr("dx", function(d) { return d.x < 180 ? 8 : -8; }) <ide> .attr("dy", ".31em") <ide> .attr("text-anchor", function(d) { return d.x < 180 ? "start" : "end"; }) <del> .attr("transform", function(d) { return d.x < 180 ? null : "rotate(180)"; }) <add> .attr("transform", function(d) { return d.x < 180 ? "translate(8)" : "rotate(180)translate(-8)"; }) <ide> .text(function(d) { return d.name; }); <ide> }); <ide><path>examples/tree/tree-radial.js <ide> d3.json("../data/flare.json", function(json) { <ide> .attr("dx", function(d) { return d.x < 180 ? 8 : -8; }) <ide> .attr("dy", ".31em") <ide> .attr("text-anchor", function(d) { return d.x < 180 ? "start" : "end"; }) <del> .attr("transform", function(d) { return d.x < 180 ? null : "rotate(180)"; }) <add> .attr("transform", function(d) { return d.x < 180 ? "translate(8)" : "rotate(180)translate(-8)"; }) <ide> .text(function(d) { return d.name; }); <ide> });
3
Java
Java
enhance messageheaderaccessor support
4867546aec48a49a8bbfd63d86dd32a8ed5eaf83
<ide><path>spring-messaging/src/main/java/org/springframework/messaging/MessageHeaders.java <ide> import java.util.Collection; <ide> import java.util.Collections; <ide> import java.util.HashMap; <del>import java.util.LinkedHashMap; <ide> import java.util.List; <ide> import java.util.Map; <ide> import java.util.Set; <ide> import org.apache.commons.logging.LogFactory; <ide> <ide> import org.springframework.util.AlternativeJdkIdGenerator; <del>import org.springframework.util.Assert; <ide> import org.springframework.util.IdGenerator; <ide> <ide> /** <ide> */ <ide> public class MessageHeaders implements Map<String, Object>, Serializable { <ide> <del> private static final long serialVersionUID = -4615750558355702881L; <add> private static final long serialVersionUID = 7035068984263400920L; <ide> <ide> private static final Log logger = LogFactory.getLog(MessageHeaders.class); <ide> <add> public static final UUID ID_VALUE_NONE = new UUID(0,0); <add> <ide> private static volatile IdGenerator idGenerator = null; <ide> <ide> private static final IdGenerator defaultIdGenerator = new AlternativeJdkIdGenerator(); <ide> public class MessageHeaders implements Map<String, Object>, Serializable { <ide> <ide> <ide> /** <del> * Consructs a {@link MessageHeaders} from the headers map; adding (or <del> * overwriting) the {@link #ID} and {@link #TIMESTAMP} headers. <add> * Construct a {@link MessageHeaders} with the given headers. An {@link #ID} and <add> * {@link #TIMESTAMP} headers will also be added, overriding any existing values. <add> * <ide> * @param headers a map with headers to add <ide> */ <ide> public MessageHeaders(Map<String, Object> headers) { <del> this(headers, ((idGenerator != null) ? idGenerator : defaultIdGenerator).generateId(), <del> System.currentTimeMillis()); <add> this(headers, null, null); <ide> } <ide> <ide> /** <del> * Constructor allowing a sub-class to access the (mutable) header map as well <del> * to provide the ID and TIMESTAMP header values. <add> * Constructor providing control over the ID and TIMESTAMP header values. <ide> * <ide> * @param headers a map with headers to add <del> * @param id the value for the {@link #ID} header, never {@code null} <del> * @param timestamp the value for the {@link #TIMESTAMP} header, <del> * or {@code null} meaning no timestamp header <add> * @param id the {@link #ID} header value <add> * @param timestamp the {@link #TIMESTAMP} header value <ide> */ <ide> protected MessageHeaders(Map<String, Object> headers, UUID id, Long timestamp) { <del> Assert.notNull(id, "'id' is required"); <add> <ide> this.headers = (headers != null) ? new HashMap<String, Object>(headers) : new HashMap<String, Object>(); <del> this.headers.put(ID, id); <del> if (timestamp != null) { <add> <add> if (id == null) { <add> this.headers.put(ID, getIdGenerator().generateId()); <add> } <add> else if (id == ID_VALUE_NONE) { <add> this.headers.remove(ID); <add> } <add> else { <add> this.headers.put(ID, id); <add> } <add> <add> if (timestamp == null) { <add> this.headers.put(TIMESTAMP, System.currentTimeMillis()); <add> } <add> else if (timestamp < 0) { <add> this.headers.remove(TIMESTAMP); <add> } <add> else { <ide> this.headers.put(TIMESTAMP, timestamp); <ide> } <ide> } <ide> protected Map<String, Object> getRawHeaders() { <ide> return this.headers; <ide> } <ide> <add> protected static IdGenerator getIdGenerator() { <add> return ((idGenerator != null) ? idGenerator : defaultIdGenerator); <add> } <add> <ide> public UUID getId() { <ide> return this.get(ID, UUID.class); <ide> } <ide> public boolean equals(Object object) { <ide> <ide> @Override <ide> public String toString() { <del> Map<String, Object> map = new LinkedHashMap<String, Object>(this.headers); <del> map.put(ID, map.remove(ID)); // remove and add again at the end <del> map.put(TIMESTAMP, map.remove(TIMESTAMP)); <del> return map.toString(); <add> return this.headers.toString(); <ide> } <ide> <ide> /* <ide><path>spring-messaging/src/main/java/org/springframework/messaging/simp/DefaultSimpMessageHeaderAccessorFactory.java <add>/* <add> * Copyright 2002-2014 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add> <add>package org.springframework.messaging.simp; <add> <add>import org.springframework.messaging.Message; <add>import org.springframework.messaging.MessageHeaders; <add>import org.springframework.messaging.support.MessageHeaderAccessorFactorySupport; <add>import org.springframework.util.IdGenerator; <add> <add>import java.util.UUID; <add> <add>/** <add> * A default implementation of <add> * {@link org.springframework.messaging.simp.SimpMessageHeaderAccessorFactory}. <add> * <add> * @author Rossen Stoyanchev <add> * @since 4.1 <add> */ <add>public class DefaultSimpMessageHeaderAccessorFactory extends MessageHeaderAccessorFactorySupport <add> implements SimpMessageHeaderAccessorFactory { <add> <add> <add> public DefaultSimpMessageHeaderAccessorFactory() { <add> super.setIdGenerator(ID_VALUE_NONE_GENERATOR); <add> } <add> <add> <add> @Override <add> public SimpMessageHeaderAccessor create() { <add> SimpMessageHeaderAccessor accessor = new SimpMessageHeaderAccessor(SimpMessageType.MESSAGE, null); <add> updateMessageHeaderAccessor(accessor); <add> return accessor; <add> } <add> <add> @Override <add> public SimpMessageHeaderAccessor create(SimpMessageType messageType) { <add> SimpMessageHeaderAccessor accessor = new SimpMessageHeaderAccessor(messageType, null); <add> updateMessageHeaderAccessor(accessor); <add> return accessor; <add> } <add> <add> @Override <add> public SimpMessageHeaderAccessor wrap(Message<?> message) { <add> SimpMessageHeaderAccessor accessor = new SimpMessageHeaderAccessor(message); <add> updateMessageHeaderAccessor(accessor); <add> return accessor; <add> } <add> <add> <add> private static final IdGenerator ID_VALUE_NONE_GENERATOR = new IdGenerator() { <add> @Override <add> public UUID generateId() { <add> return MessageHeaders.ID_VALUE_NONE; <add> } <add> }; <add>} <ide><path>spring-messaging/src/main/java/org/springframework/messaging/simp/SimpMessageHeaderAccessor.java <ide> import java.util.Map; <ide> <ide> import org.springframework.messaging.Message; <add>import org.springframework.messaging.MessageHeaders; <add>import org.springframework.messaging.support.MessageHeaderAccessor; <ide> import org.springframework.messaging.support.NativeMessageHeaderAccessor; <ide> import org.springframework.util.Assert; <ide> <ide> */ <ide> public class SimpMessageHeaderAccessor extends NativeMessageHeaderAccessor { <ide> <add> private static final SimpMessageHeaderAccessorFactory factory = new DefaultSimpMessageHeaderAccessorFactory(); <add> <add> // SiMP header names <add> <ide> public static final String CONNECT_MESSAGE_HEADER = "simpConnectMessage"; <ide> <ide> public static final String DESTINATION_HEADER = "simpDestination"; <ide> protected SimpMessageHeaderAccessor(Message<?> message) { <ide> <ide> <ide> /** <del> * Create {@link SimpMessageHeaderAccessor} for a new {@link Message} with <del> * {@link SimpMessageType#MESSAGE}. <add> * Create an instance with <add> * {@link org.springframework.messaging.simp.SimpMessageType} {@code MESSAGE}. <ide> */ <ide> public static SimpMessageHeaderAccessor create() { <del> return new SimpMessageHeaderAccessor(SimpMessageType.MESSAGE, null); <add> return factory.create(); <ide> } <ide> <ide> /** <del> * Create {@link SimpMessageHeaderAccessor} for a new {@link Message} of a specific type. <add> * Create an instance with the given <add> * {@link org.springframework.messaging.simp.SimpMessageType}. <ide> */ <ide> public static SimpMessageHeaderAccessor create(SimpMessageType messageType) { <del> return new SimpMessageHeaderAccessor(messageType, null); <add> return factory.create(messageType); <ide> } <ide> <ide> /** <del> * Create {@link SimpMessageHeaderAccessor} from the headers of an existing message. <add> * Create an instance from the payload and headers of the given Message. <ide> */ <ide> public static SimpMessageHeaderAccessor wrap(Message<?> message) { <del> return new SimpMessageHeaderAccessor(message); <add> return factory.wrap(message); <add> } <add> <add> <add> @Override <add> protected MessageHeaderAccessor createAccessor(Message<?> message) { <add> return factory.wrap(message); <ide> } <ide> <ide> public void setMessageTypeIfNotSet(SimpMessageType messageType) { <ide> public SimpMessageType getMessageType() { <ide> return (SimpMessageType) getHeader(MESSAGE_TYPE_HEADER); <ide> } <ide> <add> /** <add> * A static alternative for access to the message type. <add> */ <add> public static SimpMessageType getMessageType(Map<String, Object> headers) { <add> return (SimpMessageType) headers.get(MESSAGE_TYPE_HEADER); <add> } <add> <ide> public void setDestination(String destination) { <ide> Assert.notNull(destination, "Destination must not be null"); <ide> setHeader(DESTINATION_HEADER, destination); <ide> public String getDestination() { <ide> return (String) getHeader(DESTINATION_HEADER); <ide> } <ide> <add> /** <add> * A static alternative for access to the destination header. <add> */ <add> public static String getDestination(Map<String, Object> headers) { <add> return (String) headers.get(DESTINATION_HEADER); <add> } <add> <add> public void setSubscriptionId(String subscriptionId) { <add> setHeader(SUBSCRIPTION_ID_HEADER, subscriptionId); <add> } <add> <ide> /** <ide> * @return the subscription id (if any) of the message <ide> */ <ide> public String getSubscriptionId() { <ide> return (String) getHeader(SUBSCRIPTION_ID_HEADER); <ide> } <ide> <del> public void setSubscriptionId(String subscriptionId) { <del> setHeader(SUBSCRIPTION_ID_HEADER, subscriptionId); <add> /** <add> * A static alternative for access to the subscription id header. <add> */ <add> public static String getSubscriptionId(Map<String, Object> headers) { <add> return (String) headers.get(SUBSCRIPTION_ID_HEADER); <add> } <add> <add> public void setSessionId(String sessionId) { <add> setHeader(SESSION_ID_HEADER, sessionId); <ide> } <ide> <ide> /** <ide> public String getSessionId() { <ide> return (String) getHeader(SESSION_ID_HEADER); <ide> } <ide> <del> public void setSessionId(String sessionId) { <del> setHeader(SESSION_ID_HEADER, sessionId); <add> /** <add> * A static alternative for access to the session id header. <add> */ <add> public static String getSessionId(Map<String, Object> headers) { <add> return (String) headers.get(SESSION_ID_HEADER); <add> } <add> <add> /** <add> * A static alternative for access to the session attributes header. <add> */ <add> public void setSessionAttributes(Map<String, Object> attributes) { <add> setHeader(SESSION_ATTRIBUTES, attributes); <ide> } <ide> <ide> /** <ide> public Map<String, Object> getSessionAttributes() { <ide> return (Map<String, Object>) getHeader(SESSION_ATTRIBUTES); <ide> } <ide> <del> public void setSessionAttributes(Map<String, Object> attributes) { <del> setHeader(SESSION_ATTRIBUTES, attributes); <add> /** <add> * A static alternative for access to the session attributes header. <add> */ <add> @SuppressWarnings("unchecked") <add> public static Map<String, Object> getSessionAttributes(Map<String, Object> headers) { <add> return (Map<String, Object>) headers.get(SESSION_ATTRIBUTES); <add> } <add> <add> public void setUser(Principal principal) { <add> setHeader(USER_HEADER, principal); <ide> } <ide> <ide> /** <ide> public Principal getUser() { <ide> return (Principal) getHeader(USER_HEADER); <ide> } <ide> <del> public void setUser(Principal principal) { <del> setHeader(USER_HEADER, principal); <add> /** <add> * A static alternative for access to the user header. <add> */ <add> public static Principal getUser(Map<String, Object> headers) { <add> return (Principal) headers.get(USER_HEADER); <ide> } <ide> <ide> } <ide><path>spring-messaging/src/main/java/org/springframework/messaging/simp/SimpMessageHeaderAccessorFactory.java <add>/* <add> * Copyright 2002-2014 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add> <add>package org.springframework.messaging.simp; <add> <add> <add>import org.springframework.messaging.Message; <add> <add>/** <add> * A factory for creating pre-configured instances of type <add> * {@link org.springframework.messaging.simp.SimpMessageHeaderAccessor}. <add> * <add> * @author Rossen Stoyanchev <add> * @since 4.1 <add> */ <add>public interface SimpMessageHeaderAccessorFactory { <add> <add> /** <add> * Create an instance with <add> * {@link org.springframework.messaging.simp.SimpMessageType} {@code MESSAGE}. <add> */ <add> SimpMessageHeaderAccessor create(); <add> <add> /** <add> * Create an instance with the given <add> * {@link org.springframework.messaging.simp.SimpMessageType}. <add> */ <add> SimpMessageHeaderAccessor create(SimpMessageType messageType); <add> <add> /** <add> * Create an instance from the payload and headers of the given Message. <add> */ <add> SimpMessageHeaderAccessor wrap(Message<?> message); <add> <add>} <ide><path>spring-messaging/src/main/java/org/springframework/messaging/simp/broker/AbstractBrokerMessageHandler.java <ide> public final void stop(Runnable callback) { <ide> public final void handleMessage(Message<?> message) { <ide> if (!this.running) { <ide> if (logger.isTraceEnabled()) { <del> logger.trace("Message broker is not running. Ignoring message id=" + message.getHeaders().getId()); <add> logger.trace("Message broker is not running. Ignoring message=" + message); <ide> } <ide> return; <ide> } <ide><path>spring-messaging/src/main/java/org/springframework/messaging/simp/stomp/BufferingStompDecoder.java <ide> public List<Message<byte[]>> decode(ByteBuffer newBuffer) { <ide> <ide> if (bufferToDecode.hasRemaining()) { <ide> this.chunks.add(bufferToDecode); <del> this.expectedContentLength = getContentLength(headers); <add> this.expectedContentLength = StompHeaderAccessor.getContentLength(headers); <ide> } <ide> <ide> return messages; <ide><path>spring-messaging/src/main/java/org/springframework/messaging/simp/stomp/DefaultStompHeaderAccessorFactory.java <add>/* <add> * Copyright 2002-2014 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add> <add>package org.springframework.messaging.simp.stomp; <add> <add>import org.springframework.messaging.Message; <add>import org.springframework.messaging.MessageHeaders; <add>import org.springframework.messaging.support.MessageHeaderAccessorFactorySupport; <add>import org.springframework.util.IdGenerator; <add> <add>import java.util.List; <add>import java.util.Map; <add>import java.util.UUID; <add> <add>/** <add> * A default implementation of <add> * {@link org.springframework.messaging.simp.stomp.StompHeaderAccessorFactory}. <add> * <add> * @author Rossen Stoyanchev <add> * @since 4.1 <add> */ <add>public class DefaultStompHeaderAccessorFactory extends MessageHeaderAccessorFactorySupport <add> implements StompHeaderAccessorFactory { <add> <add> <add> public DefaultStompHeaderAccessorFactory() { <add> super.setIdGenerator(ID_VALUE_NONE_GENERATOR); <add> } <add> <add> <add> @Override <add> public StompHeaderAccessor create(StompCommand command) { <add> StompHeaderAccessor accessor = new StompHeaderAccessor(command, null); <add> updateMessageHeaderAccessor(accessor); <add> return accessor; <add> } <add> <add> @Override <add> public StompHeaderAccessor create(StompCommand command, Map<String, List<String>> headers) { <add> StompHeaderAccessor accessor = new StompHeaderAccessor(command, headers); <add> updateMessageHeaderAccessor(accessor); <add> return accessor; <add> } <add> <add> @Override <add> public StompHeaderAccessor createForHeartbeat() { <add> StompHeaderAccessor accessor = new StompHeaderAccessor(); <add> updateMessageHeaderAccessor(accessor); <add> return accessor; <add> } <add> <add> @Override <add> public StompHeaderAccessor wrap(Message<?> message) { <add> StompHeaderAccessor accessor = new StompHeaderAccessor(message); <add> updateMessageHeaderAccessor(accessor); <add> return accessor; <add> } <add> <add> private static final IdGenerator ID_VALUE_NONE_GENERATOR = new IdGenerator() { <add> @Override <add> public UUID generateId() { <add> return MessageHeaders.ID_VALUE_NONE; <add> } <add> }; <add>} <ide><path>spring-messaging/src/main/java/org/springframework/messaging/simp/stomp/StompDecoder.java <ide> import org.apache.commons.logging.LogFactory; <ide> <ide> import org.springframework.messaging.Message; <del>import org.springframework.messaging.simp.SimpMessageType; <ide> import org.springframework.messaging.support.MessageBuilder; <del>import org.springframework.util.Assert; <del>import org.springframework.util.LinkedMultiValueMap; <add>import org.springframework.messaging.support.NativeMessageHeaderAccessor; <add>import org.springframework.util.InvalidMimeTypeException; <ide> import org.springframework.util.MultiValueMap; <ide> <ide> /** <ide> */ <ide> public class StompDecoder { <ide> <del> private static final Charset UTF8_CHARSET = Charset.forName("UTF-8"); <add> static final Charset UTF8_CHARSET = Charset.forName("UTF-8"); <ide> <del> private static final byte[] HEARTBEAT_PAYLOAD = new byte[] {'\n'}; <add> static final byte[] HEARTBEAT_PAYLOAD = new byte[] {'\n'}; <ide> <ide> private final Log logger = LogFactory.getLog(StompDecoder.class); <ide> <ide> public class StompDecoder { <ide> * @return the decoded messages or an empty list <ide> */ <ide> public List<Message<byte[]>> decode(ByteBuffer buffer) { <del> return decode(buffer, new LinkedMultiValueMap<String, String>()); <add> return decode(buffer, null); <ide> } <ide> <ide> /** <ide> public List<Message<byte[]>> decode(ByteBuffer buffer) { <ide> * <p>If the buffer contains one ore more STOMP frames, those are returned and <ide> * the buffer reset to point to the beginning of the unused partial content. <ide> * <del> * <p>The input headers map is used to store successfully parsed headers and <del> * is cleared after ever successfully read message. So when partial content is <del> * read the caller can check if a "content-length" header was read, which helps <del> * to determine how much more content is needed before the next STOMP frame <del> * can be decoded. <add> * <p>The output partialMessageHeaders map is used to store successfully parsed <add> * headers in case of partial content. The caller can then check if a <add> * "content-length" header was read, which helps to determine how much more <add> * content is needed before the next attempt to decode. <ide> * <ide> * @param buffer The buffer to decode the STOMP frame from <del> * @param headers an empty map that will contain successfully parsed headers <add> * @param partialMessageHeaders an empty output map that will store the last <add> * successfully parsed partialMessageHeaders in case of partial message content <ide> * in cases where the partial buffer ended with a partial STOMP frame <ide> * <ide> * @return decoded messages or an empty list <ide> * @throws StompConversionException raised in case of decoding issues <ide> */ <del> public List<Message<byte[]>> decode(ByteBuffer buffer, MultiValueMap<String, String> headers) { <del> Assert.notNull(headers, "headers is required"); <add> public List<Message<byte[]>> decode(ByteBuffer buffer, MultiValueMap<String, String> partialMessageHeaders) { <ide> List<Message<byte[]>> messages = new ArrayList<Message<byte[]>>(); <ide> while (buffer.hasRemaining()) { <del> Message<byte[]> m = decodeMessage(buffer, headers); <add> Message<byte[]> m = decodeMessage(buffer, partialMessageHeaders); <ide> if (m != null) { <ide> messages.add(m); <del> headers.clear(); <ide> } <ide> else { <ide> break; <ide> private Message<byte[]> decodeMessage(ByteBuffer buffer, MultiValueMap<String, S <ide> String command = readCommand(buffer); <ide> if (command.length() > 0) { <ide> <del> readHeaders(buffer, headers); <del> byte[] payload = readPayload(buffer, headers); <add> StompHeaderAccessor headerAccessor = null; <add> byte[] payload = null; <ide> <del> if (payload != null) { <add> if (buffer.remaining() > 0) { <ide> StompCommand stompCommand = StompCommand.valueOf(command); <del> if ((payload.length > 0) && (!stompCommand.isBodyAllowed())) { <del> throw new StompConversionException(stompCommand + " shouldn't have but " + <del> "has a payload with length=" + payload.length + ", headers=" + headers); <add> headerAccessor = StompHeaderAccessor.create(stompCommand); <add> <add> readHeaders(buffer, headerAccessor); <add> payload = readPayload(buffer, headerAccessor); <add> } <add> <add> if (payload != null) { <add> if ((payload.length > 0) && (!headerAccessor.getCommand().isBodyAllowed())) { <add> throw new StompConversionException(headerAccessor.getCommand() + <add> " shouldn't have a payload: length=" + payload.length + ", headers=" + headers); <ide> } <del> decodedMessage = MessageBuilder.withPayload(payload) <del> .setHeaders(StompHeaderAccessor.create(stompCommand, headers)).build(); <add> headerAccessor.updateSimpMessageHeadersFromStompHeaders(); <add> headerAccessor.setLeaveMutable(true); <add> decodedMessage = MessageBuilder.createMessage(payload, headerAccessor.getMessageHeaders()); <ide> if (logger.isDebugEnabled()) { <ide> logger.debug("Decoded " + decodedMessage); <ide> } <ide> private Message<byte[]> decodeMessage(ByteBuffer buffer, MultiValueMap<String, S <ide> if (logger.isTraceEnabled()) { <ide> logger.trace("Received incomplete frame. Resetting buffer."); <ide> } <add> if (headers != null && headerAccessor != null) { <add> String name = NativeMessageHeaderAccessor.NATIVE_HEADERS; <add> @SuppressWarnings("unchecked") <add> MultiValueMap<String, String> map = (MultiValueMap<String, String>) headerAccessor.getHeader(name); <add> if (map != null) { <add> headers.putAll(map); <add> } <add> } <ide> buffer.reset(); <ide> } <ide> } <ide> else { <ide> if (logger.isTraceEnabled()) { <ide> logger.trace("Decoded heartbeat"); <ide> } <del> decodedMessage = MessageBuilder.withPayload(HEARTBEAT_PAYLOAD).setHeaders( <del> StompHeaderAccessor.create(SimpMessageType.HEARTBEAT)).build(); <add> StompHeaderAccessor headerAccessor = StompHeaderAccessor.createForHeartbeat(); <add> headerAccessor.setLeaveMutable(true); <add> decodedMessage = MessageBuilder.createMessage(HEARTBEAT_PAYLOAD, headerAccessor.getMessageHeaders()); <ide> } <ide> return decodedMessage; <ide> } <ide> private String readCommand(ByteBuffer buffer) { <ide> return new String(command.toByteArray(), UTF8_CHARSET); <ide> } <ide> <del> private void readHeaders(ByteBuffer buffer, MultiValueMap<String, String> headers) { <add> private void readHeaders(ByteBuffer buffer, StompHeaderAccessor headerAccessor) { <ide> while (true) { <ide> ByteArrayOutputStream headerStream = new ByteArrayOutputStream(256); <ide> while (buffer.remaining() > 0 && !tryConsumeEndOfLine(buffer)) { <ide> private void readHeaders(ByteBuffer buffer, MultiValueMap<String, String> header <ide> else { <ide> String headerName = unescape(header.substring(0, colonIndex)); <ide> String headerValue = unescape(header.substring(colonIndex + 1)); <del> headers.add(headerName, headerValue); <add> try { <add> headerAccessor.addNativeHeader(headerName, headerValue); <add> } <add> catch (InvalidMimeTypeException ex) { <add> if (buffer.remaining() > 0) { <add> throw ex; <add> } <add> } <ide> } <ide> } <ide> else { <ide> else if (c == '\\') { <ide> return sb.toString(); <ide> } <ide> <del> private byte[] readPayload(ByteBuffer buffer, MultiValueMap<String, String> headers) { <del> Integer contentLength = getContentLength(headers); <add> private byte[] readPayload(ByteBuffer buffer, StompHeaderAccessor headerAccessor) { <add> <add> Integer contentLength; <add> try { <add> contentLength = headerAccessor.getContentLength(); <add> } <add> catch (NumberFormatException ex) { <add> logger.warn("Ignoring invalid content-length: '" + headerAccessor); <add> contentLength = null; <add> } <add> <ide> if (contentLength != null && contentLength >= 0) { <ide> if (buffer.remaining() > contentLength) { <ide> byte[] payload = new byte[contentLength]; <ide> private byte[] readPayload(ByteBuffer buffer, MultiValueMap<String, String> head <ide> return null; <ide> } <ide> <del> protected Integer getContentLength(MultiValueMap<String, String> headers) { <del> if (headers.containsKey(StompHeaderAccessor.STOMP_CONTENT_LENGTH_HEADER)) { <del> String rawContentLength = headers.getFirst(StompHeaderAccessor.STOMP_CONTENT_LENGTH_HEADER); <del> try { <del> return Integer.valueOf(rawContentLength); <del> } <del> catch (NumberFormatException ex) { <del> logger.warn("Ignoring invalid content-length header value: '" + rawContentLength + "'"); <del> } <del> } <del> return null; <del> } <del> <ide> /** <ide> * Try to read an EOL incrementing the buffer position if successful. <ide> * <ide><path>spring-messaging/src/main/java/org/springframework/messaging/simp/stomp/StompEncoder.java <ide> import java.io.ByteArrayOutputStream; <ide> import java.io.DataOutputStream; <ide> import java.io.IOException; <del>import java.nio.charset.Charset; <add>import java.util.Arrays; <ide> import java.util.List; <ide> import java.util.Map; <ide> import java.util.Map.Entry; <ide> import org.apache.commons.logging.LogFactory; <ide> <ide> import org.springframework.messaging.Message; <add>import org.springframework.messaging.simp.SimpMessageHeaderAccessor; <ide> import org.springframework.messaging.simp.SimpMessageType; <add>import org.springframework.messaging.support.NativeMessageHeaderAccessor; <add>import org.springframework.util.Assert; <ide> <ide> /** <ide> * An encoder for STOMP frames. <ide> public final class StompEncoder { <ide> <ide> private static final byte COLON = ':'; <ide> <del> private static final Charset UTF8_CHARSET = Charset.forName("UTF-8"); <del> <ide> private final Log logger = LogFactory.getLog(StompEncoder.class); <ide> <ide> <ide> /** <ide> * Encodes the given STOMP {@code message} into a {@code byte[]} <add> * <ide> * @param message the message to encode <ide> * @return the encoded message <ide> */ <ide> public byte[] encode(Message<byte[]> message) { <add> return encode(message.getHeaders(), message.getPayload()); <add> } <add> <add> /** <add> * Encodes the given payload and headers into a {@code byte[]}. <add> * <add> * @param headers the headers <add> * @param payload the payload <add> * @return the encoded message <add> */ <add> public byte[] encode(Map<String, Object> headers, byte[] payload) { <add> Assert.notNull(headers, "'headers' is required"); <add> Assert.notNull(payload, "'payload' is required"); <ide> try { <del> ByteArrayOutputStream baos = new ByteArrayOutputStream(128 + message.getPayload().length); <add> ByteArrayOutputStream baos = new ByteArrayOutputStream(128 + payload.length); <ide> DataOutputStream output = new DataOutputStream(baos); <ide> <del> StompHeaderAccessor headers = StompHeaderAccessor.wrap(message); <del> if (SimpMessageType.HEARTBEAT == headers.getMessageType()) { <add> if (SimpMessageType.HEARTBEAT.equals(SimpMessageHeaderAccessor.getMessageType(headers))) { <ide> logger.trace("Encoded heartbeat"); <del> output.write(message.getPayload()); <add> output.write(StompDecoder.HEARTBEAT_PAYLOAD); <ide> } <ide> else { <del> output.write(headers.getCommand().toString().getBytes(UTF8_CHARSET)); <add> StompCommand command = StompHeaderAccessor.getCommand(headers); <add> Assert.notNull(command, "Missing STOMP command: " + headers); <add> output.write(command.toString().getBytes(StompDecoder.UTF8_CHARSET)); <ide> output.write(LF); <del> writeHeaders(headers, message, output); <add> writeHeaders(command, headers, payload, output); <ide> output.write(LF); <del> writeBody(message, output); <add> writeBody(payload, output); <ide> output.write((byte) 0); <ide> } <ide> <ide> public byte[] encode(Message<byte[]> message) { <ide> } <ide> } <ide> <del> private void writeHeaders(StompHeaderAccessor headers, Message<byte[]> message, DataOutputStream output) <add> private void writeHeaders(StompCommand command, Map<String, Object> headers, byte[] payload, DataOutputStream output) <ide> throws IOException { <ide> <del> StompCommand command = headers.getCommand(); <del> Map<String,List<String>> stompHeaders = headers.toStompHeaderMap(); <del> boolean shouldEscape = (command != StompCommand.CONNECT && command != StompCommand.CONNECTED); <add> @SuppressWarnings("unchecked") <add> Map<String,List<String>> nativeHeaders = <add> (Map<String, List<String>>) headers.get(NativeMessageHeaderAccessor.NATIVE_HEADERS); <ide> <ide> if (logger.isDebugEnabled()) { <del> logger.debug("Encoded STOMP " + command + ", headers=" + stompHeaders); <add> logger.debug("Encoding STOMP " + command + ", headers=" + nativeHeaders); <add> } <add> <add> if (nativeHeaders == null) { <add> return; <ide> } <ide> <del> for (Entry<String, List<String>> entry : stompHeaders.entrySet()) { <add> boolean shouldEscape = (command != StompCommand.CONNECT && command != StompCommand.CONNECTED); <add> <add> for (Entry<String, List<String>> entry : nativeHeaders.entrySet()) { <ide> byte[] key = encodeHeaderString(entry.getKey(), shouldEscape); <del> for (String value : entry.getValue()) { <add> List<String> values = entry.getValue(); <add> if (StompHeaderAccessor.STOMP_PASSCODE_HEADER.equals(entry.getKey())) { <add> values = Arrays.asList(StompHeaderAccessor.getPasscode(headers)); <add> } <add> for (String value : values) { <ide> output.write(key); <ide> output.write(COLON); <ide> output.write(encodeHeaderString(value, shouldEscape)); <ide> output.write(LF); <ide> } <ide> } <ide> if (command.requiresContentLength()) { <del> int contentLength = message.getPayload().length; <del> output.write("content-length:".getBytes(UTF8_CHARSET)); <del> output.write(Integer.toString(contentLength).getBytes(UTF8_CHARSET)); <add> int contentLength = payload.length; <add> output.write("content-length:".getBytes(StompDecoder.UTF8_CHARSET)); <add> output.write(Integer.toString(contentLength).getBytes(StompDecoder.UTF8_CHARSET)); <ide> output.write(LF); <ide> } <ide> } <ide> <ide> private byte[] encodeHeaderString(String input, boolean escape) { <ide> input = escape ? escape(input) : input; <del> return input.getBytes(UTF8_CHARSET); <add> return input.getBytes(StompDecoder.UTF8_CHARSET); <ide> } <ide> <ide> /** <ide> else if (c == '\r') { <ide> return sb.toString(); <ide> } <ide> <del> private void writeBody(Message<byte[]> message, DataOutputStream output) throws IOException { <del> output.write(message.getPayload()); <add> private void writeBody(byte[] payload, DataOutputStream output) throws IOException { <add> output.write(payload); <ide> } <ide> <ide> } <ide><path>spring-messaging/src/main/java/org/springframework/messaging/simp/stomp/StompHeaderAccessor.java <ide> import org.springframework.messaging.Message; <ide> import org.springframework.messaging.simp.SimpMessageHeaderAccessor; <ide> import org.springframework.messaging.simp.SimpMessageType; <add>import org.springframework.messaging.support.MessageHeaderAccessor; <ide> import org.springframework.util.Assert; <del>import org.springframework.util.CollectionUtils; <ide> import org.springframework.util.MimeType; <ide> import org.springframework.util.MimeTypeUtils; <add>import org.springframework.util.MultiValueMap; <ide> import org.springframework.util.StringUtils; <ide> <ide> /** <del> * Can be used to prepare headers for a new STOMP message, or to access and/or modify <del> * STOMP-specific headers of an existing message. <add> * A {@code MessageHeaderAccessor} to use when creating a {@code Message} from a <add> * decoded STOMP frame, or when encoding a {@code Message} to a STOMP frame. <ide> * <del> * <p>Use one of the static factory method in this class, then call getters and setters, <del> * and at the end if necessary call {@link #toMap()} to obtain the updated headers <del> * or call {@link #toNativeHeaderMap()} to obtain only the STOMP-specific headers. <add> * <p>When created from STOMP frame content, the actual STOMP headers are stored <add> * in the native header sub-map managed by the parent class <add> * {@link org.springframework.messaging.support.NativeMessageHeaderAccessor} <add> * while the parent class <add> * {@link org.springframework.messaging.simp.SimpMessageHeaderAccessor} manages <add> * common processing headers some of which are based on STOMP headers (e.g. <add> * destination, content-type, etc). <add> * <add> * <p>An instance of this class can also be created by wrapping an existing <add> * {@code Message}. That message may have been created with the more generic <add> * {@link org.springframework.messaging.simp.SimpMessageHeaderAccessor} in <add> * which case STOMP headers are created from common processing headers. <add> * In this case it is also necessary to invoke either <add> * {@link #updateStompCommandAsClientMessage()} or <add> * {@link #updateStompCommandAsServerMessage()} if sending a message and <add> * depending on whether a message is sent to a client or the message broker. <ide> * <ide> * @author Rossen Stoyanchev <ide> * @since 4.0 <ide> */ <ide> public class StompHeaderAccessor extends SimpMessageHeaderAccessor { <ide> <add> private static final StompHeaderAccessorFactory factory = new DefaultStompHeaderAccessorFactory(); <add> <ide> private static final AtomicLong messageIdCounter = new AtomicLong(); <ide> <add> private static final long[] DEFAULT_HEARTBEAT = new long[] {0, 0}; <add> <ide> // STOMP header names <ide> <ide> public static final String STOMP_ID_HEADER = "id"; <ide> public class StompHeaderAccessor extends SimpMessageHeaderAccessor { <ide> <ide> public static final String STOMP_HEARTBEAT_HEADER = "heart-beat"; <ide> <del> private static final long[] DEFAULT_HEARTBEAT = new long[] {0, 0}; <del> <del> <ide> // Other header names <ide> <ide> private static final String COMMAND_HEADER = "stompCommand"; <ide> public class StompHeaderAccessor extends SimpMessageHeaderAccessor { <ide> <ide> <ide> /** <del> * A constructor for creating new STOMP message headers. <add> * A constructor for creating message headers from a parsed STOMP frame. <ide> */ <del> private StompHeaderAccessor(StompCommand command, Map<String, List<String>> externalSourceHeaders) { <del> <add> StompHeaderAccessor(StompCommand command, Map<String, List<String>> externalSourceHeaders) { <ide> super(command.getMessageType(), externalSourceHeaders); <del> <del> Assert.notNull(command, "Command must not be null"); <ide> setHeader(COMMAND_HEADER, command); <add> updateSimpMessageHeadersFromStompHeaders(); <add> } <ide> <del> if (externalSourceHeaders != null) { <del> setSimpMessageHeaders(command, externalSourceHeaders); <del> } <add> /** <add> * A constructor for accessing and modifying existing message headers. <add> * Note that the message headers may not have been created from a STOMP frame <add> * but may have rather originated from using the more generic <add> * {@link org.springframework.messaging.simp.SimpMessageHeaderAccessor}. <add> */ <add> StompHeaderAccessor(Message<?> message) { <add> super(message); <add> updateStompHeadersFromSimpMessageHeaders(); <ide> } <ide> <del> private void setSimpMessageHeaders(StompCommand command, Map<String, List<String>> extHeaders) { <add> StompHeaderAccessor() { <add> super(SimpMessageType.HEARTBEAT, null); <add> } <ide> <del> List<String> values = extHeaders.get(StompHeaderAccessor.STOMP_DESTINATION_HEADER); <del> if (!CollectionUtils.isEmpty(values)) { <del> super.setDestination(values.get(0)); <add> void updateSimpMessageHeadersFromStompHeaders() { <add> if (getNativeHeaders() == null) { <add> return; <ide> } <del> <del> values = extHeaders.get(StompHeaderAccessor.STOMP_CONTENT_TYPE_HEADER); <del> if (!CollectionUtils.isEmpty(values)) { <del> super.setContentType(MimeTypeUtils.parseMimeType(values.get(0))); <add> String value = getFirstNativeHeader(STOMP_DESTINATION_HEADER); <add> if (value != null) { <add> super.setDestination(value); <ide> } <del> <del> if (StompCommand.SUBSCRIBE.equals(command) || StompCommand.UNSUBSCRIBE.equals(command)) { <del> values = extHeaders.get(StompHeaderAccessor.STOMP_ID_HEADER); <del> if (!CollectionUtils.isEmpty(values)) { <del> super.setSubscriptionId(values.get(0)); <add> value = getFirstNativeHeader(STOMP_CONTENT_TYPE_HEADER); <add> if (value != null) { <add> super.setContentType(MimeTypeUtils.parseMimeType(value)); <add> } <add> StompCommand command = getCommand(); <add> if (StompCommand.MESSAGE.equals(command)) { <add> value = getFirstNativeHeader(STOMP_SUBSCRIPTION_HEADER); <add> if (value != null) { <add> super.setSubscriptionId(value); <ide> } <ide> } <del> else if (StompCommand.MESSAGE.equals(command)) { <del> values = extHeaders.get(StompHeaderAccessor.STOMP_SUBSCRIPTION_HEADER); <del> if (!CollectionUtils.isEmpty(values)) { <del> super.setSubscriptionId(values.get(0)); <add> else if (StompCommand.SUBSCRIBE.equals(command) || StompCommand.UNSUBSCRIBE.equals(command)) { <add> value = getFirstNativeHeader(STOMP_ID_HEADER); <add> if (value != null) { <add> super.setSubscriptionId(value); <ide> } <ide> } <ide> else if (StompCommand.CONNECT.equals(command)) { <del> if (!StringUtils.isEmpty(getPasscode())) { <del> setHeader(CREDENTIALS_HEADER, new StompPasscode(getPasscode())); <del> setPasscode("PROTECTED"); <del> } <add> protectPasscode(); <ide> } <ide> } <ide> <del> /** <del> * A constructor for accessing and modifying existing message headers. <del> */ <del> private StompHeaderAccessor(Message<?> message) { <del> super(message); <add> private void updateStompHeadersFromSimpMessageHeaders() { <add> if (getDestination() != null) { <add> setNativeHeader(STOMP_DESTINATION_HEADER, getDestination()); <add> } <add> if (getContentType() != null) { <add> setNativeHeader(STOMP_CONTENT_TYPE_HEADER, getContentType().toString()); <add> } <add> trySetStompHeaderForSubscriptionId(); <ide> } <ide> <ide> /** <del> * Create {@link StompHeaderAccessor} for a new {@link Message}. <add> * Create an instance for the given STOMP command. <ide> */ <ide> public static StompHeaderAccessor create(StompCommand command) { <del> return new StompHeaderAccessor(command, null); <add> return factory.create(command); <ide> } <ide> <ide> /** <del> * Create {@link StompHeaderAccessor} from parsed STOP frame content. <add> * Create an instance for the given STOMP command and headers. <ide> */ <ide> public static StompHeaderAccessor create(StompCommand command, Map<String, List<String>> headers) { <del> return new StompHeaderAccessor(command, headers); <add> return factory.create(command, headers); <ide> } <ide> <ide> /** <del> * Create {@link StompHeaderAccessor} from the headers of an existing {@link Message}. <add> * Create headers for a heartbeat. While a STOMP heartbeat frame does not <add> * have headers, a session id is needed for processing purposes at a minimum. <ide> */ <del> public static StompHeaderAccessor wrap(Message<?> message) { <del> return new StompHeaderAccessor(message); <add> public static StompHeaderAccessor createForHeartbeat() { <add> return factory.createForHeartbeat(); <ide> } <ide> <del> <ide> /** <del> * Return STOMP headers including original, wrapped STOMP headers (if any) plus <del> * additional header updates made through accessor methods. <add> * Create an instance from the payload and headers of the given Message. <ide> */ <del> @Override <del> public Map<String, List<String>> toNativeHeaderMap() { <del> <del> Map<String, List<String>> result = super.toNativeHeaderMap(); <del> <del> String destination = super.getDestination(); <del> if (destination != null) { <del> result.put(STOMP_DESTINATION_HEADER, Arrays.asList(destination)); <del> } <del> <del> MimeType contentType = super.getContentType(); <del> if (contentType != null) { <del> result.put(STOMP_CONTENT_TYPE_HEADER, Arrays.asList(contentType.toString())); <del> } <add> public static StompHeaderAccessor wrap(Message<?> message) { <add> return factory.wrap(message); <add> } <ide> <del> if (getCommand() != null && getCommand().requiresSubscriptionId()) { <del> String subscriptionId = getSubscriptionId(); <del> if (subscriptionId != null) { <del> String name = StompCommand.MESSAGE.equals(getCommand()) ? STOMP_SUBSCRIPTION_HEADER : STOMP_ID_HEADER; <del> result.put(name, Arrays.asList(subscriptionId)); <del> } <del> else { <del> logger.warn(getCommand() + " frame does not have a subscription identifier" + this.toString()); <del> } <del> } <ide> <del> if (StompCommand.MESSAGE.equals(getCommand()) && ((getMessageId() == null))) { <del> String messageId = getSessionId() + "-" + messageIdCounter.getAndIncrement(); <del> result.put(STOMP_MESSAGE_ID_HEADER, Arrays.asList(messageId)); <del> } <del> <del> return result; <add> @Override <add> protected MessageHeaderAccessor createAccessor(Message<?> message) { <add> return factory.wrap(message); <ide> } <ide> <del> public Map<String, List<String>> toStompHeaderMap() { <del> if (StompCommand.CONNECT.equals(getCommand())) { <del> StompPasscode credentials = (StompPasscode) getHeader(CREDENTIALS_HEADER); <del> if (credentials != null) { <del> Map<String, List<String>> headers = toNativeHeaderMap(); <del> headers.put(STOMP_PASSCODE_HEADER, Arrays.asList(credentials.passcode)); <del> return headers; <del> } <del> } <del> return toNativeHeaderMap(); <add> Map<String, List<String>> getNativeHeaders() { <add> @SuppressWarnings("unchecked") <add> Map<String, List<String>> map = (Map<String, List<String>>) getHeader(NATIVE_HEADERS); <add> return (map != null ? map : Collections.<String, List<String>>emptyMap()); <ide> } <ide> <ide> public StompCommand updateStompCommandAsClientMessage() { <ide> <del> Assert.state(SimpMessageType.MESSAGE.equals(getMessageType()), <del> "Unexpected message type " + getMessage()); <add> Assert.state(SimpMessageType.MESSAGE.equals(getMessageType()), "Unexpected message type " + getMessage()); <ide> <ide> if (getCommand() == null) { <ide> setHeader(COMMAND_HEADER, StompCommand.SEND); <ide> else if (!getCommand().equals(StompCommand.SEND)) { <ide> <ide> public void updateStompCommandAsServerMessage() { <ide> <del> Assert.state(SimpMessageType.MESSAGE.equals(getMessageType()), <del> "Unexpected message type " + getMessage()); <add> Assert.state(SimpMessageType.MESSAGE.equals(getMessageType()), "Unexpected message type " + getMessage()); <ide> <del> if ((getCommand() == null) || getCommand().equals(StompCommand.SEND)) { <add> StompCommand command = getCommand(); <add> if ((command == null) || StompCommand.SEND.equals(command)) { <ide> setHeader(COMMAND_HEADER, StompCommand.MESSAGE); <ide> } <del> else if (!getCommand().equals(StompCommand.MESSAGE)) { <del> throw new IllegalStateException("Unexpected STOMP command " + getCommand()); <add> else if (!StompCommand.MESSAGE.equals(command)) { <add> throw new IllegalStateException("Unexpected STOMP command " + command); <add> } <add> <add> trySetStompHeaderForSubscriptionId(); <add> <add> if (getMessageId() == null) { <add> String messageId = getSessionId() + "-" + messageIdCounter.getAndIncrement(); <add> setNativeHeader(STOMP_MESSAGE_ID_HEADER, messageId); <ide> } <ide> } <ide> <add> /** <add> * @return the STOMP command, or {@code null} if not yet set. <add> */ <ide> public StompCommand getCommand() { <ide> return (StompCommand) getHeader(COMMAND_HEADER); <ide> } <ide> <add> /** <add> * A static alternative for access to the STOMP command. <add> */ <add> public static StompCommand getCommand(Map<String, Object> headers) { <add> return (StompCommand) headers.get(COMMAND_HEADER); <add> } <add> <ide> public Set<String> getAcceptVersion() { <ide> String rawValue = getFirstNativeHeader(STOMP_ACCEPT_VERSION_HEADER); <ide> return (rawValue != null) ? StringUtils.commaDelimitedListToSet(rawValue) : Collections.<String>emptySet(); <ide> } <ide> <add> public boolean isHeartbeat() { <add> return (SimpMessageType.HEARTBEAT == getMessageType()); <add> } <add> <ide> public void setAcceptVersion(String acceptVersion) { <ide> setNativeHeader(STOMP_ACCEPT_VERSION_HEADER, acceptVersion); <ide> } <ide> public void setContentType(MimeType contentType) { <ide> setNativeHeader(STOMP_CONTENT_TYPE_HEADER, contentType.toString()); <ide> } <ide> <add> @Override <add> public void setSubscriptionId(String subscriptionId) { <add> super.setSubscriptionId(subscriptionId); <add> trySetStompHeaderForSubscriptionId(); <add> } <add> <add> private void trySetStompHeaderForSubscriptionId() { <add> String subscriptionId = getSubscriptionId(); <add> if (subscriptionId != null) { <add> if (getCommand() != null && StompCommand.MESSAGE.equals(getCommand())) { <add> setNativeHeader(STOMP_SUBSCRIPTION_HEADER, subscriptionId); <add> } <add> else { <add> SimpMessageType messageType = getMessageType(); <add> if (SimpMessageType.SUBSCRIBE.equals(messageType) || SimpMessageType.UNSUBSCRIBE.equals(messageType)) { <add> setNativeHeader(STOMP_ID_HEADER, subscriptionId); <add> } <add> } <add> } <add> } <add> <ide> public Integer getContentLength() { <del> String contentLength = getFirstNativeHeader(STOMP_CONTENT_LENGTH_HEADER); <del> return StringUtils.hasText(contentLength) ? new Integer(contentLength) : null; <add> if (containsNativeHeader(STOMP_CONTENT_LENGTH_HEADER)) { <add> return Integer.valueOf(getFirstNativeHeader(STOMP_CONTENT_LENGTH_HEADER)); <add> } <add> return null; <add> } <add> <add> public static Integer getContentLength(Map<String, List<String>> nativeHeaders) { <add> if (nativeHeaders.containsKey(STOMP_CONTENT_LENGTH_HEADER)) { <add> List<String> values = nativeHeaders.get(STOMP_CONTENT_LENGTH_HEADER); <add> String value = (values != null ? values.get(0) : null); <add> return Integer.valueOf(value); <add> } <add> return null; <ide> } <ide> <ide> public void setContentLength(int contentLength) { <ide> setNativeHeader(STOMP_CONTENT_LENGTH_HEADER, String.valueOf(contentLength)); <ide> } <ide> <ide> public void setHeartbeat(long cx, long cy) { <del> setNativeHeader(STOMP_HEARTBEAT_HEADER, StringUtils.arrayToCommaDelimitedString(new Object[] {cx, cy})); <add> setNativeHeader(STOMP_HEARTBEAT_HEADER, StringUtils.arrayToCommaDelimitedString(new Object[]{cx, cy})); <ide> } <ide> <ide> public void setAck(String ack) { <ide> public String getLogin() { <ide> <ide> public void setPasscode(String passcode) { <ide> setNativeHeader(STOMP_PASSCODE_HEADER, passcode); <add> protectPasscode(); <ide> } <ide> <add> private void protectPasscode() { <add> String value = getFirstNativeHeader(STOMP_PASSCODE_HEADER); <add> if (value != null && !"PROTECTED".equals(value)) { <add> setHeader(CREDENTIALS_HEADER, new StompPasscode(value)); <add> setNativeHeader(STOMP_PASSCODE_HEADER, "PROTECTED"); <add> } <add> } <add> <add> /** <add> * @return the passcode header value or {@code null}. <add> */ <ide> public String getPasscode() { <del> return getFirstNativeHeader(STOMP_PASSCODE_HEADER); <add> StompPasscode credentials = (StompPasscode) getHeader(CREDENTIALS_HEADER); <add> return (credentials != null ? credentials.passcode : null); <add> } <add> <add> /** <add> * A static alternative for access to the passcode header. <add> */ <add> public static String getPasscode(Map<String, Object> headers) { <add> StompPasscode credentials = (StompPasscode) headers.get(CREDENTIALS_HEADER); <add> return (credentials != null ? credentials.passcode : null); <ide> } <ide> <ide> public void setReceiptId(String receiptId) { <ide><path>spring-messaging/src/main/java/org/springframework/messaging/simp/stomp/StompHeaderAccessorFactory.java <add>/* <add> * Copyright 2002-2014 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add> <add>package org.springframework.messaging.simp.stomp; <add> <add> <add>import org.springframework.messaging.Message; <add> <add>import java.util.List; <add>import java.util.Map; <add> <add>/** <add> * A factory for creating pre-configured instances of type <add> * {@link org.springframework.messaging.simp.stomp.StompHeaderAccessor}. <add> * <add> * @author Rossen Stoyanchev <add> * @since 4.1 <add> */ <add>public interface StompHeaderAccessorFactory { <add> <add> /** <add> * Create an instance for the given STOMP command. <add> */ <add> StompHeaderAccessor create(StompCommand command); <add> <add> /** <add> * Create an instance for the given STOMP command and headers. <add> */ <add> StompHeaderAccessor create(StompCommand command, Map<String, List<String>> headers); <add> <add> /** <add> * Create headers for a heartbeat. While a STOMP heartbeat frame does not <add> * have headers, a session id is needed for processing purposes at a minimum. <add> */ <add> StompHeaderAccessor createForHeartbeat(); <add> <add> /** <add> * Create an instance from the payload and headers of the given Message. <add> */ <add> StompHeaderAccessor wrap(Message<?> message); <add> <add>} <ide><path>spring-messaging/src/main/java/org/springframework/messaging/support/AbstractMessageChannel.java <ide> public final boolean send(Message<?> message, long timeout) { <ide> Assert.notNull(message, "Message must not be null"); <ide> <ide> if (logger.isTraceEnabled()) { <del> logger.trace("[" + this.beanName + "] sending message id=" + message.getHeaders().getId()); <add> logger.trace("[" + this.beanName + "] sending message=" + message); <ide> } <ide> <ide> message = this.interceptorChain.preSend(message, this); <ide><path>spring-messaging/src/main/java/org/springframework/messaging/support/ChannelInterceptorChain.java <ide> public List<ChannelInterceptor> getInterceptors() { <ide> <ide> <ide> public Message<?> preSend(Message<?> message, MessageChannel channel) { <del> UUID originalId = message.getHeaders().getId(); <add> Message<?> originalMessage = message; <ide> for (ChannelInterceptor interceptor : this.interceptors) { <ide> message = interceptor.preSend(message, channel); <ide> if (message == null) { <ide> public Message<?> preSend(Message<?> message, MessageChannel channel) { <ide> } <ide> } <ide> if (logger.isDebugEnabled()) { <del> if (!message.getHeaders().getId().equals(originalId)) { <del> logger.debug("preSend returned modified message, new message id=" + message.getHeaders().getId()); <add> if (message != originalMessage) { <add> logger.debug("preSend returned modified message, new message=" + message); <ide> } <ide> } <ide> return message; <ide> } <ide> <ide> public void postSend(Message<?> message, MessageChannel channel, boolean sent) { <ide> if (logger.isTraceEnabled()) { <del> logger.trace("postSend (sent=" + sent + ") message id " + message.getHeaders().getId()); <add> logger.trace("postSend (sent=" + sent + ")"); <ide> } <ide> for (ChannelInterceptor interceptor : this.interceptors) { <ide> interceptor.postSend(message, channel, sent); <ide><path>spring-messaging/src/main/java/org/springframework/messaging/support/ErrorMessage.java <ide> /* <del> * Copyright 2002-2013 the original author or authors. <add> * Copyright 2002-2014 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> <ide> package org.springframework.messaging.support; <ide> <add>import org.springframework.messaging.MessageHeaders; <add> <ide> import java.util.Map; <ide> <ide> /** <ide> public ErrorMessage(Throwable payload) { <ide> <ide> /** <ide> * Create a new message with the given payload and headers. <add> * The content of the given header map is copied. <ide> * <ide> * @param payload the message payload, never {@code null} <del> * @param headers message headers <add> * @param headers message headers to use for initialization <ide> */ <ide> public ErrorMessage(Throwable payload, Map<String, Object> headers) { <ide> super(payload, headers); <ide> } <ide> <add> /** <add> * A constructor with the {@link MessageHeaders} instance to use. <add> * <add> * <p><strong>Note:</strong> the given {@code MessageHeaders} instance is used <add> * directly in the new message, i.e. it is not copied. <add> * <add> * @param payload the message payload, never {@code null} <add> * @param headers message headers <add> */ <add> public ErrorMessage(Throwable payload, MessageHeaders headers) { <add> super(payload, headers); <add> } <add> <ide> } <ide><path>spring-messaging/src/main/java/org/springframework/messaging/support/GenericMessage.java <ide> * @param payload the message payload, never {@code null} <ide> */ <ide> public GenericMessage(T payload) { <del> this(payload, null); <add> this(payload, new MessageHeaders(null)); <ide> } <ide> <ide> /** <ide> * Create a new message with the given payload and headers. <add> * The content of the given header map is copied. <ide> * <ide> * @param payload the message payload, never {@code null} <del> * @param headers message headers <add> * @param headers message headers to use for initialization <ide> */ <ide> public GenericMessage(T payload, Map<String, Object> headers) { <add> this(payload, new MessageHeaders(headers)); <add> } <add> <add> /** <add> * A constructor with the {@link MessageHeaders} instance to use. <add> * <add> * <p><strong>Note:</strong> the given {@code MessageHeaders} instance is used <add> * directly in the new message, i.e. it is not copied. <add> * <add> * @param payload the message payload, never {@code null} <add> * @param headers message headers <add> */ <add> public GenericMessage(T payload, MessageHeaders headers) { <add> Assert.notNull(headers, "'headers' must not be null"); <ide> Assert.notNull(payload, "payload must not be null"); <del> this.headers = new MessageHeaders(headers); <add> this.headers = headers; <ide> this.payload = payload; <ide> } <ide> <ide> public boolean equals(Object obj) { <ide> } <ide> if (obj != null && obj instanceof GenericMessage<?>) { <ide> GenericMessage<?> other = (GenericMessage<?>) obj; <del> return (this.headers.getId().equals(other.headers.getId()) && <add> return (ObjectUtils.nullSafeEquals(this.headers.getId(), other.headers.getId()) && <ide> this.headers.equals(other.headers) && this.payload.equals(other.payload)); <ide> } <ide> return false; <ide><path>spring-messaging/src/main/java/org/springframework/messaging/support/MessageBuilder.java <ide> <ide> import org.springframework.messaging.Message; <ide> import org.springframework.messaging.MessageChannel; <add>import org.springframework.messaging.MessageHeaders; <ide> import org.springframework.util.Assert; <ide> <ide> /** <ide> */ <ide> public final class MessageBuilder<T> { <ide> <add> private final Message<T> originalMessage; <add> <ide> private final T payload; <ide> <ide> private MessageHeaderAccessor headerAccessor; <ide> <del> private final Message<T> originalMessage; <del> <ide> <del> /** <del> * Private constructor to be invoked from the static factory methods only. <del> */ <del> private MessageBuilder(T payload, Message<T> originalMessage) { <del> Assert.notNull(payload, "payload must not be null"); <del> this.payload = payload; <del> this.originalMessage = originalMessage; <add> private MessageBuilder(Message<T> originalMessage) { <add> Assert.notNull(originalMessage, "'originalMessage' must not be null"); <add> this.payload = originalMessage.getPayload(); <ide> this.headerAccessor = new MessageHeaderAccessor(originalMessage); <add> this.originalMessage = originalMessage; <ide> } <ide> <add> private MessageBuilder(T payload, MessageHeaderAccessor accessor) { <add> Assert.notNull(payload, "'payload' must not be null"); <add> Assert.notNull(accessor, "'messageHeaderAccessor' must not be null"); <add> this.payload = payload; <add> this.headerAccessor = accessor; <add> this.originalMessage = null; <add> } <ide> <ide> /** <ide> * Create a builder for a new {@link Message} instance pre-populated with all of the <ide> private MessageBuilder(T payload, Message<T> originalMessage) { <ide> * @param message the Message from which the payload and all headers will be copied <ide> */ <ide> public static <T> MessageBuilder<T> fromMessage(Message<T> message) { <del> Assert.notNull(message, "message must not be null"); <del> return new MessageBuilder<T>(message.getPayload(), message); <add> return new MessageBuilder<T>(message); <ide> } <ide> <ide> /** <del> * Create a builder for a new {@link Message} instance with the provided payload. <del> * @param payload the payload for the new message <add> * Create a new builder for a message with the given payload. <add> * @param payload the payload <ide> */ <ide> public static <T> MessageBuilder<T> withPayload(T payload) { <del> return new MessageBuilder<T>(payload, null); <add> return new MessageBuilder<T>(payload, new MessageHeaderAccessor()); <ide> } <ide> <add> /** <add> * A shortcut factory method for creating a message with the given payload <add> * and {@code MessageHeaders}. <add> * <add> * <p><strong>Note:</strong> the given {@code MessageHeaders} instance is used <add> * directly in the new message, i.e. it is not copied. <add> * <add> * @param payload the payload to use, never {@code null} <add> * @param messageHeaders the headers to use, never {@code null} <add> * @return the created message <add> * @since 4.1 <add> */ <add> @SuppressWarnings("unchecked") <add> public static <T> Message<T> createMessage(T payload, MessageHeaders messageHeaders) { <add> Assert.notNull(payload, "'payload' must not be null"); <add> Assert.notNull(messageHeaders, "'messageHeaders' must not be null"); <add> if (payload instanceof Throwable) { <add> return (Message<T>) new ErrorMessage((Throwable) payload, messageHeaders); <add> } <add> else { <add> return new GenericMessage<T>(payload, messageHeaders); <add> } <add> } <ide> <ide> /** <del> * Set the message headers. <del> * @param headerAccessor the headers for the message <add> * Set the message headers to use by providing a {@code MessageHeaderAccessor}. <add> * <add> * @param accessor the headers to use <ide> */ <del> public MessageBuilder<T> setHeaders(MessageHeaderAccessor headerAccessor) { <del> Assert.notNull(headerAccessor, "HeaderAccessor must not be null"); <del> this.headerAccessor = headerAccessor; <add> public MessageBuilder<T> setHeaders(MessageHeaderAccessor accessor) { <add> Assert.notNull(accessor, "HeaderAccessor must not be null"); <add> this.headerAccessor = accessor; <ide> return this; <ide> } <ide> <ide> public MessageBuilder<T> setErrorChannelName(String errorChannelName) { <ide> <ide> @SuppressWarnings("unchecked") <ide> public Message<T> build() { <del> if ((this.originalMessage != null) && !this.headerAccessor.isModified()) { <add> <add> if (this.originalMessage != null && !this.headerAccessor.isModified()) { <ide> return this.originalMessage; <ide> } <add> <ide> if (this.payload instanceof Throwable) { <ide> return (Message<T>) new ErrorMessage((Throwable) this.payload, this.headerAccessor.toMap()); <ide> } <del> return new GenericMessage<T>(this.payload, this.headerAccessor.toMap()); <add> else { <add> return new GenericMessage<T>(this.payload, this.headerAccessor.toMap()); <add> } <ide> } <ide> <ide> } <ide><path>spring-messaging/src/main/java/org/springframework/messaging/support/MessageHeaderAccessor.java <ide> /* <del> * Copyright 2002-2013 the original author or authors. <add> * Copyright 2002-2014 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> import org.springframework.messaging.MessageChannel; <ide> import org.springframework.messaging.MessageHeaders; <ide> import org.springframework.util.Assert; <add>import org.springframework.util.IdGenerator; <ide> import org.springframework.util.MimeType; <ide> import org.springframework.util.ObjectUtils; <ide> import org.springframework.util.PatternMatchUtils; <ide> import org.springframework.util.StringUtils; <ide> <ide> /** <del> * A base class for read/write access to {@link MessageHeaders}. Supports creation of new <del> * headers or modification of existing message headers. <add> * A base for classes providing strongly typed getters and setters as well as <add> * behavior around specific categories of headers (e.g. STOMP headers). <add> * Supports creating new headers (default constructor), modifying existing headers <add> * (when still mutable), or copying and modifying existing headers. <ide> * <del> * <p>Sub-classes can provide additional typed getters and setters for convenient access <del> * to specific headers. Getters and setters should delegate to {@link #getHeader(String)} <del> * or {@link #setHeader(String, Object)} respectively. At the end {@link #toMap()} can be <del> * used to obtain the resulting headers. <add> * <p>The {@link #getMessageHeaders()} method provides access to the underlying, <add> * fully-prepared {@code MessageHeaders} instance that can then be used as-is <add> * to create a single message as follows: <add> * <add> * <pre class="code"> <add> * MessageHeaderAccessor headerAccessor = new MessageHeaderAccessor(); <add> * headerAccessor.set("foo", "bar"); <add> * Message message = MessageBuilder.createMessage("payload", headerAccessor.getMessageHeaders()); <add> * </pre> <add> * <add> * <p>After the above is executed, by default the {@code MessageHeaderAccessor} <add> * is immutable. It is also possible to leave it mutable, for example for further <add> * initialization of the message in the same thread: <add> * <add> * <pre class="code"> <add> * MessageHeaderAccessor headerAccessor = new MessageHeaderAccessor(); <add> * headerAccessor.set("foo", "bar"); <add> * headerAccessor.setLeaveMutable(true); <add> * Message message = MessageBuilder.createMessage("payload", headerAccessor.getMessageHeaders()); <add> * <add> * // later on in the same thread... <add> * <add> * MessageHeaderAccessor headerAccessor = MessageHeaderAccessor.getAccessor(message); <add> * headerAccessor.set("bar", "baz"); <add> * headerAccessor.setImmutable(); <add> * </pre> <add> * <add> * <p>To re-obtain the {@code MessageHeaderAccessor} for a {@code MessageHeaders} <add> * instance, use the following: <add> * <add> * <pre class="code"> <add> * MessageHeaderAccessor headerAccessor = new MessageHeaderAccessor(); <add> * headerAccessor.set("foo", "bar"); <add> * Message message = MessageBuilder.createMessage("payload", headerAccessor.getMessageHeaders()); <add> * <add> * // later on (any thread)... <add> * MessageHeaderAccessor headerAccessor = MessageHeaderAccessor.getAccessor(message); <add> * headerAccessor.get("foo"); <add> * </pre> <add> * <add> * <p>To prepare multiple messages with the same {@code MessageHeaderAccessor} <add> * instance, use the code below. However note that this usage style does not allow <add> * re-obtaining a header accessor later on: <add> * <pre class="code"> <add> * MessageHeaderAccessor headerAccessor = new MessageHeaderAccessor(); <add> * MessageBuilder builder = MessageBuilder.withPayload("payload").setHeaders(headerAccessor); <add> * <add> * headerAccessor.setHeader("foo", "bar1"); <add> * Message message1 = builder.build(); <add> * <add> * headerAccessor.setHeader("foo", "bar2"); <add> * Message message2 = builder.build(); <add> * <add> * headerAccessor.setHeader("foo", "bar3"); <add> * Message message3 = builder.build(); <add> * </pre> <ide> * <ide> * @author Rossen Stoyanchev <ide> * @since 4.0 <ide> public class MessageHeaderAccessor { <ide> <ide> protected Log logger = LogFactory.getLog(getClass()); <ide> <add> private final MutableMessageHeaders headers; <add> <add> private boolean modified; <ide> <del> // wrapped read-only message headers <del> private final MessageHeaders originalHeaders; <add> private boolean leaveMutable; <ide> <del> // header updates <del> private final Map<String, Object> headers = new HashMap<String, Object>(4); <add> private IdGenerator idGenerator; <add> <add> private boolean enableTimestamp = false; <ide> <ide> <ide> /** <del> * A constructor for creating new message headers. <add> * A constructor to create new headers. <ide> */ <ide> public MessageHeaderAccessor() { <del> this.originalHeaders = null; <add> this.headers = new MutableMessageHeaders(); <ide> } <ide> <ide> /** <del> * A constructor for accessing and modifying existing message headers. <add> * A constructor accepting the headers of an existing message to copy. <ide> */ <ide> public MessageHeaderAccessor(Message<?> message) { <del> this.originalHeaders = (message != null) ? message.getHeaders() : null; <add> if (message != null) { <add> this.headers = new MutableMessageHeaders(message.getHeaders()); <add> MessageHeaderAccessor accessor = getAccessor(message, MessageHeaderAccessor.class); <add> if (accessor != null) { <add> this.idGenerator = accessor.idGenerator; <add> this.enableTimestamp = accessor.enableTimestamp; <add> } <add> } <add> else { <add> this.headers = new MutableMessageHeaders(); <add> } <ide> } <ide> <add> /** <add> * Return the original {@code MessageHeaderAccessor} used to create the headers <add> * of the given {@code Message}, or {@code null} if that's not available or if <add> * its type does not match the required type. <add> * <add> * <p>This is for cases where the existence of an accessor is strongly expected <add> * (to be followed up with an assertion) or will created if not provided. <add> * <add> * @return an accessor instance of the specified type or {@code null}. <add> * @since 4.1 <add> */ <add> @SuppressWarnings("unchecked") <add> public static <T extends MessageHeaderAccessor> T getAccessor(Message<?> message, Class<T> requiredType) { <add> return getAccessor(message.getHeaders(), requiredType); <add> } <ide> <ide> /** <del> * Return a header map including original, wrapped headers (if any) plus additional <del> * header updates made through accessor methods. <add> * A variation of {@link #getAccessor(org.springframework.messaging.Message, Class)} <add> * with a {@code MessageHeaders} instance instead of a {@code Message}. <add> * <add> * <p>This is for cases when a full message may not have been created yet. <add> * <add> * @return an accessor instance of the specified type or {@code null}. <add> * @since 4.1 <ide> */ <del> public Map<String, Object> toMap() { <del> Map<String, Object> result = new HashMap<String, Object>(); <del> if (this.originalHeaders != null) { <del> result.putAll(this.originalHeaders); <del> } <del> for (String key : this.headers.keySet()) { <del> Object value = this.headers.get(key); <del> if (value == null) { <del> result.remove(key); <add> @SuppressWarnings("unchecked") <add> public static <T extends MessageHeaderAccessor> T getAccessor(MessageHeaders messageHeaders, Class<T> requiredType) { <add> if (messageHeaders instanceof MutableMessageHeaders) { <add> MutableMessageHeaders mutableHeaders = (MutableMessageHeaders) messageHeaders; <add> MessageHeaderAccessor headerAccessor = mutableHeaders.getMessageHeaderAccessor(); <add> if (requiredType.isAssignableFrom(headerAccessor.getClass())) { <add> return (T) headerAccessor; <ide> } <del> else { <del> result.put(key, value); <add> } <add> return null; <add> } <add> <add> /** <add> * Return a mutable {@code MessageHeaderAccessor} for the given message attempting <add> * to match the type of accessor used to create the message headers, or otherwise <add> * wrapping the message with a {@code MessageHeaderAccessor} instance. <add> * <add> * <p>This is for cases where a header needs to be updated in generic code <add> * while preserving the accessor type for downstream processing. <add> * <add> * @return an accessor of the required type, never {@code null}. <add> * @since 4.1 <add> */ <add> public static MessageHeaderAccessor getMutableAccessor(Message<?> message) { <add> if (message.getHeaders() instanceof MutableMessageHeaders) { <add> MutableMessageHeaders mutableHeaders = (MutableMessageHeaders) message.getHeaders(); <add> MessageHeaderAccessor accessor = mutableHeaders.getMessageHeaderAccessor(); <add> if (accessor != null) { <add> return (accessor.isMutable() ? accessor : accessor.createAccessor(message)); <ide> } <ide> } <del> return result; <add> return new MessageHeaderAccessor(message); <add> } <add> <add> protected MessageHeaderAccessor createAccessor(Message<?> message) { <add> return new MessageHeaderAccessor(message); <add> } <add> <add> /** <add> * Return the underlying {@code MessageHeaders} instance. <add> * <add> * <p>Unless {@link #setLeaveMutable(boolean)} was set to {@code true}, after <add> * this call, the headers are immutable and this accessor can no longer <add> * modify them. <add> * <add> * <p>This method always returns the same {@code MessageHeaders} instance if <add> * invoked multiples times. To obtain a copy of the underlying headers instead <add> * use {@link #toMap()}. <add> */ <add> public MessageHeaders getMessageHeaders() { <add> this.headers.setIdAndTimestamp(); <add> if (!this.leaveMutable) { <add> setImmutable(); <add> } <add> return this.headers; <add> } <add> <add> /** <add> * Return a copy of the underlying header values. <add> * <add> * <p>This method can be invoked many times, with modifications in between <add> * where each new call returns a fresh copy of the current header values. <add> */ <add> public Map<String, Object> toMap() { <add> return new HashMap<String, Object>(this.headers); <add> } <add> <add> /** <add> * By default when {@link #getMessageHeaders()} is called, {@code "this"} <add> * {@code MessageHeaderAccessor} instance can no longer be used to modify the <add> * underlying message headers and the returned {@code MessageHeaders} is immutable. <add> * <add> * <p>However when this is set to {@code true}, the returned (underlying) <add> * {@code MessageHeaders} instance remains mutable. To make further modifications <add> * continue to use the same accessor instance or re-obtain it via:<br> <add> * {@link org.springframework.messaging.support.MessageHeaderAccessor#getAccessor(org.springframework.messaging.Message, Class) <add> * MessageHeaderAccessor.getAccessor(Message, Class)} <add> * <add> * <p>When modifications are complete use {@link #setImmutable()} to prevent <add> * further changes. The intended use case for this mechanism is initialization <add> * of a Message within a single thread. <add> * <add> * <p>By default this is set to {@code false}. <add> * @since 4.1 <add> */ <add> public void setLeaveMutable(boolean leaveMutable) { <add> Assert.state(this.headers.isMutable(), "Already immutable"); <add> this.leaveMutable = leaveMutable; <add> } <add> <add> /** <add> * By default when {@link #getMessageHeaders()} is called, {@code "this"} <add> * {@code MessageHeaderAccessor} instance can no longer be used to modify the <add> * underlying message headers. However if {@link #setLeaveMutable(boolean)} <add> * is used, this method is necessary to indicate explicitly when the <add> * {@code MessageHeaders} instance should no longer be modified. <add> * @since 4.1 <add> */ <add> public void setImmutable() { <add> this.headers.setImmutable(); <add> } <add> <add> /** <add> * Whether the underlying headers can still be modified. <add> * @since 4.1 <add> */ <add> public boolean isMutable() { <add> return this.headers.isMutable(); <add> } <add> <add> /** <add> * A private mechanism for providing an alternate IdGenerator strategy. <add> * <add> * <p>By default this property is not set in which case the default IdGenerator <add> * of {@link org.springframework.messaging.MessageHeaders} is used. <add> * <add> * @see org.springframework.messaging.support.MessageHeaderAccessorFactorySupport <add> */ <add> void setIdGenerator(IdGenerator idGenerator) { <add> this.idGenerator = idGenerator; <add> } <add> <add> /** <add> * A private mechanism to enable having a timestamp added to every message. <add> * <add> * <p>By default this property is set to false. <add> * <add> * @see org.springframework.messaging.support.MessageHeaderAccessorFactorySupport <add> */ <add> void setEnableTimestamp(boolean enableTimestamp) { <add> this.enableTimestamp = enableTimestamp; <ide> } <ide> <ide> public boolean isModified() { <del> return (!this.headers.isEmpty()); <add> return this.modified; <add> } <add> <add> protected void setModified(boolean modified) { <add> this.modified = modified; <ide> } <ide> <ide> public Object getHeader(String headerName) { <del> if (this.headers.containsKey(headerName)) { <del> return this.headers.get(headerName); <del> } <del> else if (this.originalHeaders != null) { <del> return this.originalHeaders.get(headerName); <del> } <del> return null; <add> return this.headers.get(headerName); <ide> } <ide> <ide> /** <ide> public void setHeader(String name, Object value) { <ide> Assert.isTrue(!isReadOnly(name), "The '" + name + "' header is read-only."); <ide> verifyType(name, value); <ide> if (!ObjectUtils.nullSafeEquals(value, getHeader(name))) { <del> this.headers.put(name, value); <add> this.modified = true; <add> if (value != null) { <add> this.headers.getRawHeaders().put(name, value); <add> } <add> else { <add> this.headers.getRawHeaders().remove(name); <add> } <add> } <add> } <add> <add> protected void verifyType(String headerName, Object headerValue) { <add> if (headerName != null && headerValue != null) { <add> if (MessageHeaders.ERROR_CHANNEL.equals(headerName) || MessageHeaders.REPLY_CHANNEL.endsWith(headerName)) { <add> Assert.isTrue(headerValue instanceof MessageChannel || headerValue instanceof String, "The '" <add> + headerName + "' header value must be a MessageChannel or String."); <add> } <ide> } <ide> } <ide> <ide> public void removeHeaders(String... headerPatterns) { <ide> if (StringUtils.hasLength(pattern)){ <ide> if (pattern.contains("*")){ <ide> headersToRemove.addAll(getMatchingHeaderNames(pattern, this.headers)); <del> headersToRemove.addAll(getMatchingHeaderNames(pattern, this.originalHeaders)); <ide> } <ide> else { <ide> headersToRemove.add(pattern); <ide> public void setContentType(MimeType contentType) { <ide> <ide> @Override <ide> public String toString() { <del> return getClass().getSimpleName() + " [originalHeaders=" + this.originalHeaders <del> + ", updated headers=" + this.headers + "]"; <add> return getClass().getSimpleName() + " [headers=" + this.headers + "]"; <add> } <add> <add> <add> @SuppressWarnings("serial") <add> private class MutableMessageHeaders extends MessageHeaders { <add> <add> private boolean immutable; <add> <add> <add> public MutableMessageHeaders() { <add> this(null); <add> } <add> <add> public MutableMessageHeaders(Map<String, Object> headers) { <add> super(headers, MessageHeaders.ID_VALUE_NONE, -1L); <add> } <add> <add> public MessageHeaderAccessor getMessageHeaderAccessor() { <add> return MessageHeaderAccessor.this; <add> } <add> <add> @Override <add> public Map<String, Object> getRawHeaders() { <add> Assert.state(!this.immutable, "Already immutable"); <add> return super.getRawHeaders(); <add> } <add> <add> public void setImmutable() { <add> this.immutable = true; <add> } <add> <add> public boolean isMutable() { <add> return !this.immutable; <add> } <add> <add> public void setIdAndTimestamp() { <add> if (getId() == null) { <add> IdGenerator idGenerator = (MessageHeaderAccessor.this.idGenerator != null) ? <add> MessageHeaderAccessor.this.idGenerator : <add> MessageHeaders.getIdGenerator(); <add> <add> UUID id = idGenerator.generateId(); <add> if (id != null && id != MessageHeaders.ID_VALUE_NONE) { <add> getRawHeaders().put(ID, id); <add> } <add> } <add> if (getTimestamp() == null) { <add> if (MessageHeaderAccessor.this.enableTimestamp) { <add> getRawHeaders().put(TIMESTAMP, System.currentTimeMillis()); <add> } <add> } <add> } <ide> } <ide> <del> protected void verifyType(String headerName, Object headerValue) { <del> if (headerName != null && headerValue != null) { <del> if (MessageHeaders.ERROR_CHANNEL.equals(headerName) <del> || MessageHeaders.REPLY_CHANNEL.endsWith(headerName)) { <del> Assert.isTrue(headerValue instanceof MessageChannel || headerValue instanceof String, "The '" <del> + headerName + "' header value must be a MessageChannel or String."); <del> } <del> } <del> } <ide> } <ide><path>spring-messaging/src/main/java/org/springframework/messaging/support/MessageHeaderAccessorFactorySupport.java <add>/* <add> * Copyright 2002-2014 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add> <add>package org.springframework.messaging.support; <add> <add>import org.springframework.util.IdGenerator; <add> <add>/** <add> * A support class for factories creating pre-configured instances of type <add> * {@link org.springframework.messaging.support.MessageHeaderAccessor}. <add> * <add> * @author Rossen Stoyanchev <add> * @since 4.1 <add> */ <add>public class MessageHeaderAccessorFactorySupport { <add> <add> private IdGenerator idGenerator; <add> <add> private Boolean enableTimestamp; <add> <add> <add> protected MessageHeaderAccessorFactorySupport() { <add> } <add> <add> /** <add> * <add> * @param idGenerator <add> */ <add> public void setIdGenerator(IdGenerator idGenerator) { <add> this.idGenerator = idGenerator; <add> } <add> <add> public IdGenerator getIdGenerator() { <add> return this.idGenerator; <add> } <add> <add> public void setEnableTimestamp(boolean enableTimestamp) { <add> this.enableTimestamp = enableTimestamp; <add> } <add> <add> public boolean isEnableTimestamp() { <add> return this.enableTimestamp; <add> } <add> <add> protected void updateMessageHeaderAccessor(MessageHeaderAccessor headerAccessor) { <add> if (this.idGenerator != null) { <add> headerAccessor.setIdGenerator(this.idGenerator); <add> } <add> if (this.enableTimestamp != null) { <add> headerAccessor.setEnableTimestamp(this.enableTimestamp); <add> } <add> } <add> <add>} <ide><path>spring-messaging/src/main/java/org/springframework/messaging/support/NativeMessageHeaderAccessor.java <ide> /* <del> * Copyright 2002-2013 the original author or authors. <add> * Copyright 2002-2014 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> <ide> package org.springframework.messaging.support; <ide> <del>import java.util.HashMap; <add>import java.util.Collections; <add>import java.util.LinkedList; <ide> import java.util.List; <ide> import java.util.Map; <ide> <ide> import org.springframework.messaging.Message; <add>import org.springframework.util.Assert; <ide> import org.springframework.util.CollectionUtils; <ide> import org.springframework.util.LinkedMultiValueMap; <del>import org.springframework.util.MultiValueMap; <ide> import org.springframework.util.ObjectUtils; <ide> <ide> /** <ide> * An extension of {@link MessageHeaderAccessor} that also stores and provides read/write <ide> * access to message headers from an external source -- e.g. a Spring {@link Message} <ide> * created to represent a STOMP message received from a STOMP client or message broker. <del> * Native message headers are kept in a {@link MultiValueMap} under the key <add> * Native message headers are kept in a {@code Map<String, List<String>>} under the key <ide> * {@link #NATIVE_HEADERS}. <ide> * <p> <del> * This class is not intended for direct use but is rather expected to be consumed <del> * through sub-classes such as <add> * This class is not intended for direct use but is rather expected to be used <add> * indirectly through protocol-specific sub-classes such as <ide> * {@link org.springframework.messaging.simp.stomp.StompHeaderAccessor StompHeaderAccessor}. <ide> * Such sub-classes may provide factory methods to translate message headers from <ide> * an external messaging source (e.g. STOMP) to Spring {@link Message} headers and <ide> public class NativeMessageHeaderAccessor extends MessageHeaderAccessor { <ide> public static final String NATIVE_HEADERS = "nativeHeaders"; <ide> <ide> <del> // wrapped native headers <del> private final Map<String, List<String>> originalNativeHeaders; <del> <del> // native header updates <del> private final MultiValueMap<String, String> nativeHeaders = new LinkedMultiValueMap<String, String>(4); <del> <add> /** <add> * A protected constructor to create new headers. <add> */ <add> protected NativeMessageHeaderAccessor() { <add> this((Map<String, List<String>>) null); <add> } <ide> <ide> /** <del> * A constructor for creating new headers, accepting an optional native header map. <add> * A protected constructor to create new headers. <add> * @param nativeHeaders native headers to create the message with, may be {@code null} <ide> */ <ide> protected NativeMessageHeaderAccessor(Map<String, List<String>> nativeHeaders) { <del> this.originalNativeHeaders = nativeHeaders; <add> if (!CollectionUtils.isEmpty(nativeHeaders)) { <add> setHeader(NATIVE_HEADERS, new LinkedMultiValueMap<String, String>(nativeHeaders)); <add> } <ide> } <ide> <ide> /** <del> * A constructor for accessing and modifying existing message headers. <add> * A protected constructor accepting the headers of an existing message to copy. <ide> */ <ide> protected NativeMessageHeaderAccessor(Message<?> message) { <ide> super(message); <del> this.originalNativeHeaders = initNativeHeaders(message); <del> } <del> <del> private static Map<String, List<String>> initNativeHeaders(Message<?> message) { <ide> if (message != null) { <ide> @SuppressWarnings("unchecked") <del> Map<String, List<String>> headers = (Map<String, List<String>>) message.getHeaders().get(NATIVE_HEADERS); <del> if (headers != null) { <del> return headers; <add> Map<String, List<String>> map = (Map<String, List<String>>) getHeader(NATIVE_HEADERS); <add> if (map != null) { <add> // Force removal since setHeader checks for equality <add> removeHeader(NATIVE_HEADERS); <add> setHeader(NATIVE_HEADERS, new LinkedMultiValueMap<String, String>(map)); <ide> } <ide> } <del> return null; <ide> } <ide> <del> @Override <del> public Map<String, Object> toMap() { <del> Map<String, Object> result = super.toMap(); <del> result.put(NATIVE_HEADERS, toNativeHeaderMap()); <del> return result; <del> } <del> <del> @Override <del> public boolean isModified() { <del> return (super.isModified() || (!this.nativeHeaders.isEmpty())); <add> @SuppressWarnings("unchecked") <add> private Map<String, List<String>> getNativeHeaders() { <add> return (Map<String, List<String>>) getHeader(NATIVE_HEADERS); <ide> } <ide> <ide> /** <del> * Return a map with native headers including original, wrapped headers (if any) plus <del> * additional header updates made through accessor methods. <add> * Return a copy of the native header values or an empty map. <ide> */ <ide> public Map<String, List<String>> toNativeHeaderMap() { <del> Map<String, List<String>> result = new HashMap<String, List<String>>(); <del> if (this.originalNativeHeaders != null) { <del> result.putAll(this.originalNativeHeaders); <del> } <del> for (String key : this.nativeHeaders.keySet()) { <del> List<String> value = this.nativeHeaders.get(key); <del> if (value == null) { <del> result.remove(key); <del> } <del> else { <del> result.put(key, value); <add> Map<String, List<String>> map = getNativeHeaders(); <add> return (map != null ? new LinkedMultiValueMap<String, String>(map) : Collections.<String, List<String>>emptyMap()); <add> } <add> <add> @Override <add> public void setImmutable() { <add> if (isMutable()) { <add> Map<String, List<String>> map = getNativeHeaders(); <add> if (map != null) { <add> // Force removal since setHeader checks for equality <add> removeHeader(NATIVE_HEADERS); <add> setHeader(NATIVE_HEADERS, Collections.<String, List<String>>unmodifiableMap(map)); <ide> } <add> super.setImmutable(); <ide> } <del> return result; <ide> } <ide> <ide> /** <del> * Return all values for the specified native header or {@code null}. <add> * Whether the native header map contains the give header name. <add> */ <add> public boolean containsNativeHeader(String headerName) { <add> Map<String, List<String>> map = getNativeHeaders(); <add> return (map != null ? map.containsKey(headerName) : false); <add> } <add> <add> /** <add> * @return all values for the specified native header or {@code null}. <ide> */ <ide> public List<String> getNativeHeader(String headerName) { <del> if (this.nativeHeaders.containsKey(headerName)) { <del> return this.nativeHeaders.get(headerName); <del> } <del> else if (this.originalNativeHeaders != null) { <del> return this.originalNativeHeaders.get(headerName); <del> } <del> return null; <add> Map<String, List<String>> map = getNativeHeaders(); <add> return (map != null ? map.get(headerName) : null); <ide> } <ide> <ide> /** <del> * Return the first value for the specified native header of {@code null}. <add> * @return the first value for the specified native header of {@code null}. <ide> */ <ide> public String getFirstNativeHeader(String headerName) { <del> List<String> values = getNativeHeader(headerName); <del> return CollectionUtils.isEmpty(values) ? null : values.get(0); <add> Map<String, List<String>> map = getNativeHeaders(); <add> if (map != null) { <add> List<String> values = map.get(headerName); <add> if (values != null) { <add> return values.get(0); <add> } <add> } <add> return null; <ide> } <ide> <ide> /** <del> * Set the specified native header value. <add> * Set the specified native header value replacing existing values. <ide> */ <ide> public void setNativeHeader(String name, String value) { <del> if (!ObjectUtils.nullSafeEquals(value, getHeader(name))) { <del> this.nativeHeaders.set(name, value); <add> Assert.state(isMutable(), "Already immutable"); <add> Map<String, List<String>> map = getNativeHeaders(); <add> if (value == null) { <add> if (map != null && map.get(name) != null) { <add> setModified(true); <add> map.remove(name); <add> } <add> return; <add> } <add> if (map == null) { <add> map = new LinkedMultiValueMap<String, String>(4); <add> setHeader(NATIVE_HEADERS, map); <add> } <add> List<String> values = new LinkedList<String>(); <add> values.add(value); <add> if (!ObjectUtils.nullSafeEquals(values, getHeader(name))) { <add> setModified(true); <add> map.put(name, values); <ide> } <ide> } <ide> <ide> /** <del> * Add the specified native header value. <add> * Add the specified native header value to existing values. <ide> */ <ide> public void addNativeHeader(String name, String value) { <del> this.nativeHeaders.add(name, value); <add> Assert.state(isMutable(), "Already immutable"); <add> if (value == null) { <add> return; <add> } <add> Map<String, List<String>> nativeHeaders = getNativeHeaders(); <add> if (nativeHeaders == null) { <add> nativeHeaders = new LinkedMultiValueMap<String, String>(4); <add> setHeader(NATIVE_HEADERS, nativeHeaders); <add> } <add> List<String> values = nativeHeaders.get(name); <add> if (values == null) { <add> values = new LinkedList<String>(); <add> nativeHeaders.put(name, values); <add> } <add> values.add(value); <add> setModified(true); <ide> } <ide> <ide> } <ide><path>spring-messaging/src/test/java/org/springframework/messaging/MessageHeadersTests.java <ide> import java.io.ByteArrayOutputStream; <ide> import java.io.ObjectInputStream; <ide> import java.io.ObjectOutputStream; <add>import java.util.Collections; <ide> import java.util.HashMap; <ide> import java.util.Map; <ide> import java.util.Set; <ide> public void testTimestampOverwritten() throws Exception { <ide> assertNotSame(headers1.getTimestamp(), headers2.getTimestamp()); <ide> } <ide> <add> @Test <add> public void testTimestampProvided() throws Exception { <add> MessageHeaders headers = new MessageHeaders(null, null, 10L); <add> assertEquals(10L, (long) headers.getTimestamp()); <add> } <add> <add> @Test <add> public void testTimestampProvidedNullValue() throws Exception { <add> Map<String, Object> input = Collections.<String, Object>singletonMap(MessageHeaders.TIMESTAMP, 1L); <add> MessageHeaders headers = new MessageHeaders(input, null, null); <add> assertNotNull(headers.getTimestamp()); <add> } <add> <add> @Test <add> public void testTimestampNone() throws Exception { <add> MessageHeaders headers = new MessageHeaders(null, null, -1L); <add> assertNull(headers.getTimestamp()); <add> } <add> <ide> @Test <ide> public void testIdOverwritten() throws Exception { <ide> MessageHeaders headers1 = new MessageHeaders(null); <ide> public void testId() { <ide> assertNotNull(headers.getId()); <ide> } <ide> <add> @Test <add> public void testIdProvided() { <add> UUID id = new UUID(0L, 25L); <add> MessageHeaders headers = new MessageHeaders(null, id, null); <add> assertEquals(id, headers.getId()); <add> } <add> <add> @Test <add> public void testIdProvidedNullValue() { <add> Map<String, Object> input = Collections.<String, Object>singletonMap(MessageHeaders.ID, new UUID(0L, 25L)); <add> MessageHeaders headers = new MessageHeaders(input, null, null); <add> assertNotNull(headers.getId()); <add> } <add> <add> @Test <add> public void testIdNone() { <add> MessageHeaders headers = new MessageHeaders(null, MessageHeaders.ID_VALUE_NONE, null); <add> assertNull(headers.getId()); <add> } <add> <ide> @Test <ide> public void testNonTypedAccessOfHeaderValue() { <ide> Integer value = new Integer(123); <ide> public void subClassWithCustomIdAndNoTimestamp() { <ide> class MyMH extends MessageHeaders { <ide> <ide> public MyMH() { <del> super(null, new UUID(0, id.incrementAndGet()), null); <add> super(null, new UUID(0, id.incrementAndGet()), -1L); <ide> } <ide> <ide> } <ide><path>spring-messaging/src/test/java/org/springframework/messaging/handler/annotation/support/HeaderMethodArgumentResolverTests.java <ide> package org.springframework.messaging.handler.annotation.support; <ide> <ide> import java.lang.reflect.Method; <add>import java.util.List; <add>import java.util.Map; <ide> <ide> import org.junit.Before; <ide> import org.junit.Test; <ide> private void handleMessage( <ide> public static class TestMessageHeaderAccessor extends NativeMessageHeaderAccessor { <ide> <ide> protected TestMessageHeaderAccessor() { <del> super((Message<?>) null); <add> super((Map<String, List<String>>) null); <ide> } <ide> } <ide> <ide><path>spring-messaging/src/test/java/org/springframework/messaging/simp/SimpMessagingTemplateTests.java <ide> import org.springframework.messaging.Message; <ide> import org.springframework.messaging.StubMessageChannel; <ide> import org.springframework.messaging.support.NativeMessageHeaderAccessor; <add>import org.springframework.util.LinkedMultiValueMap; <ide> <ide> import java.util.*; <ide> <ide> public void convertAndSendWithCustomHeader() { <ide> <ide> @Test <ide> public void convertAndSendWithCustomHeaderNonNative() { <del> Map<String, Object> headers = new HashMap<String, Object>(); <add> Map<String, Object> headers = new HashMap<>(); <ide> headers.put("key", "value"); <del> headers.put(NativeMessageHeaderAccessor.NATIVE_HEADERS, Collections.emptyMap()); <add> headers.put(NativeMessageHeaderAccessor.NATIVE_HEADERS, new LinkedMultiValueMap<String, String>()); <ide> this.messagingTemplate.convertAndSend("/foo", "data", headers); <ide> <ide> List<Message<byte[]>> messages = this.messageChannel.getMessages(); <ide><path>spring-messaging/src/test/java/org/springframework/messaging/simp/stomp/BufferingStompDecoderTests.java <ide> import org.junit.Test; <ide> import org.springframework.messaging.Message; <ide> import org.springframework.messaging.converter.MessageConversionException; <add>import org.springframework.util.LinkedMultiValueMap; <ide> <ide> import java.nio.ByteBuffer; <ide> import java.nio.charset.Charset; <ide> public void bufferSizeLimit() throws InterruptedException { <ide> stompDecoder.decode(toByteBuffer(payload)); <ide> } <ide> <add> @Test <add> public void incompleteCommand() throws InterruptedException { <add> <add> BufferingStompDecoder stompDecoder = new BufferingStompDecoder(128); <add> String chunk = "MESSAG"; <add> <add> LinkedMultiValueMap<String, String> headers = new LinkedMultiValueMap<>(); <add> List<Message<byte[]>> messages = stompDecoder.decode(toByteBuffer(chunk), headers); <add> assertEquals(0, messages.size()); <add> } <add> <ide> <ide> private ByteBuffer toByteBuffer(String chunk) { <ide> return ByteBuffer.wrap(chunk.getBytes(Charset.forName("UTF-8"))); <ide><path>spring-messaging/src/test/java/org/springframework/messaging/simp/stomp/StompCodecTests.java <ide> import org.springframework.messaging.simp.SimpMessageType; <ide> import org.springframework.messaging.support.MessageBuilder; <ide> <add>import org.springframework.util.InvalidMimeTypeException; <ide> import reactor.function.Consumer; <ide> import reactor.function.Function; <ide> import reactor.io.Buffer; <ide> public void decodeFrameWithCrLfEols() { <ide> StompHeaderAccessor headers = StompHeaderAccessor.wrap(frame); <ide> <ide> assertEquals(StompCommand.DISCONNECT, headers.getCommand()); <del> assertEquals(0, headers.toStompHeaderMap().size()); <add> assertEquals(0, headers.toNativeHeaderMap().size()); <ide> assertEquals(0, frame.getPayload().length); <ide> } <ide> <ide> public void decodeFrameWithNoHeadersAndNoBody() { <ide> StompHeaderAccessor headers = StompHeaderAccessor.wrap(frame); <ide> <ide> assertEquals(StompCommand.DISCONNECT, headers.getCommand()); <del> assertEquals(0, headers.toStompHeaderMap().size()); <add> assertEquals(0, headers.toNativeHeaderMap().size()); <ide> assertEquals(0, frame.getPayload().length); <ide> } <ide> <ide> public void decodeFrameWithNoBody() { <ide> <ide> assertEquals(StompCommand.CONNECT, headers.getCommand()); <ide> <del> assertEquals(2, headers.toStompHeaderMap().size()); <add> assertEquals(2, headers.toNativeHeaderMap().size()); <ide> assertEquals("1.1", headers.getFirstNativeHeader("accept-version")); <ide> assertEquals("github.org", headers.getHost()); <ide> <ide> public void decodeFrame() throws UnsupportedEncodingException { <ide> <ide> assertEquals(StompCommand.SEND, headers.getCommand()); <ide> <del> assertEquals(1, headers.toStompHeaderMap().size()); <add> assertEquals(headers.toNativeHeaderMap().toString(), 1, headers.toNativeHeaderMap().size()); <ide> assertEquals("test", headers.getDestination()); <ide> <ide> String bodyText = new String(frame.getPayload()); <ide> public void decodeFrame() throws UnsupportedEncodingException { <ide> <ide> @Test <ide> public void decodeFrameWithContentLength() { <del> Message<byte[]> frame = decode("SEND\ncontent-length:23\n\nThe body of the message\0"); <del> StompHeaderAccessor headers = StompHeaderAccessor.wrap(frame); <add> Message<byte[]> message = decode("SEND\ncontent-length:23\n\nThe body of the message\0"); <add> StompHeaderAccessor headers = StompHeaderAccessor.wrap(message); <ide> <ide> assertEquals(StompCommand.SEND, headers.getCommand()); <ide> <del> assertEquals(1, headers.toStompHeaderMap().size()); <add> assertEquals(1, headers.toNativeHeaderMap().size()); <ide> assertEquals(Integer.valueOf(23), headers.getContentLength()); <ide> <del> String bodyText = new String(frame.getPayload()); <add> String bodyText = new String(message.getPayload()); <ide> assertEquals("The body of the message", bodyText); <ide> } <ide> <ide> // SPR-11528 <ide> <ide> @Test <ide> public void decodeFrameWithInvalidContentLength() { <del> Message<byte[]> frame = decode("SEND\ncontent-length:-1\n\nThe body of the message\0"); <del> StompHeaderAccessor headers = StompHeaderAccessor.wrap(frame); <add> Message<byte[]> message = decode("SEND\ncontent-length:-1\n\nThe body of the message\0"); <add> StompHeaderAccessor headers = StompHeaderAccessor.wrap(message); <ide> <ide> assertEquals(StompCommand.SEND, headers.getCommand()); <ide> <del> assertEquals(1, headers.toStompHeaderMap().size()); <add> assertEquals(1, headers.toNativeHeaderMap().size()); <ide> assertEquals(Integer.valueOf(-1), headers.getContentLength()); <ide> <del> String bodyText = new String(frame.getPayload()); <add> String bodyText = new String(message.getPayload()); <ide> assertEquals("The body of the message", bodyText); <ide> } <ide> <ide> public void decodeFrameWithContentLengthZero() { <ide> <ide> assertEquals(StompCommand.SEND, headers.getCommand()); <ide> <del> assertEquals(1, headers.toStompHeaderMap().size()); <add> assertEquals(1, headers.toNativeHeaderMap().size()); <ide> assertEquals(Integer.valueOf(0), headers.getContentLength()); <ide> <ide> String bodyText = new String(frame.getPayload()); <ide> public void decodeFrameWithNullOctectsInTheBody() { <ide> <ide> assertEquals(StompCommand.SEND, headers.getCommand()); <ide> <del> assertEquals(1, headers.toStompHeaderMap().size()); <add> assertEquals(1, headers.toNativeHeaderMap().size()); <ide> assertEquals(Integer.valueOf(23), headers.getContentLength()); <ide> <ide> String bodyText = new String(frame.getPayload()); <ide> public void decodeFrameWithEscapedHeaders() { <ide> <ide> assertEquals(StompCommand.DISCONNECT, headers.getCommand()); <ide> <del> assertEquals(1, headers.toStompHeaderMap().size()); <add> assertEquals(1, headers.toNativeHeaderMap().size()); <ide> assertEquals("alpha:bravo\r\n\\", headers.getFirstNativeHeader("a:\r\n\\b")); <ide> } <ide> <ide> public void accept(Message<byte[]> message) { <ide> assertEquals(StompCommand.DISCONNECT, StompHeaderAccessor.wrap(messages.get(1)).getCommand()); <ide> } <ide> <add> @Test <add> public void decodeFrameWithIncompleteCommand() { <add> assertIncompleteDecode("MESSAG"); <add> } <add> <ide> @Test <ide> public void decodeFrameWithIncompleteHeader() { <ide> assertIncompleteDecode("SEND\ndestination"); <ide> public void decodeFrameWithInsufficientContent() { <ide> assertIncompleteDecode("SEND\ncontent-length:23\n\nThe body of the mess"); <ide> } <ide> <add> @Test <add> public void decodeFrameWithIncompleteContentType() { <add> assertIncompleteDecode("SEND\ncontent-type:text/plain;charset=U"); <add> } <add> <add> @Test(expected = InvalidMimeTypeException.class) <add> public void decodeFrameWithInvalidContentType() { <add> assertIncompleteDecode("SEND\ncontent-type:text/plain;charset=U\n\nThe body\0"); <add> } <add> <ide> @Test(expected=StompConversionException.class) <ide> public void decodeFrameWithIncorrectTerminator() { <ide> decode("SEND\ncontent-length:23\n\nThe body of the message*"); <ide> public void accept(Message<byte[]> message) { <ide> public void encodeFrameWithNoHeadersAndNoBody() { <ide> StompHeaderAccessor headers = StompHeaderAccessor.create(StompCommand.DISCONNECT); <ide> <del> Message<byte[]> frame = MessageBuilder.withPayload(new byte[0]).setHeaders(headers).build(); <add> Message<byte[]> frame = MessageBuilder.createMessage(new byte[0], headers.getMessageHeaders()); <ide> <ide> assertEquals("DISCONNECT\n\n\0", new StompCodec().encoder().apply(frame).asString()); <ide> } <ide> public void encodeFrameWithHeaders() { <ide> headers.setAcceptVersion("1.2"); <ide> headers.setHost("github.org"); <ide> <del> Message<byte[]> frame = MessageBuilder.withPayload(new byte[0]).setHeaders(headers).build(); <add> Message<byte[]> frame = MessageBuilder.createMessage(new byte[0], headers.getMessageHeaders()); <ide> <ide> String frameString = new StompCodec().encoder().apply(frame).asString(); <ide> <ide> public void encodeFrameWithHeadersThatShouldBeEscaped() { <ide> StompHeaderAccessor headers = StompHeaderAccessor.create(StompCommand.DISCONNECT); <ide> headers.addNativeHeader("a:\r\n\\b", "alpha:bravo\r\n\\"); <ide> <del> Message<byte[]> frame = MessageBuilder.withPayload(new byte[0]).setHeaders(headers).build(); <add> Message<byte[]> frame = MessageBuilder.createMessage(new byte[0], headers.getMessageHeaders()); <ide> <del> assertEquals("DISCONNECT\na\\c\\r\\n\\\\b:alpha\\cbravo\\r\\n\\\\\n\n\0", new StompCodec().encoder().apply(frame).asString()); <add> assertEquals("DISCONNECT\na\\c\\r\\n\\\\b:alpha\\cbravo\\r\\n\\\\\n\n\0", <add> new StompCodec().encoder().apply(frame).asString()); <ide> } <ide> <ide> @Test <ide> public void encodeFrameWithHeadersBody() { <ide> StompHeaderAccessor headers = StompHeaderAccessor.create(StompCommand.SEND); <ide> headers.addNativeHeader("a", "alpha"); <ide> <del> Message<byte[]> frame = MessageBuilder.withPayload("Message body".getBytes()).setHeaders(headers).build(); <add> Message<byte[]> frame = MessageBuilder.createMessage("Message body".getBytes(), headers.getMessageHeaders()); <ide> <del> assertEquals("SEND\na:alpha\ncontent-length:12\n\nMessage body\0", new StompCodec().encoder().apply(frame).asString()); <add> assertEquals("SEND\na:alpha\ncontent-length:12\n\nMessage body\0", <add> new StompCodec().encoder().apply(frame).asString()); <ide> } <ide> <ide> private void assertIncompleteDecode(String partialFrame) { <ide><path>spring-messaging/src/test/java/org/springframework/messaging/simp/stomp/StompHeaderAccessorTests.java <ide> /* <del> * Copyright 2002-2013 the original author or authors. <add> * Copyright 2002-2014 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> <ide> package org.springframework.messaging.simp.stomp; <ide> <add>import java.io.UnsupportedEncodingException; <ide> import java.util.List; <ide> import java.util.Map; <ide> <add>import org.hamcrest.CoreMatchers; <ide> import org.junit.Test; <ide> import org.springframework.messaging.Message; <ide> import org.springframework.messaging.MessageHeaders; <add>import org.springframework.messaging.simp.SimpMessageHeaderAccessor; <ide> import org.springframework.messaging.simp.SimpMessageType; <ide> import org.springframework.messaging.support.MessageBuilder; <add>import org.springframework.messaging.support.MessageHeaderAccessor; <add>import org.springframework.util.AlternativeJdkIdGenerator; <ide> import org.springframework.util.LinkedMultiValueMap; <ide> import org.springframework.util.MimeTypeUtils; <ide> import org.springframework.util.MultiValueMap; <ide> <ide> import static org.junit.Assert.*; <add>import static org.junit.Assert.assertEquals; <ide> <ide> /** <del> * Test fixture for {@link StompHeaderAccessor}. <add> * Unit tests for {@link StompHeaderAccessor}. <ide> * <ide> * @author Rossen Stoyanchev <ide> * @since 4.0 <ide> public void createWithConnectNativeHeaders() { <ide> extHeaders.add(StompHeaderAccessor.STOMP_LOGIN_HEADER, "joe"); <ide> extHeaders.add(StompHeaderAccessor.STOMP_PASSCODE_HEADER, "joe123"); <ide> <del> StompHeaderAccessor headers = StompHeaderAccessor.create(StompCommand.CONNECT, extHeaders); <add> StompHeaderAccessor headerAccessor = StompHeaderAccessor.create(StompCommand.CONNECT, extHeaders); <ide> <del> assertEquals(StompCommand.CONNECT, headers.getCommand()); <del> assertEquals(SimpMessageType.CONNECT, headers.getMessageType()); <del> assertNotNull(headers.getHeader("stompCredentials")); <del> assertEquals("joe", headers.getLogin()); <del> assertEquals("PROTECTED", headers.getPasscode()); <add> assertEquals(StompCommand.CONNECT, headerAccessor.getCommand()); <add> assertEquals(SimpMessageType.CONNECT, headerAccessor.getMessageType()); <add> assertNotNull(headerAccessor.getHeader("stompCredentials")); <add> assertEquals("joe", headerAccessor.getLogin()); <add> assertEquals("joe123", headerAccessor.getPasscode()); <add> assertThat(headerAccessor.toString(), CoreMatchers.containsString("passcode=[PROTECTED]")); <ide> <del> Map<String, List<String>> output = headers.toStompHeaderMap(); <add> Map<String, List<String>> output = headerAccessor.toNativeHeaderMap(); <ide> assertEquals("joe", output.get(StompHeaderAccessor.STOMP_LOGIN_HEADER).get(0)); <del> assertEquals("joe123", output.get(StompHeaderAccessor.STOMP_PASSCODE_HEADER).get(0)); <add> assertEquals("PROTECTED", output.get(StompHeaderAccessor.STOMP_PASSCODE_HEADER).get(0)); <ide> } <ide> <ide> @Test <ide> public void toNativeHeadersMessageFrame() { <ide> headers.setSubscriptionId("s1"); <ide> headers.setDestination("/d"); <ide> headers.setContentType(MimeTypeUtils.APPLICATION_JSON); <add> headers.updateStompCommandAsServerMessage(); <ide> <ide> Map<String, List<String>> actual = headers.toNativeHeaderMap(); <ide> <del> assertEquals(4, actual.size()); <add> assertEquals(actual.toString(), 4, actual.size()); <ide> assertEquals("s1", actual.get(StompHeaderAccessor.STOMP_SUBSCRIPTION_HEADER).get(0)); <ide> assertEquals("/d", actual.get(StompHeaderAccessor.STOMP_DESTINATION_HEADER).get(0)); <ide> assertEquals("application/json", actual.get(StompHeaderAccessor.STOMP_CONTENT_TYPE_HEADER).get(0)); <ide> public void toNativeHeadersMessageFrame() { <ide> @Test <ide> public void toNativeHeadersContentType() { <ide> <del> Message<byte[]> message = MessageBuilder.withPayload(new byte[0]) <del> .setHeader(MessageHeaders.CONTENT_TYPE, MimeTypeUtils.APPLICATION_ATOM_XML).build(); <add> SimpMessageHeaderAccessor simpHeaderAccessor = SimpMessageHeaderAccessor.create(); <add> simpHeaderAccessor.setContentType(MimeTypeUtils.APPLICATION_ATOM_XML); <add> Message<byte[]> message = MessageBuilder.createMessage(new byte[0], simpHeaderAccessor.getMessageHeaders()); <ide> <del> StompHeaderAccessor headers = StompHeaderAccessor.wrap(message); <del> Map<String, List<String>> map = headers.toNativeHeaderMap(); <add> StompHeaderAccessor stompHeaderAccessor = StompHeaderAccessor.wrap(message); <add> Map<String, List<String>> map = stompHeaderAccessor.toNativeHeaderMap(); <ide> <ide> assertEquals("application/atom+xml", map.get(StompHeaderAccessor.STOMP_CONTENT_TYPE_HEADER).get(0)); <ide> } <ide> <add> @Test <add> public void encodeConnectWithLoginAndPasscode() throws UnsupportedEncodingException { <add> <add> MultiValueMap<String, String> extHeaders = new LinkedMultiValueMap<>(); <add> extHeaders.add(StompHeaderAccessor.STOMP_LOGIN_HEADER, "joe"); <add> extHeaders.add(StompHeaderAccessor.STOMP_PASSCODE_HEADER, "joe123"); <add> <add> StompHeaderAccessor headerAccessor = StompHeaderAccessor.create(StompCommand.CONNECT, extHeaders); <add> Message<byte[]> message = MessageBuilder.createMessage(new byte[0], headerAccessor.getMessageHeaders()); <add> byte[] bytes = new StompEncoder().encode(message); <add> <add> assertEquals("CONNECT\nlogin:joe\npasscode:joe123\n\n\0", new String(bytes, "UTF-8")); <add> } <add> <ide> @Test <ide> public void modifyCustomNativeHeader() { <ide> <ide> public void modifyCustomNativeHeader() { <ide> assertNotNull("abc123", actual.get("accountId").get(0)); <ide> } <ide> <add> @Test <add> public void messageIdAndTimestampDefaultBehavior() { <add> StompHeaderAccessor headerAccessor = StompHeaderAccessor.create(StompCommand.SEND); <add> MessageHeaders headers = headerAccessor.getMessageHeaders(); <add> <add> assertNull(headers.getId()); <add> assertNull(headers.getTimestamp()); <add> } <add> <add> @Test <add> public void messageIdAndTimestampEnabled() { <add> DefaultStompHeaderAccessorFactory factory = new DefaultStompHeaderAccessorFactory(); <add> factory.setIdGenerator(new AlternativeJdkIdGenerator()); <add> factory.setEnableTimestamp(true); <add> <add> StompHeaderAccessor headerAccessor = factory.create(StompCommand.SEND); <add> MessageHeaders headers = headerAccessor.getMessageHeaders(); <add> <add> assertNotNull(headers.getId()); <add> assertNotNull(headers.getTimestamp()); <add> } <add> <add> @Test <add> public void getAccessor() { <add> StompHeaderAccessor headerAccessor = StompHeaderAccessor.create(StompCommand.CONNECT); <add> Message<byte[]> message = MessageBuilder.createMessage(new byte[0], headerAccessor.getMessageHeaders()); <add> <add> assertSame(headerAccessor, MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class)); <add> } <ide> <ide> } <ide><path>spring-messaging/src/test/java/org/springframework/messaging/support/MessageBuilderTests.java <ide> /* <del> * Copyright 2002-2013 the original author or authors. <add> * Copyright 2002-2014 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> import java.util.Map; <ide> import java.util.UUID; <ide> <add>import org.junit.Rule; <ide> import org.junit.Test; <add>import org.junit.rules.ExpectedException; <ide> import org.springframework.messaging.Message; <ide> import org.springframework.messaging.MessageHeaders; <add>import org.springframework.util.IdGenerator; <ide> <ide> import static org.junit.Assert.*; <ide> <ide> /** <ide> * @author Mark Fisher <add> * @author Rossen Stoyanchev <ide> */ <ide> public class MessageBuilderTests { <ide> <add> @Rule <add> public final ExpectedException thrown = ExpectedException.none(); <add> <add> <ide> @Test <ide> public void testSimpleMessageCreation() { <ide> Message<String> message = MessageBuilder.withPayload("foo").build(); <ide> public void testSimpleMessageCreation() { <ide> public void testHeaderValues() { <ide> Message<String> message = MessageBuilder.withPayload("test") <ide> .setHeader("foo", "bar") <del> .setHeader("count", new Integer(123)) <add> .setHeader("count", 123) <ide> .build(); <ide> assertEquals("bar", message.getHeaders().get("foo", String.class)); <ide> assertEquals(new Integer(123), message.getHeaders().get("count", Integer.class)); <ide> public void testSameHeaderValueAddedNotModifiedSameMessage() throws Exception { <ide> @Test <ide> public void testCopySameHeaderValuesNotModifiedSameMessage() throws Exception { <ide> Date current = new Date(); <del> Map<String, Object> originalHeaders = new HashMap<String, Object>(); <add> Map<String, Object> originalHeaders = new HashMap<>(); <ide> originalHeaders.put("b", "xyz"); <ide> originalHeaders.put("c", current); <ide> Message<?> original = MessageBuilder.withPayload("foo").setHeader("a", 123).copyHeaders(originalHeaders).build(); <del> Map<String, Object> newHeaders = new HashMap<String, Object>(); <add> Map<String, Object> newHeaders = new HashMap<>(); <ide> newHeaders.put("a", 123); <ide> newHeaders.put("b", "xyz"); <ide> newHeaders.put("c", current); <ide> Message<?> result = MessageBuilder.fromMessage(original).copyHeaders(newHeaders).build(); <ide> assertEquals(original, result); <ide> } <ide> <add> @Test <add> public void testBuildMessageWithMutableHeaders() { <add> MessageHeaderAccessor accessor = new MessageHeaderAccessor(); <add> accessor.setLeaveMutable(true); <add> MessageHeaders headers = accessor.getMessageHeaders(); <add> Message<?> message = MessageBuilder.createMessage("payload", headers); <add> accessor.setHeader("foo", "bar"); <add> <add> assertEquals("bar", headers.get("foo")); <add> assertSame(accessor, MessageHeaderAccessor.getAccessor(message, MessageHeaderAccessor.class)); <add> } <add> <add> @Test <add> public void testBuildMessageWithDefaultMutability() { <add> MessageHeaderAccessor accessor = new MessageHeaderAccessor(); <add> MessageHeaders headers = accessor.getMessageHeaders(); <add> Message<?> message = MessageBuilder.createMessage("foo", headers); <add> <add> this.thrown.expect(IllegalStateException.class); <add> this.thrown.expectMessage("Already immutable"); <add> accessor.setHeader("foo", "bar"); <add> <add> assertSame(accessor, MessageHeaderAccessor.getAccessor(message, MessageHeaderAccessor.class)); <add> } <add> <add> @Test <add> public void testBuildMessageWithoutIdAndTimestamp() { <add> MessageHeaderAccessor headerAccessor = new MessageHeaderAccessor(); <add> headerAccessor.setIdGenerator(new IdGenerator() { <add> @Override <add> public UUID generateId() { <add> return MessageHeaders.ID_VALUE_NONE; <add> } <add> }); <add> Message<?> message = MessageBuilder.createMessage("foo", headerAccessor.getMessageHeaders()); <add> assertNull(message.getHeaders().getId()); <add> assertNull(message.getHeaders().getTimestamp()); <add> } <add> <add> @Test <add> public void testBuildMultipleMessages() { <add> MessageHeaderAccessor headerAccessor = new MessageHeaderAccessor(); <add> MessageBuilder messageBuilder = MessageBuilder.withPayload("payload").setHeaders(headerAccessor); <add> <add> headerAccessor.setHeader("foo", "bar1"); <add> Message<?> message1 = messageBuilder.build(); <add> <add> headerAccessor.setHeader("foo", "bar2"); <add> Message<?> message2 = messageBuilder.build(); <add> <add> headerAccessor.setHeader("foo", "bar3"); <add> Message<?> message3 = messageBuilder.build(); <add> <add> assertEquals("bar1", message1.getHeaders().get("foo")); <add> assertEquals("bar2", message2.getHeaders().get("foo")); <add> assertEquals("bar3", message3.getHeaders().get("foo")); <add> } <ide> } <ide><path>spring-messaging/src/test/java/org/springframework/messaging/support/MessageHeaderAccessorTests.java <ide> /* <del> * Copyright 2002-2013 the original author or authors. <add> * Copyright 2002-2014 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> <ide> package org.springframework.messaging.support; <ide> <del>import java.util.Collections; <add>import java.util.Arrays; <ide> import java.util.HashMap; <add>import java.util.HashSet; <ide> import java.util.Map; <add>import java.util.UUID; <ide> <add>import org.junit.Rule; <ide> import org.junit.Test; <add>import org.junit.rules.ExpectedException; <add>import org.springframework.messaging.Message; <ide> import org.springframework.messaging.MessageHeaders; <add>import org.springframework.util.IdGenerator; <ide> <ide> import static org.junit.Assert.*; <add>import static org.junit.Assert.assertEquals; <ide> <ide> /** <ide> * Test fixture for {@link MessageHeaderAccessor}. <ide> */ <ide> public class MessageHeaderAccessorTests { <ide> <add> @Rule <add> public final ExpectedException thrown = ExpectedException.none(); <add> <ide> <ide> @Test <del> public void empty() { <del> MessageHeaderAccessor headers = new MessageHeaderAccessor(); <del> assertEquals(Collections.emptyMap(), headers.toMap()); <add> public void newEmptyHeaders() { <add> MessageHeaderAccessor accessor = new MessageHeaderAccessor(); <add> assertEquals(0, accessor.toMap().size()); <ide> } <ide> <ide> @Test <del> public void wrapMessage() { <del> Map<String, Object> original = new HashMap<>(); <del> original.put("foo", "bar"); <del> original.put("bar", "baz"); <del> GenericMessage<String> message = new GenericMessage<>("payload", original); <add> public void existingHeaders() throws InterruptedException { <add> Map<String, Object> map = new HashMap<>(); <add> map.put("foo", "bar"); <add> map.put("bar", "baz"); <add> GenericMessage<String> message = new GenericMessage<>("payload", map); <ide> <del> MessageHeaderAccessor headers = new MessageHeaderAccessor(message); <del> Map<String, Object> actual = headers.toMap(); <add> MessageHeaderAccessor accessor = new MessageHeaderAccessor(message); <add> MessageHeaders actual = accessor.getMessageHeaders(); <ide> <del> assertEquals(4, actual.size()); <del> assertNotNull(actual.get(MessageHeaders.ID)); <del> assertNotNull(actual.get(MessageHeaders.TIMESTAMP)); <add> assertEquals(3, actual.size()); <ide> assertEquals("bar", actual.get("foo")); <ide> assertEquals("baz", actual.get("bar")); <ide> } <ide> <ide> @Test <del> public void wrapMessageAndModifyHeaders() { <del> Map<String, Object> original = new HashMap<>(); <del> original.put("foo", "bar"); <del> original.put("bar", "baz"); <del> GenericMessage<String> message = new GenericMessage<>("payload", original); <add> public void existingHeadersModification() throws InterruptedException { <add> Map<String, Object> map = new HashMap<>(); <add> map.put("foo", "bar"); <add> map.put("bar", "baz"); <add> GenericMessage<String> message = new GenericMessage<>("payload", map); <ide> <del> MessageHeaderAccessor headers = new MessageHeaderAccessor(message); <del> headers.setHeader("foo", "BAR"); <del> Map<String, Object> actual = headers.toMap(); <add> Thread.sleep(50); <ide> <del> assertEquals(4, actual.size()); <del> assertNotNull(actual.get(MessageHeaders.ID)); <del> assertNotNull(actual.get(MessageHeaders.TIMESTAMP)); <add> MessageHeaderAccessor accessor = new MessageHeaderAccessor(message); <add> accessor.setHeader("foo", "BAR"); <add> MessageHeaders actual = accessor.getMessageHeaders(); <add> <add> assertEquals(3, actual.size()); <add> assertNotEquals(message.getHeaders().getId(), actual.getId()); <ide> assertEquals("BAR", actual.get("foo")); <ide> assertEquals("baz", actual.get("bar")); <ide> } <ide> <ide> @Test <del> public void copyHeadersNullMap() { <add> public void copyHeadersFromNullMap() { <ide> MessageHeaderAccessor headers = new MessageHeaderAccessor(); <ide> headers.copyHeaders(null); <ide> headers.copyHeadersIfAbsent(null); <ide> <del> assertEquals(0, headers.toMap().size()); <add> assertEquals(1, headers.getMessageHeaders().size()); <add> assertEquals(new HashSet<>(Arrays.asList("id")), headers.getMessageHeaders().keySet()); <add> } <add> <add> @Test <add> public void toMap() { <add> <add> MessageHeaderAccessor accessor = new MessageHeaderAccessor(); <add> <add> accessor.setHeader("foo", "bar1"); <add> Map<String, Object> map1 = accessor.toMap(); <add> <add> accessor.setHeader("foo", "bar2"); <add> Map<String, Object> map2 = accessor.toMap(); <add> <add> accessor.setHeader("foo", "bar3"); <add> Map<String, Object> map3 = accessor.toMap(); <add> <add> assertEquals(1, map1.size()); <add> assertEquals(1, map2.size()); <add> assertEquals(1, map3.size()); <add> <add> assertEquals("bar1", map1.get("foo")); <add> assertEquals("bar2", map2.get("foo")); <add> assertEquals("bar3", map3.get("foo")); <add> } <add> <add> @Test <add> public void leaveMutable() { <add> MessageHeaderAccessor accessor = new MessageHeaderAccessor(); <add> accessor.setHeader("foo", "bar"); <add> accessor.setLeaveMutable(true); <add> MessageHeaders headers = accessor.getMessageHeaders(); <add> Message<?> message = MessageBuilder.createMessage("payload", headers); <add> <add> accessor.setHeader("foo", "baz"); <add> <add> assertEquals("baz", headers.get("foo")); <add> assertSame(accessor, MessageHeaderAccessor.getAccessor(message, MessageHeaderAccessor.class)); <add> } <add> <add> @Test <add> public void leaveMutableDefaultBehavior() { <add> MessageHeaderAccessor accessor = new MessageHeaderAccessor(); <add> accessor.setHeader("foo", "bar"); <add> MessageHeaders headers = accessor.getMessageHeaders(); <add> Message<?> message = MessageBuilder.createMessage("payload", headers); <add> <add> this.thrown.expect(IllegalStateException.class); <add> this.thrown.expectMessage("Already immutable"); <add> accessor.setLeaveMutable(true); <add> <add> this.thrown.expect(IllegalStateException.class); <add> this.thrown.expectMessage("Already immutable"); <add> accessor.setHeader("foo", "baz"); <add> <add> assertEquals("bar", headers.get("foo")); <add> assertSame(accessor, MessageHeaderAccessor.getAccessor(message, MessageHeaderAccessor.class)); <add> } <add> <add> @Test <add> public void getAccessor() { <add> MessageHeaderAccessor expected = new MessageHeaderAccessor(); <add> Message<?> message = MessageBuilder.createMessage("payload", expected.getMessageHeaders()); <add> assertSame(expected, MessageHeaderAccessor.getAccessor(message, MessageHeaderAccessor.class)); <add> } <add> <add> @Test <add> public void getMutableAccessorSameInstance() { <add> TestMessageHeaderAccessor expected = new TestMessageHeaderAccessor(); <add> expected.setLeaveMutable(true); <add> Message<?> message = MessageBuilder.createMessage("payload", expected.getMessageHeaders()); <add> <add> MessageHeaderAccessor actual = MessageHeaderAccessor.getMutableAccessor(message); <add> assertNotNull(actual); <add> assertTrue(actual.isMutable()); <add> assertSame(expected, actual); <add> } <add> <add> @Test <add> public void getMutableAccessorNewInstance() { <add> Message<?> message = MessageBuilder.withPayload("payload").build(); <add> <add> MessageHeaderAccessor actual = MessageHeaderAccessor.getMutableAccessor(message); <add> assertNotNull(actual); <add> assertTrue(actual.isMutable()); <add> } <add> <add> @Test <add> public void getMutableAccessorNewInstanceMatchingType() { <add> TestMessageHeaderAccessor expected = new TestMessageHeaderAccessor(); <add> Message<?> message = MessageBuilder.createMessage("payload", expected.getMessageHeaders()); <add> <add> MessageHeaderAccessor actual = MessageHeaderAccessor.getMutableAccessor(message); <add> assertNotNull(actual); <add> assertTrue(actual.isMutable()); <add> assertEquals(TestMessageHeaderAccessor.class, actual.getClass()); <add> } <add> <add> @Test <add> public void timestampEnabled() { <add> MessageHeaderAccessor accessor = new MessageHeaderAccessor(); <add> accessor.setEnableTimestamp(true); <add> assertNotNull(accessor.getMessageHeaders().getTimestamp()); <add> } <add> <add> @Test <add> public void timestampDefaultBehavior() { <add> MessageHeaderAccessor accessor = new MessageHeaderAccessor(); <add> assertNull(accessor.getMessageHeaders().getTimestamp()); <add> } <add> <add> @Test <add> public void timestampBehaviorCopyFromExistingMessage() { <add> MessageHeaderAccessor accessor = new MessageHeaderAccessor(); <add> accessor.setEnableTimestamp(true); <add> Message<?> message = MessageBuilder.createMessage("payload", accessor.getMessageHeaders()); <add> MessageHeaderAccessor secondAccessor = new MessageHeaderAccessor(message); <add> assertNotNull(secondAccessor.getMessageHeaders().getTimestamp()); <add> } <add> <add> @Test <add> public void idGeneratorCustom() { <add> final UUID id = new UUID(0L, 23L); <add> MessageHeaderAccessor accessor = new MessageHeaderAccessor(); <add> accessor.setIdGenerator(new IdGenerator() { <add> @Override <add> public UUID generateId() { <add> return id; <add> } <add> }); <add> assertSame(id, accessor.getMessageHeaders().getId()); <add> } <add> <add> @Test <add> public void idGeneratorDefaultBehavior() { <add> MessageHeaderAccessor accessor = new MessageHeaderAccessor(); <add> assertNotNull(accessor.getMessageHeaders().getId()); <add> } <add> <add> @Test <add> public void idGeneratorCopyFromExistingMessage() { <add> final UUID id = new UUID(0L, 23L); <add> MessageHeaderAccessor accessor = new MessageHeaderAccessor(); <add> accessor.setIdGenerator(new IdGenerator() { <add> @Override <add> public UUID generateId() { <add> return id; <add> } <add> }); <add> Message<?> message = MessageBuilder.createMessage("payload", accessor.getMessageHeaders()); <add> MessageHeaderAccessor secondAccessor = new MessageHeaderAccessor(message); <add> assertSame(id, secondAccessor.getMessageHeaders().getId()); <add> } <add> <add> <add> public static class TestMessageHeaderAccessor extends MessageHeaderAccessor { <add> <add> private TestMessageHeaderAccessor() { <add> } <add> <add> private TestMessageHeaderAccessor(Message<?> message) { <add> super(message); <add> } <add> <add> public static TestMessageHeaderAccessor wrap(Message<?> message) { <add> return new TestMessageHeaderAccessor(message); <add> } <add> <add> @Override <add> protected TestMessageHeaderAccessor createAccessor(Message<?> message) { <add> return wrap(message); <add> } <ide> } <ide> <ide> } <ide><path>spring-messaging/src/test/java/org/springframework/messaging/support/NativeMessageHeaderAccessorTests.java <ide> /* <del> * Copyright 2002-2013 the original author or authors. <add> * Copyright 2002-2014 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> import java.util.Arrays; <ide> import java.util.Collections; <ide> import java.util.HashMap; <add>import java.util.HashSet; <ide> import java.util.List; <ide> import java.util.Map; <ide> <add>import org.junit.Rule; <ide> import org.junit.Test; <add>import org.junit.rules.ExpectedException; <ide> import org.springframework.messaging.Message; <del>import org.springframework.messaging.MessageHeaders; <ide> import org.springframework.util.LinkedMultiValueMap; <ide> import org.springframework.util.MultiValueMap; <ide> <ide> import static org.junit.Assert.*; <add>import static org.junit.Assert.assertEquals; <ide> <ide> /** <ide> * Test fixture for {@link NativeMessageHeaderAccessor}. <ide> */ <ide> public class NativeMessageHeaderAccessorTests { <ide> <add> @Rule <add> public final ExpectedException thrown = ExpectedException.none(); <add> <ide> <ide> @Test <del> public void originalNativeHeaders() { <del> MultiValueMap<String, String> original = new LinkedMultiValueMap<>(); <del> original.add("foo", "bar"); <del> original.add("bar", "baz"); <add> public void createFromNativeHeaderMap() { <add> MultiValueMap<String, String> inputNativeHeaders = new LinkedMultiValueMap<>(); <add> inputNativeHeaders.add("foo", "bar"); <add> inputNativeHeaders.add("bar", "baz"); <ide> <del> NativeMessageHeaderAccessor headers = new NativeMessageHeaderAccessor(original); <del> Map<String, Object> actual = headers.toMap(); <add> NativeMessageHeaderAccessor headerAccessor = new NativeMessageHeaderAccessor(inputNativeHeaders); <add> Map<String, Object> actual = headerAccessor.toMap(); <ide> <del> assertEquals(1, actual.size()); <add> assertEquals(actual.toString(), 1, actual.size()); <ide> assertNotNull(actual.get(NativeMessageHeaderAccessor.NATIVE_HEADERS)); <del> assertEquals(original, actual.get(NativeMessageHeaderAccessor.NATIVE_HEADERS)); <add> assertEquals(inputNativeHeaders, actual.get(NativeMessageHeaderAccessor.NATIVE_HEADERS)); <add> assertNotSame(inputNativeHeaders, actual.get(NativeMessageHeaderAccessor.NATIVE_HEADERS)); <ide> } <ide> <ide> @Test <del> public void wrapMessage() { <del> <del> MultiValueMap<String, String> originalNativeHeaders = new LinkedMultiValueMap<>(); <del> originalNativeHeaders.add("foo", "bar"); <del> originalNativeHeaders.add("bar", "baz"); <add> public void createFromMessage() { <add> MultiValueMap<String, String> inputNativeHeaders = new LinkedMultiValueMap<>(); <add> inputNativeHeaders.add("foo", "bar"); <add> inputNativeHeaders.add("bar", "baz"); <ide> <del> Map<String, Object> original = new HashMap<String, Object>(); <del> original.put("a", "b"); <del> original.put(NativeMessageHeaderAccessor.NATIVE_HEADERS, originalNativeHeaders); <add> Map<String, Object> inputHeaders = new HashMap<String, Object>(); <add> inputHeaders.put("a", "b"); <add> inputHeaders.put(NativeMessageHeaderAccessor.NATIVE_HEADERS, inputNativeHeaders); <ide> <del> GenericMessage<String> message = new GenericMessage<>("p", original); <add> GenericMessage<String> message = new GenericMessage<>("p", inputHeaders); <add> NativeMessageHeaderAccessor headerAccessor = new NativeMessageHeaderAccessor(message); <add> Map<String, Object> actual = headerAccessor.toMap(); <ide> <del> NativeMessageHeaderAccessor headers = new NativeMessageHeaderAccessor(message); <del> Map<String, Object> actual = headers.toMap(); <del> <del> assertEquals(4, actual.size()); <del> assertNotNull(actual.get(MessageHeaders.ID)); <del> assertNotNull(actual.get(MessageHeaders.TIMESTAMP)); <add> assertEquals(2, actual.size()); <ide> assertEquals("b", actual.get("a")); <ide> assertNotNull(actual.get(NativeMessageHeaderAccessor.NATIVE_HEADERS)); <del> assertEquals(originalNativeHeaders, actual.get(NativeMessageHeaderAccessor.NATIVE_HEADERS)); <add> assertEquals(inputNativeHeaders, actual.get(NativeMessageHeaderAccessor.NATIVE_HEADERS)); <add> assertNotSame(inputNativeHeaders, actual.get(NativeMessageHeaderAccessor.NATIVE_HEADERS)); <ide> } <ide> <ide> @Test <del> public void wrapNullMessage() { <del> NativeMessageHeaderAccessor headers = new NativeMessageHeaderAccessor((Message<?>) null); <del> Map<String, Object> actual = headers.toMap(); <add> public void createFromMessageNull() { <add> NativeMessageHeaderAccessor headerAccessor = new NativeMessageHeaderAccessor((Message<?>) null); <ide> <del> assertEquals(1, actual.size()); <add> Map<String, Object> actual = headerAccessor.toMap(); <add> assertEquals(0, actual.size()); <ide> <ide> @SuppressWarnings("unchecked") <del> Map<String, List<String>> actualNativeHeaders = <del> (Map<String, List<String>>) actual.get(NativeMessageHeaderAccessor.NATIVE_HEADERS); <del> <add> Map<String, List<String>> actualNativeHeaders = headerAccessor.toNativeHeaderMap(); <ide> assertEquals(Collections.emptyMap(), actualNativeHeaders); <ide> } <ide> <ide> @Test <del> public void wrapMessageAndModifyHeaders() { <add> public void createFromMessageAndModify() { <ide> <del> MultiValueMap<String, String> originalNativeHeaders = new LinkedMultiValueMap<>(); <del> originalNativeHeaders.add("foo", "bar"); <del> originalNativeHeaders.add("bar", "baz"); <add> MultiValueMap<String, String> inputNativeHeaders = new LinkedMultiValueMap<>(); <add> inputNativeHeaders.add("foo", "bar"); <add> inputNativeHeaders.add("bar", "baz"); <ide> <del> Map<String, Object> original = new HashMap<String, Object>(); <del> original.put("a", "b"); <del> original.put(NativeMessageHeaderAccessor.NATIVE_HEADERS, originalNativeHeaders); <add> Map<String, Object> nativeHeaders = new HashMap<String, Object>(); <add> nativeHeaders.put("a", "b"); <add> nativeHeaders.put(NativeMessageHeaderAccessor.NATIVE_HEADERS, inputNativeHeaders); <ide> <del> GenericMessage<String> message = new GenericMessage<>("p", original); <add> GenericMessage<String> message = new GenericMessage<>("p", nativeHeaders); <ide> <del> NativeMessageHeaderAccessor headers = new NativeMessageHeaderAccessor(message); <del> headers.setHeader("a", "B"); <del> headers.setNativeHeader("foo", "BAR"); <add> NativeMessageHeaderAccessor headerAccessor = new NativeMessageHeaderAccessor(message); <add> headerAccessor.setHeader("a", "B"); <add> headerAccessor.setNativeHeader("foo", "BAR"); <ide> <del> Map<String, Object> actual = headers.toMap(); <add> Map<String, Object> actual = headerAccessor.toMap(); <ide> <del> assertEquals(4, actual.size()); <del> assertNotNull(actual.get(MessageHeaders.ID)); <del> assertNotNull(actual.get(MessageHeaders.TIMESTAMP)); <add> assertEquals(2, actual.size()); <ide> assertEquals("B", actual.get("a")); <ide> <ide> @SuppressWarnings("unchecked") <ide> public void wrapMessageAndModifyHeaders() { <ide> assertEquals(Arrays.asList("baz"), actualNativeHeaders.get("bar")); <ide> } <ide> <del>} <add> @Test <add> public void setNativeHeader() { <add> MultiValueMap<String, String> nativeHeaders = new LinkedMultiValueMap<>(); <add> nativeHeaders.add("foo", "bar"); <add> <add> NativeMessageHeaderAccessor headers = new NativeMessageHeaderAccessor(nativeHeaders); <add> headers.setNativeHeader("foo", "baz"); <add> <add> assertEquals(Arrays.asList("baz"), headers.getNativeHeader("foo")); <add> } <add> <add> @Test <add> public void setNativeHeaderNullValue() { <add> MultiValueMap<String, String> nativeHeaders = new LinkedMultiValueMap<>(); <add> nativeHeaders.add("foo", "bar"); <add> <add> NativeMessageHeaderAccessor headers = new NativeMessageHeaderAccessor(nativeHeaders); <add> headers.setNativeHeader("foo", null); <add> <add> assertNull(headers.getNativeHeader("foo")); <add> } <add> <add> @Test <add> public void setNativeHeaderLazyInit() { <add> NativeMessageHeaderAccessor headerAccessor = new NativeMessageHeaderAccessor(); <add> headerAccessor.setNativeHeader("foo", "baz"); <add> <add> assertEquals(Arrays.asList("baz"), headerAccessor.getNativeHeader("foo")); <add> } <add> <add> @Test <add> public void setNativeHeaderLazyInitNullValue() { <add> NativeMessageHeaderAccessor headerAccessor = new NativeMessageHeaderAccessor(); <add> headerAccessor.setNativeHeader("foo", null); <add> <add> assertNull(headerAccessor.getNativeHeader("foo")); <add> assertNull(headerAccessor.getMessageHeaders().get(NativeMessageHeaderAccessor.NATIVE_HEADERS)); <add> } <add> <add> @Test <add> public void setNativeHeaderImmutable() { <add> NativeMessageHeaderAccessor headerAccessor = new NativeMessageHeaderAccessor(); <add> headerAccessor.setNativeHeader("foo", "bar"); <add> headerAccessor.setImmutable(); <add> <add> this.thrown.expect(IllegalStateException.class); <add> this.thrown.expectMessage("Already immutable"); <add> headerAccessor.setNativeHeader("foo", "baz"); <add> } <add> <add> @Test <add> public void addNativeHeader() { <add> MultiValueMap<String, String> nativeHeaders = new LinkedMultiValueMap<>(); <add> nativeHeaders.add("foo", "bar"); <add> <add> NativeMessageHeaderAccessor headers = new NativeMessageHeaderAccessor(nativeHeaders); <add> headers.addNativeHeader("foo", "baz"); <add> <add> assertEquals(Arrays.asList("bar", "baz"), headers.getNativeHeader("foo")); <add> } <add> <add> @Test <add> public void addNativeHeaderNullValue() { <add> MultiValueMap<String, String> nativeHeaders = new LinkedMultiValueMap<>(); <add> nativeHeaders.add("foo", "bar"); <add> <add> NativeMessageHeaderAccessor headers = new NativeMessageHeaderAccessor(nativeHeaders); <add> headers.addNativeHeader("foo", null); <add> <add> assertEquals(Arrays.asList("bar"), headers.getNativeHeader("foo")); <add> } <add> <add> @Test <add> public void addNativeHeaderLazyInit() { <add> NativeMessageHeaderAccessor headerAccessor = new NativeMessageHeaderAccessor(); <add> headerAccessor.addNativeHeader("foo", "bar"); <add> <add> assertEquals(Arrays.asList("bar"), headerAccessor.getNativeHeader("foo")); <add> } <add> <add> @Test <add> public void addNativeHeaderLazyInitNullValue() { <add> NativeMessageHeaderAccessor headerAccessor = new NativeMessageHeaderAccessor(); <add> headerAccessor.addNativeHeader("foo", null); <add> <add> assertNull(headerAccessor.getNativeHeader("foo")); <add> assertNull(headerAccessor.getMessageHeaders().get(NativeMessageHeaderAccessor.NATIVE_HEADERS)); <add> } <add> <add> @Test <add> public void addNativeHeaderImmutable() { <add> NativeMessageHeaderAccessor headerAccessor = new NativeMessageHeaderAccessor(); <add> headerAccessor.addNativeHeader("foo", "bar"); <add> headerAccessor.setImmutable(); <add> <add> this.thrown.expect(IllegalStateException.class); <add> this.thrown.expectMessage("Already immutable"); <add> headerAccessor.addNativeHeader("foo", "baz"); <add> } <add> <add> @Test <add> public void setImmutableIdempotent() { <add> NativeMessageHeaderAccessor headerAccessor = new NativeMessageHeaderAccessor(); <add> headerAccessor.addNativeHeader("foo", "bar"); <add> headerAccessor.setImmutable(); <add> headerAccessor.setImmutable(); <add> } <add> <add>} <ide>\ No newline at end of file <ide><path>spring-websocket/src/test/java/org/springframework/web/socket/messaging/StompSubProtocolHandlerTests.java <ide> public void handleMessageFromClient() { <ide> assertNotNull(headers.getSessionAttributes()); <ide> assertEquals("joe", headers.getUser().getName()); <ide> assertEquals("guest", headers.getLogin()); <del> assertEquals("PROTECTED", headers.getPasscode()); <add> assertEquals("guest", headers.getPasscode()); <ide> assertArrayEquals(new long[] {10000, 10000}, headers.getHeartbeat()); <ide> assertEquals(new HashSet<>(Arrays.asList("1.1","1.0")), headers.getAcceptVersion()); <ide>
29
Python
Python
add missing numpy library
a91b81ba299deecfec41f1264fa4f4368745772d
<ide><path>keras/legacy/layers.py <add>import numpy as np <ide> import types as python_types <ide> import warnings <ide>
1
Python
Python
adjust sort order [ci skip]
f25f05c503c83949c9831028e221f3d024358889
<ide><path>spacy/util.py <ide> # Default order of sections in the config.cfg. Not all sections needs to exist, <ide> # and additional sections are added at the end, in alphabetical order. <ide> # fmt: off <del>CONFIG_SECTION_ORDER = ["paths", "variables", "system", "nlp", "components", "training", "pretraining"] <add>CONFIG_SECTION_ORDER = ["paths", "variables", "system", "nlp", "components", "corpora", "training", "pretraining"] <ide> # fmt: on <ide> <ide>
1
Javascript
Javascript
simplify cleartimeout & clearinterval
8204b0f9c6dbbdba1ca4120698a7f87ca1c9d91c
<ide><path>lib/timers.js <ide> function rearm(timer, start = TimerWrap.now()) { <ide> <ide> <ide> const clearTimeout = exports.clearTimeout = function(timer) { <del> if (timer && (timer[kOnTimeout] || timer._onTimeout)) { <del> timer[kOnTimeout] = timer._onTimeout = null; <add> if (timer && timer._onTimeout) { <add> timer._onTimeout = null; <ide> if (timer instanceof Timeout) { <ide> timer.close(); // for after === 0 <ide> } else {
1
PHP
PHP
replace shell with command where possible
633bcac5fc49ccb67a4d00443d86932c4cb507e0
<ide><path>tests/TestCase/Command/CompletionCommandTest.php <ide> */ <ide> namespace Cake\Test\TestCase\Command; <ide> <del>use Cake\Console\Shell; <add>use Cake\Console\Command; <ide> use Cake\Core\Configure; <ide> use Cake\Routing\Router; <ide> use Cake\TestSuite\ConsoleIntegrationTestCase; <ide> public function tearDown(): void <ide> } <ide> <ide> /** <del> * test that the startup method suppresses the shell header <add> * test that the startup method suppresses the command header <ide> * <ide> * @return void <ide> */ <ide> public function testStartup() <ide> { <ide> $this->exec('completion'); <del> $this->assertExitCode(Shell::CODE_ERROR); <add> $this->assertExitCode(Command::CODE_ERROR); <ide> <ide> $this->assertOutputNotContains('Welcome to CakePHP'); <ide> } <ide> public function testStartup() <ide> public function testCommands() <ide> { <ide> $this->exec('completion commands'); <del> $this->assertExitCode(Shell::CODE_SUCCESS); <add> $this->assertExitCode(Command::CODE_SUCCESS); <ide> <ide> $expected = [ <ide> 'test_plugin.example', <ide> public function testCommands() <ide> public function testOptionsNoArguments() <ide> { <ide> $this->exec('completion options'); <del> $this->assertExitCode(Shell::CODE_SUCCESS); <add> $this->assertExitCode(Command::CODE_SUCCESS); <ide> $this->assertOutputEmpty(); <ide> } <ide> <ide> public function testOptionsNoArguments() <ide> public function testOptionsNonExistingCommand() <ide> { <ide> $this->exec('completion options foo'); <del> $this->assertExitCode(Shell::CODE_SUCCESS); <add> $this->assertExitCode(Command::CODE_SUCCESS); <ide> $this->assertOutputEmpty(); <ide> } <ide> <ide> public function testOptionsNonExistingCommand() <ide> * <ide> * @return void <ide> */ <del> public function testOptionsShell() <add> public function testOptionsCommand() <ide> { <ide> $this->exec('completion options schema_cache'); <del> $this->assertExitCode(Shell::CODE_SUCCESS); <add> $this->assertExitCode(Command::CODE_SUCCESS); <ide> <ide> $expected = [ <ide> '--connection -c', <ide> public function testOptionsShellTask() <ide> 'This test does not work correctly with shells.' <ide> ); <ide> $this->exec('completion options sample sample'); <del> $this->assertExitCode(Shell::CODE_SUCCESS); <add> $this->assertExitCode(Command::CODE_SUCCESS); <ide> <ide> $expected = [ <ide> '--help -h', <ide> public function testOptionsShellTask() <ide> * <ide> * @return void <ide> */ <del> public function testOptionsShellCommand() <add> public function testOptionsSubCommand() <ide> { <ide> $this->exec('completion options cache list'); <del> $this->assertExitCode(Shell::CODE_SUCCESS); <add> $this->assertExitCode(Command::CODE_SUCCESS); <ide> <ide> $expected = [ <ide> '--help -h', <ide> public function testOptionsShellCommand() <ide> public function testOptionsNestedCommand() <ide> { <ide> $this->exec('completion options i18n extract'); <del> $this->assertExitCode(Shell::CODE_SUCCESS); <add> $this->assertExitCode(Command::CODE_SUCCESS); <ide> <ide> $expected = [ <ide> '--plugin', <ide> public function testOptionsNestedCommand() <ide> public function testSubCommandsCorePlugin() <ide> { <ide> $this->exec('completion subcommands schema_cache'); <del> $this->assertExitCode(Shell::CODE_SUCCESS); <add> $this->assertExitCode(Command::CODE_SUCCESS); <ide> <ide> $expected = "build clear"; <ide> $this->assertOutputContains($expected); <ide> public function testSubCommandsCorePlugin() <ide> public function testSubCommandsAppPlugin() <ide> { <ide> $this->exec('completion subcommands sample'); <del> $this->assertExitCode(Shell::CODE_SUCCESS); <add> $this->assertExitCode(Command::CODE_SUCCESS); <ide> $expected = [ <ide> 'derp', <ide> 'returnValue', <ide> public function testSubCommandsAppPlugin() <ide> public function testSubCommandsCoreMultiwordCommand() <ide> { <ide> $this->exec('completion subcommands cache'); <del> $this->assertExitCode(Shell::CODE_SUCCESS); <add> $this->assertExitCode(Command::CODE_SUCCESS); <ide> <ide> $expected = [ <ide> 'list', 'clear', 'clear_all', <ide> public function testSubCommandsCoreMultiwordCommand() <ide> public function testSubCommandsPlugin() <ide> { <ide> $this->exec('completion subcommands welcome'); <del> $this->assertExitCode(Shell::CODE_SUCCESS); <add> $this->assertExitCode(Command::CODE_SUCCESS); <ide> <ide> $expected = "say_hello"; <ide> $this->assertOutputContains($expected); <ide> public function testSubCommandsPlugin() <ide> public function testSubCommandsPluginDotNotationBackwardCompatibility() <ide> { <ide> $this->exec('completion subcommands test_plugin_two.welcome'); <del> $this->assertExitCode(Shell::CODE_SUCCESS); <add> $this->assertExitCode(Command::CODE_SUCCESS); <ide> <ide> $expected = "say_hello"; <ide> $this->assertOutputContains($expected); <ide> public function testSubCommandsPluginDotNotationBackwardCompatibility() <ide> public function testSubCommandsPluginDotNotation() <ide> { <ide> $this->exec('completion subcommands test_plugin_two.example'); <del> $this->assertExitCode(Shell::CODE_SUCCESS); <add> $this->assertExitCode(Command::CODE_SUCCESS); <ide> <ide> $expected = "say_hello"; <ide> $this->assertOutputContains($expected); <ide> public function testSubCommandsPluginDotNotation() <ide> public function testSubCommandsAppDuplicatePluginNoDot() <ide> { <ide> $this->exec('completion subcommands sample'); <del> $this->assertExitCode(Shell::CODE_SUCCESS); <add> $this->assertExitCode(Command::CODE_SUCCESS); <ide> <ide> $expected = [ <ide> 'derp', <ide> public function testSubCommandsAppDuplicatePluginNoDot() <ide> public function testSubCommandsPluginDuplicateApp() <ide> { <ide> $this->exec('completion subcommands test_plugin.sample'); <del> $this->assertExitCode(Shell::CODE_SUCCESS); <add> $this->assertExitCode(Command::CODE_SUCCESS); <ide> <ide> $expected = "example"; <ide> $this->assertOutputContains($expected); <ide> public function testSubCommandsPluginDuplicateApp() <ide> public function testSubCommandsNoArguments() <ide> { <ide> $this->exec('completion subcommands'); <del> $this->assertExitCode(Shell::CODE_SUCCESS); <add> $this->assertExitCode(Command::CODE_SUCCESS); <ide> <ide> $this->assertOutputEmpty(); <ide> } <ide> public function testSubCommandsNoArguments() <ide> public function testSubCommandsNonExistingCommand() <ide> { <ide> $this->exec('completion subcommands foo'); <del> $this->assertExitCode(Shell::CODE_SUCCESS); <add> $this->assertExitCode(Command::CODE_SUCCESS); <ide> <ide> $this->assertOutputEmpty(); <ide> } <ide> public function testSubCommandsNonExistingCommand() <ide> public function testSubCommands() <ide> { <ide> $this->exec('completion subcommands schema_cache'); <del> $this->assertExitCode(Shell::CODE_SUCCESS); <add> $this->assertExitCode(Command::CODE_SUCCESS); <ide> <ide> $expected = "build clear"; <ide> $this->assertOutputContains($expected); <ide> public function testFuzzy() <ide> public function testHelp() <ide> { <ide> $this->exec('completion --help'); <del> $this->assertExitCode(Shell::CODE_SUCCESS); <add> $this->assertExitCode(Command::CODE_SUCCESS); <ide> <ide> $this->assertOutputContains('Output a list of available commands'); <ide> $this->assertOutputContains('Output a list of available sub-commands');
1
Java
Java
fix multiple subscription bug on operation filter
581b19f0fef9fbd7f4a5e2d6569b8eca09bf28e1
<ide><path>rxjava-core/src/main/java/rx/operators/OperationFilter.java <ide> public static <T> Func1<Observer<T>, Subscription> filter(Observable<T> that, Fu <ide> <ide> private final Observable<T> that; <ide> private final Func1<T, Boolean> predicate; <del> private final AtomicObservableSubscription subscription = new AtomicObservableSubscription(); <ide> <ide> public Filter(Observable<T> that, Func1<T, Boolean> predicate) { <ide> this.that = that; <ide> this.predicate = predicate; <ide> } <ide> <ide> public Subscription call(final Observer<T> observer) { <add> final AtomicObservableSubscription subscription = new AtomicObservableSubscription(); <ide> return subscription.wrap(that.subscribe(new Observer<T>() { <ide> public void onNext(T value) { <ide> try {
1
Javascript
Javascript
change handlebars bindings to use scheduleonce
7642bfeeb7d2f025cb1112961aa5898f196661eb
<ide><path>packages/ember-handlebars/lib/helpers/binding.js <ide> function bind(property, options, preserveContext, shouldDisplay, valueNormalizer <ide> <ide> /** @private */ <ide> var observer = function() { <del> Ember.run.once(bindView, 'rerenderIfNeeded'); <add> Ember.run.scheduleOnce('render', bindView, 'rerenderIfNeeded'); <ide> }; <ide> <ide> // Observes the given property on the context and <ide> EmberHandlebars.registerHelper('bindAttr', function(options) { <ide> <ide> /** @private */ <ide> invoker = function() { <del> Ember.run.once(observer); <add> Ember.run.scheduleOnce('render', observer); <ide> }; <ide> <ide> // Add an observer to the view for when the property changes. <ide> EmberHandlebars.bindClasses = function(context, classBindings, view, bindAttrId, <ide> <ide> /** @private */ <ide> invoker = function() { <del> Ember.run.once(observer); <add> Ember.run.scheduleOnce('render', observer); <ide> }; <ide> <ide> if (path !== '' && path !== 'this') {
1
Go
Go
add mountlabel to dev
0c7143b32386c62cccd529de69abf88df938757d
<ide><path>pkg/libcontainer/mount/init.go <ide> package mount <ide> <ide> import ( <ide> "fmt" <add> "os" <add> "path/filepath" <add> "syscall" <add> <ide> "github.com/dotcloud/docker/pkg/label" <ide> "github.com/dotcloud/docker/pkg/libcontainer" <ide> "github.com/dotcloud/docker/pkg/libcontainer/mount/nodes" <ide> "github.com/dotcloud/docker/pkg/libcontainer/security/restrict" <ide> "github.com/dotcloud/docker/pkg/system" <del> "os" <del> "path/filepath" <del> "syscall" <ide> ) <ide> <ide> // default mount point flags <ide> func newSystemMounts(rootfs, mountLabel string, mounts libcontainer.Mounts) []mo <ide> } <ide> <ide> if len(mounts.OfType("devtmpfs")) == 1 { <del> systemMounts = append(systemMounts, mount{source: "tmpfs", path: filepath.Join(rootfs, "dev"), device: "tmpfs", flags: syscall.MS_NOSUID | syscall.MS_STRICTATIME, data: "mode=755"}) <add> systemMounts = append(systemMounts, mount{source: "tmpfs", path: filepath.Join(rootfs, "dev"), device: "tmpfs", flags: syscall.MS_NOSUID | syscall.MS_STRICTATIME, data: label.FormatMountLabel("mode=755", mountLabel)}) <ide> } <ide> systemMounts = append(systemMounts, <ide> mount{source: "shm", path: filepath.Join(rootfs, "dev", "shm"), device: "tmpfs", flags: defaultMountFlags, data: label.FormatMountLabel("mode=1777,size=65536k", mountLabel)}, <del> mount{source: "devpts", path: filepath.Join(rootfs, "dev", "pts"), device: "devpts", flags: syscall.MS_NOSUID | syscall.MS_NOEXEC, data: label.FormatMountLabel("newinstance,ptmxmode=0666,mode=620,gid=5", mountLabel)}) <add> mount{source: "devpts", path: filepath.Join(rootfs, "dev", "pts"), device: "devpts", flags: syscall.MS_NOSUID | syscall.MS_NOEXEC, data: label.FormatMountLabel("newinstance,ptmxmode=0666,mode=620,gid=5", mountLabel)}, <add> ) <ide> <ide> if len(mounts.OfType("sysfs")) == 1 { <ide> systemMounts = append(systemMounts, mount{source: "sysfs", path: filepath.Join(rootfs, "sys"), device: "sysfs", flags: defaultMountFlags})
1
Ruby
Ruby
update collectionproxy#destroy_all documentation
03402d206ae1d1977e5283173ecb43a88aacead0
<ide><path>activerecord/lib/active_record/associations/collection_proxy.rb <ide> class CollectionProxy < Relation <ide> <ide> ## <ide> # :method: destroy_all <del> # Destroy all the records from this association. <add> # Deletes the records of the collection directly from the database. <ide> # <ide> # class Person < ActiveRecord::Base <ide> # has_many :pets <ide> # end <ide> # <ide> # person.pets.size # => 3 <add> # person.pets <add> # # => [ <add> # # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>, <add> # # #<Pet id: 2, name: "Spook", person_id: 1>, <add> # # #<Pet id: 3, name: "Choo-Choo", person_id: 1> <add> # # ] <ide> # <ide> # person.pets.destroy_all <ide> # <ide> # person.pets.size # => 0 <ide> # person.pets # => [] <add> # <add> # Pet.find(1) # => Couldn't find Pet with id=1 <ide> <ide> ## <ide> # :method: empty?
1
Javascript
Javascript
fix typo $digest -> $watch
50eb7f15b8b9bfbf7b1aed193ce72ec9b586dc14
<ide><path>src/service/scope.js <ide> function $RootScopeProvider(){ <ide> scope.counter = 0; <ide> <ide> expect(scope.counter).toEqual(0); <del> scope.$digest('name', function(scope, newValue, oldValue) { <add> scope.$watch('name', function(scope, newValue, oldValue) { <ide> counter = counter + 1; <ide> }); <ide> expect(scope.counter).toEqual(0);
1
Javascript
Javascript
increase limit for network space overhead test
2550ddb04909f19068e947a18681e6c675346e42
<ide><path>test/sequential/test-net-bytes-per-incoming-chunk-overhead.js <ide> process.on('exit', () => { <ide> const bytesPerChunk = <ide> (process.memoryUsage().rss - baseRSS) / receivedChunks.length; <ide> // We should always have less than one page (usually ~ 4 kB) per chunk. <del> assert(bytesPerChunk < 512, `measured ${bytesPerChunk} bytes per chunk`); <add> assert(bytesPerChunk < 600, `measured ${bytesPerChunk} bytes per chunk`); <ide> });
1
PHP
PHP
pass array validation rules as array
5744ca139d686c21169cacdaaddbbaf726ed5553
<ide><path>src/Illuminate/Validation/Validator.php <ide> protected function explodeRules($rules) <ide> { <ide> foreach ($rules as $key => $rule) { <ide> if (Str::contains($key, '*')) { <del> $this->each($key, $rule); <add> $this->each($key, [$rule]); <ide> <ide> unset($rules[$key]); <ide> } else { <ide><path>tests/Validation/ValidationValidatorTest.php <ide> public function testValidateEach() <ide> $v = new Validator($trans, $data, ['foo' => 'Array']); <ide> $v->each('foo', 'numeric|min:4|max:16'); <ide> $this->assertTrue($v->passes()); <add> <add> $v = new Validator($trans, $data, ['foo' => 'Array']); <add> $v->each('foo', ['numeric','min:6','max:14']); <add> $this->assertFalse($v->passes()); <add> <add> $v = new Validator($trans, $data, ['foo' => 'Array']); <add> $v->each('foo', ['numeric','min:4','max:16']); <add> $this->assertTrue($v->passes()); <ide> } <ide> <ide> public function testValidateImplicitEachWithAsterisks() <ide> public function testValidateImplicitEachWithAsterisks() <ide> $v = new Validator($trans, $data, ['foo' => 'Array', 'foo.*' => 'Numeric|Min:4|Max:16']); <ide> $this->assertTrue($v->passes()); <ide> <add> $v = new Validator($trans, $data, ['foo' => 'Array', 'foo.*' => ['Numeric','Min:6','Max:16']]); <add> $this->assertFalse($v->passes()); <add> <add> $v = new Validator($trans, $data, ['foo' => 'Array', 'foo.*' => ['Numeric','Min:4','Max:16']]); <add> $this->assertTrue($v->passes()); <add> <ide> $v = new Validator($trans, ['foo' => [['name' => 'first'], ['name' => 'second']]], <ide> ['foo' => 'Array', 'foo.*.name' => 'Required|String']); <ide> $this->assertTrue($v->passes()); <ide> public function testValidateImplicitEachWithAsterisks() <ide> $v = new Validator($trans, ['foo' => [['name' => 'first', 'votes' => [1, 2]], ['name' => 'second', 'votes' => ['something', 2]]]], <ide> ['foo' => 'Array', 'foo.*.name' => 'Required|String', 'foo.*.votes.*' => 'Required|Integer']); <ide> $this->assertFalse($v->passes()); <add> <add> $v = new Validator($trans, ['foo' => [['name' => 'first'], ['name' => 'second']]], <add> ['foo' => 'Array', 'foo.*.name' => ['Required','String']]); <add> $this->assertTrue($v->passes()); <add> <add> $v = new Validator($trans, ['foo' => [['name' => 'first'], ['name' => 'second']]], <add> ['foo' => 'Array', 'foo.*.name' => ['Required','Numeric']]); <add> $this->assertFalse($v->passes()); <add> <add> $v = new Validator($trans, ['foo' => [['name' => 'first', 'votes' => [1, 2]], ['name' => 'second', 'votes' => ['something', 2]]]], <add> ['foo' => 'Array', 'foo.*.name' => ['Required','String'], 'foo.*.votes.*' => ['Required','Integer']]); <add> $this->assertFalse($v->passes()); <ide> } <ide> <ide> public function testValidateEachWithNonIndexedArray()
2
Ruby
Ruby
update tabs only if core formula installed
f88f2b7054ac3ff11a8b0581549776879738e868
<ide><path>Library/Homebrew/cmd/update.rb <ide> def update <ide> install_tap tap_user, tap_repo <ide> # update tap for each Tab <ide> tabs = dir.subdirs.each.map { |d| Tab.for_keg(Keg.new(d)) } <add> next if tabs.first.source["tap"] != "Homebrew/homebrew" <ide> tabs.each { |tab| tab.source["tap"] = "#{tap_user}/homebrew-#{tap_repo}" } <ide> tabs.each(&:write) <ide> end if load_tap_migrations <ide><path>Library/Homebrew/migrator.rb <ide> def from_same_taps? <ide> # newname's tap is the same as tap to which oldname migrated, then we <ide> # can perform migrations and the taps for oldname and newname are the same. <ide> elsif TAP_MIGRATIONS && (rec = TAP_MIGRATIONS[formula.oldname]) \ <del> && rec == formula.tap.sub("homebrew-", "") <add> && rec == formula.tap.sub("homebrew-", "") && old_tap == "Homebrew/homebrew" <ide> fix_tabs <ide> true <ide> elsif formula.tap
2
PHP
PHP
allow serialize in json and xml alias
cbb4f7db90616e5902fb4658afac9e15cb2f0b82
<ide><path>lib/Cake/Test/Case/View/JsonViewTest.php <ide> public function testRenderWithoutViewMultiple() { <ide> $this->assertSame('application/json', $Response->type()); <ide> } <ide> <add>/** <add> * Test render with an array in _serialize and alias <add> * <add> * @return void <add> */ <add> public function testRenderWithoutViewMultipleAndAlias() { <add> $Request = new CakeRequest(); <add> $Response = new CakeResponse(); <add> $Controller = new Controller($Request, $Response); <add> $data = array('original_name' => 'my epic name', 'user' => 'fake', 'list' => array('item1', 'item2')); <add> $Controller->set($data); <add> $Controller->set('_serialize', array('new_name' => 'original_name', 'user')); <add> $View = new JsonView($Controller); <add> $output = $View->render(false); <add> <add> $this->assertSame(json_encode(array('new_name' => $data['original_name'], 'user' => $data['user'])), $output); <add> $this->assertSame('application/json', $Response->type()); <add> } <add> <ide> /** <ide> * testJsonpResponse method <ide> * <ide><path>lib/Cake/Test/Case/View/XmlViewTest.php <ide> public function testRenderWithoutViewMultiple() { <ide> $this->assertSame(Xml::build($expected)->asXML(), $output); <ide> } <ide> <add>/** <add> * Test render with an array in _serialize and alias <add> * <add> * @return void <add> */ <add> public function testRenderWithoutViewMultipleAndAlias() { <add> $Request = new CakeRequest(); <add> $Response = new CakeResponse(); <add> $Controller = new Controller($Request, $Response); <add> $data = array('original_name' => 'my epic name', 'user' => 'fake', 'list' => array('item1', 'item2')); <add> $Controller->set($data); <add> $Controller->set('_serialize', array('new_name' => 'original_name', 'user')); <add> $View = new XmlView($Controller); <add> $this->assertSame('application/xml', $Response->type()); <add> $output = $View->render(false); <add> $expected = array( <add> 'response' => array('new_name' => $data['original_name'], 'user' => $data['user']) <add> ); <add> $this->assertSame(Xml::build($expected)->asXML(), $output); <add> <add> $Controller->set('_rootNode', 'custom_name'); <add> $View = new XmlView($Controller); <add> $output = $View->render(false); <add> $expected = array( <add> 'custom_name' => array('new_name' => $data['original_name'], 'user' => $data['user']) <add> ); <add> $this->assertSame(Xml::build($expected)->asXML(), $output); <add> } <add> <ide> /** <ide> * testRenderWithView method <ide> * <ide><path>lib/Cake/View/JsonView.php <ide> public function render($view = null, $layout = null) { <ide> protected function _serialize($serialize) { <ide> if (is_array($serialize)) { <ide> $data = array(); <del> foreach ($serialize as $key) { <del> $data[$key] = $this->viewVars[$key]; <add> foreach ($serialize as $alias => $key) { <add> if (is_numeric($alias)) { <add> $alias = $key; <add> } <add> $data[$alias] = $this->viewVars[$key]; <ide> } <ide> } else { <ide> $data = isset($this->viewVars[$serialize]) ? $this->viewVars[$serialize] : null; <ide><path>lib/Cake/View/XmlView.php <ide> protected function _serialize($serialize) { <ide> <ide> if (is_array($serialize)) { <ide> $data = array($rootNode => array()); <del> foreach ($serialize as $key) { <del> $data[$rootNode][$key] = $this->viewVars[$key]; <add> foreach ($serialize as $alias => $key) { <add> if (is_numeric($alias)) { <add> $alias = $key; <add> } <add> $data[$rootNode][$alias] = $this->viewVars[$key]; <ide> } <ide> } else { <ide> $data = isset($this->viewVars[$serialize]) ? $this->viewVars[$serialize] : null;
4
Ruby
Ruby
assign the `#alias_name` to each reflection
f6729309a06f40b32e52f8ee8143d1b1da412597
<ide><path>activerecord/lib/active_record/associations/association_scope.rb <ide> def next_chain_scope(scope, table, reflection, connection, assoc_klass, foreign_ <ide> end <ide> <ide> class ReflectionProxy < SimpleDelegator <del> attr_accessor :next <add> attr_accessor :next, :alias_name <ide> <del> def alias_name(name, alias_tracker) <del> @alias ||= begin <del> alias_name = "#{plural_name}_#{name}" <del> alias_tracker.aliased_table_for(table_name, alias_name) <del> end <add> def alias_candidate(name) <add> "#{plural_name}_#{name}" <ide> end <ide> end <ide> <ide> def get_chain(refl, association, tracker) <ide> name = refl.name <ide> runtime_reflection = ActiveRecord::Reflection::RuntimeReflection.new(refl, association) <del> runtime_reflection.alias_name(name, tracker) <add> alias_name = tracker.aliased_table_for(runtime_reflection.table_name, runtime_reflection.alias_candidate(name)) <add> runtime_reflection.alias_name = alias_name <ide> prev = runtime_reflection <ide> refl.chain.drop(1).each { |reflection| <ide> proxy = ReflectionProxy.new(reflection) <del> proxy.alias_name(name, tracker) <add> <add> alias_name = tracker.aliased_table_for(proxy.table_name, proxy.alias_candidate(name)) <add> proxy.alias_name = alias_name <add> <ide> prev.next = proxy <ide> prev = proxy <ide> } <ide> def get_chain(refl, association, tracker) <ide> <ide> def add_constraints(scope, owner, assoc_klass, refl, tracker, chain_head, chain_tail) <ide> owner_reflection = chain_tail <del> table = owner_reflection.alias_name(refl.name, tracker) <add> table = owner_reflection.alias_name <ide> scope = last_chain_scope(scope, table, owner_reflection, owner, tracker, assoc_klass) <ide> <ide> reflection = chain_head <ide> loop do <ide> break unless reflection <del> table = reflection.alias_name(refl.name, tracker) <add> table = reflection.alias_name <ide> <ide> unless reflection == chain_tail <ide> next_reflection = reflection.next <del> foreign_table = next_reflection.alias_name(refl.name, tracker) <add> foreign_table = next_reflection.alias_name <ide> scope = next_chain_scope(scope, table, reflection, tracker, assoc_klass, foreign_table, next_reflection) <ide> end <ide> <ide><path>activerecord/lib/active_record/reflection.rb <ide> def source_type_info <ide> end <ide> <ide> class RuntimeReflection < PolymorphicReflection <del> attr_accessor :next <add> attr_accessor :next, :alias_name <ide> <ide> def initialize(reflection, association) <ide> @reflection = reflection <ide> def source_type_info <ide> @reflection.source_type_info <ide> end <ide> <del> def alias_name(name, alias_tracker) <del> @alias ||= begin <del> alias_name = "#{plural_name}_#{name}_join" <del> table_name = klass.table_name <del> alias_tracker.aliased_table_for(table_name, alias_name) <del> end <add> def alias_candidate(name) <add> "#{plural_name}_#{name}_join" <ide> end <ide> end <ide> end
2
PHP
PHP
fix viewfacade reference
f9165439ba826dab16b177680a14cf21f3ce462c
<ide><path>src/Illuminate/Foundation/Testing/Concerns/InteractsWithViews.php <ide> protected function blade(string $template, array $data = []) <ide> $tempDirectory = sys_get_temp_dir(); <ide> <ide> if (! in_array($tempDirectory, ViewFacade::getFinder()->getPaths())) { <del> View::addLocation(sys_get_temp_dir()); <add> ViewFacade::addLocation(sys_get_temp_dir()); <ide> } <ide> <ide> $tempFile = tempnam($tempDirectory, 'laravel-blade').'.blade.php';
1
Java
Java
fix null pointer exception in logbox
ae03bf88a5386915d36095aac09f49f792760171
<ide><path>ReactAndroid/src/main/java/com/facebook/react/devsupport/LogBoxModule.java <ide> public void show() { <ide> new Runnable() { <ide> @Override <ide> public void run() { <del> if (mLogBoxDialog == null) { <add> if (mLogBoxDialog == null && mReactRootView != null) { <ide> Activity context = getCurrentActivity(); <ide> if (context == null || context.isFinishing()) { <ide> FLog.e(
1
Text
Text
add bullet point on modifying an existing pr
45de313a9edcc7a57b09a2a80be3aa865cf8c12c
<ide><path>CONTRIBUTING.md <ide> # How to contribute to transformers? <ide> <ide> Everyone is welcome to contribute, and we value everybody's contribution. Code <del>is thus not the only way to contribute. Answering questions, helping others, <del>reaching out and improving the documentations are immensely valuable to the <del>community. <add>is thus not the only way to help the community. Answering questions, helping <add>others, reaching out and improving the documentations are immensely valuable to <add>the community. <ide> <ide> It also helps us if you spread the word: reference the library from blog posts <del>on the awesome projects it made possible, shout out on twitter every time it has <add>on the awesome projects it made possible, shout out on Twitter every time it has <ide> helped you, or simply star the repo to say "thank you". <ide> <ide> ## You can contribute in so many ways! <ide> <ide> There are 4 ways you can contribute to transformers: <ide> * Fixing outstanding issues with the existing code; <ide> * Implementing new models; <del>* Contributing to the examples, or to the documentation; <add>* Contributing to the examples or to the documentation; <ide> * Submitting issues related to bugs or desired new features. <ide> <ide> *All are equally valuable to the community.* <ide> feedback. <ide> ### Did you find a bug? <ide> <ide> The transformers are robust and reliable thanks to the users who notify us of <del>the problems they encounter. <add>the problems they encounter. So thank you for reporting an issue. <ide> <del>So thank you for reporting an issue. First, we would really appreciate it if you <del>could **make sure the bug was not already reported** (use the search bar on <del>Github under Issues). <add>First, we would really appreciate it if you could **make sure the bug was not <add>already reported** (use the search bar on Github under Issues). <ide> <ide> Did not find it? :( So we can act quickly on it, please follow these steps: <ide> <ide> * Include your **OS type and version**, the versions of **Python**, **PyTorch** and <ide> **Tensorflow** when applicable; <ide> * A short, self-contained, code snippet that allows us to reproduce the bug in <del> less than 30s. <add> less than 30s; <ide> * Provide the *full* traceback if an exception is raised. <ide> <ide> To get the OS and software versions, execute the following code and copy-paste <ide> import tensorflow; print("Tensorflow", tensorflow.__version__) <ide> <ide> ### Do you want to implement a new model? <ide> <del>Please provide the following: <add>Awesome! Please provide the following information: <ide> <del>* Short description of the model and link to the paper <del>* Link to the implementation if open-source <del>* Link to the model weights if they are available <add>* Short description of the model and link to the paper; <add>* Link to the implementation if it is open-source; <add>* Link to the model weights if they are available. <ide> <del>Let us know if you are willing to contribute so we can best guide you. <add>If you are willing to contribute the model yourself, let us know so we can best <add>guide you. <ide> <ide> ### Do you want a new feature (that is not a model)? <ide> <ide> A world-class feature request addresses the following points: <ide> about it! <ide> * Is it something you worked on and think could benefit the community? <ide> Awesome! Tell us what problem it solved for you. <del>2. Write a *full paragraph* describing the feature. <del>3. Provide a **code snippet** that demonstrates its future use. <del>4. In case this is related to a paper, please provide a link <add>2. Write a *full paragraph* describing the feature; <add>3. Provide a **code snippet** that demonstrates its future use; <add>4. In case this is related to a paper, please attach a link; <ide> 5. Attach any additional information (drawings, screenshots, etc.) you think may help. <ide> <del>If your issue is well-written we're already 80% of the way there by the time you <add>If your issue is well written we're already 80% of the way there by the time you <ide> post it. <ide> <ide> ## Start contributing! (Pull Requests) <ide> <ide> Before writing code, we strongly advise you to search through the exising PRs or <del>issues to make sure that nobody is already working on the same thing. It is <del>always a good idea to open an issue to get some feedback. <add>issues to make sure that nobody is already working on the same thing. If you are <add>unsure, it is always a good idea to open an issue to get some feedback. <ide> <ide> You will need basic `git` proficiency to be able to contribute to <ide> `transformers`. `git` is not the easiest tool to use but it has the greatest <ide> Git](https://git-scm.com/book/en/v2) is a very good reference. <ide> Follow these steps to start contributing: <ide> <ide> 1. Fork the [repository](https://github.com/huggingface/transformers) by <del> clicking on the 'Fork' button. This creates a copy of the code <add> clicking on the 'Fork' button on the repository's page. This creates a copy of the code <ide> under your github user account. <ide> 2. Clone your fork to your local disk, and add the base repository as a remote: <ide> <ide> Follow these steps to start contributing: <ide> <ide> **do not** work on the `master` branch. <ide> <del>4. Set up a development environment by running in a virtual environment: <add>4. Set up a development environment by running the following command in a virtual environment: <ide> <ide> ```bash <ide> $ pip install -r requirements-dev.txt <ide> Follow these steps to start contributing: <ide> 6. Once you are satisfied (**and the checklist below is happy too**), go to the <ide> webpage of your fork on Github. Click on 'Pull request' to send your changes <ide> to the project maintainers for review. <add> <add>7. It's ok if maintainers ask you for changes. It happens to core contributors <add> too! So everyone can see the changes in the Pull request, work in your local <add> branch and push the changes to your fork. They will automatically appear in <add> the pull request. <ide> <ide> <ide> ### Checklist <ide> <ide> 1. The title of your pull request should be a summary of its contribution; <ide> 2. If your pull request adresses an issue, please mention the issue number in <del> the pull request description to make sure they are linked; <add> the pull request description to make sure they are linked (and people <add> consulting the issue know you are working on it); <ide> 3. To indicate a work in progress please prefix the title with `[WIP]`. These <ide> are useful to avoid duplicated work, and to differentiate it from PRs ready <ide> to be merged;
1
PHP
PHP
update uuid pattern to accept the 'nil' uuid
5aa8a458b16125fe53004b2785e51a3515f75b6b
<ide><path>lib/Cake/Test/Case/Utility/ValidationTest.php <ide> public function testUrl() { <ide> } <ide> <ide> public function testUuid() { <add> $this->assertTrue(Validation::uuid('00000000-0000-0000-0000-000000000000')); <ide> $this->assertTrue(Validation::uuid('550e8400-e29b-11d4-a716-446655440000')); <ide> $this->assertFalse(Validation::uuid('BRAP-e29b-11d4-a716-446655440000')); <ide> $this->assertTrue(Validation::uuid('550E8400-e29b-11D4-A716-446655440000')); <ide><path>lib/Cake/Utility/Validation.php <ide> public static function userDefined($check, $object, $method, $args = null) { <ide> * @return boolean Success <ide> */ <ide> public static function uuid($check) { <del> $regex = '/^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[1-5][a-fA-F0-9]{3}-[89aAbB][a-fA-F0-9]{3}-[a-fA-F0-9]{12}$/'; <add> $regex = '/^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[0-5][a-fA-F0-9]{3}-[089aAbB][a-fA-F0-9]{3}-[a-fA-F0-9]{12}$/'; <ide> return self::_check($check, $regex); <ide> } <ide>
2
Mixed
Python
correct allow_null behaviour when required=false
6c0c69ed6546d24cf68edaecd5a8698553bfbe6a
<ide><path>docs/api-guide/fields.md <ide> Setting this to `False` also allows the object attribute or dictionary key to be <ide> <ide> Defaults to `True`. <ide> <del>### `allow_null` <del> <del>Normally an error will be raised if `None` is passed to a serializer field. Set this keyword argument to `True` if `None` should be considered a valid value. <del> <del>Note that setting this argument to `True` will imply a default value of `null` for serialization output, but does not imply a default for input deserialization. <del> <del>Defaults to `False` <del> <ide> ### `default` <ide> <ide> If set, this gives the default value that will be used for the field if no input value is supplied. If not set the default behaviour is to not populate the attribute at all. <ide> When serializing the instance, default will be used if the the object attribute <ide> <ide> Note that setting a `default` value implies that the field is not required. Including both the `default` and `required` keyword arguments is invalid and will raise an error. <ide> <add>### `allow_null` <add> <add>Normally an error will be raised if `None` is passed to a serializer field. Set this keyword argument to `True` if `None` should be considered a valid value. <add> <add>Note that, without an explicit `default`, setting this argument to `True` will imply a `default` value of `null` for serialization output, but does not imply a default for input deserialization. <add> <add>Defaults to `False` <add> <ide> ### `source` <ide> <ide> The name of the attribute that will be used to populate the field. May be a method that only takes a `self` argument, such as `URLField(source='get_absolute_url')`, or may use dotted notation to traverse attributes, such as `EmailField(source='user.email')`. When serializing fields with dotted notation, it may be necessary to provide a `default` value if any object is not present or is empty during attribute traversal. <ide><path>rest_framework/fields.py <ide> def get_attribute(self, instance): <ide> except (KeyError, AttributeError) as exc: <ide> if self.default is not empty: <ide> return self.get_default() <del> if not self.required: <del> raise SkipField() <ide> if self.allow_null: <ide> return None <add> if not self.required: <add> raise SkipField() <ide> msg = ( <ide> 'Got {exc_type} when attempting to get a value for field ' <ide> '`{field}` on serializer `{serializer}`.\nThe serializer ' <ide><path>tests/test_serializer.py <ide> def create(self, validated_data): <ide> serializer.save() <ide> assert serializer.data == {'included': 'abc'} <ide> <del> def test_not_required_output_for_allow_null_field(self): <del> class ExampleSerializer(serializers.Serializer): <del> omitted = serializers.CharField(required=False, allow_null=True) <del> included = serializers.CharField() <del> <del> serializer = ExampleSerializer({'included': 'abc'}) <del> assert 'omitted' not in serializer.data <del> <ide> <ide> class TestDefaultOutput: <ide> def setup(self): <ide> class Serializer(serializers.Serializer): <ide> assert Serializer({'nested': {'a': '3', 'b': {'c': '4'}}}).data == {'nested': {'a': '3', 'c': '4'}} <ide> <ide> def test_default_for_allow_null(self): <del> # allow_null=True should imply default=None <add> """ <add> Without an explicit default, allow_null implies default=None when serializing. #5518 #5708 <add> """ <ide> class Serializer(serializers.Serializer): <ide> foo = serializers.CharField() <ide> bar = serializers.CharField(source='foo.bar', allow_null=True) <add> optional = serializers.CharField(required=False, allow_null=True) <ide> <del> assert Serializer({'foo': None}).data == {'foo': None, 'bar': None} <add> # allow_null=True should imply default=None when serialising: <add> assert Serializer({'foo': None}).data == {'foo': None, 'bar': None, 'optional': None, } <ide> <ide> <ide> class TestCacheSerializerData:
3
Ruby
Ruby
fix install order
a7cf6c1ff038a14b09d433e969c4e4a186d7b6f1
<ide><path>Library/Homebrew/cask/lib/hbc/artifact/abstract_artifact.rb <ide> def <=>(other) <ide> Vst3Plugin, <ide> ScreenSaver, <ide> ], <del> Binary, <ide> Pkg, <add> Binary, <ide> PostflightBlock, <ide> Zap, <ide> ].each_with_index.flat_map { |classes, i| [*classes].map { |c| [c, i] } }.to_h
1
Javascript
Javascript
ignore ssr mounts
b5850fe3044b20f00b9d5482b56989a2ad259955
<ide><path>src/backend/legacy/renderer.js <ide> export function attach( <ide> // React 15 <ide> oldReconcilerMethods = decorateMany(renderer.Reconciler, { <ide> mountComponent(fn, args) { <del> const [internalInstance, , , hostContainerInfo] = args; <add> const internalInstance = args[0]; <add> const hostContainerInfo = args[3]; <ide> if (getElementType(internalInstance) === ElementTypeOtherOrUnknown) { <ide> return fn.apply(this, args); <ide> } <add> if (hostContainerInfo._topLevelWrapper === undefined) { <add> // SSR <add> return fn.apply(this, args); <add> } <ide> <ide> const id = getID(internalInstance); <del> <ide> // Push the operation. <ide> const parentID = <ide> parentIDStack.length > 0 <ide> export function attach( <ide> } <ide> }, <ide> performUpdateIfNecessary(fn, args) { <del> const [internalInstance] = args; <add> const internalInstance = args[0]; <ide> if (getElementType(internalInstance) === ElementTypeOtherOrUnknown) { <ide> return fn.apply(this, args); <ide> } <ide> export function attach( <ide> } <ide> }, <ide> receiveComponent(fn, args) { <del> const [internalInstance] = args; <add> const internalInstance = args[0]; <ide> if (getElementType(internalInstance) === ElementTypeOtherOrUnknown) { <ide> return fn.apply(this, args); <ide> } <ide> export function attach( <ide> } <ide> }, <ide> unmountComponent(fn, args) { <del> const [internalInstance] = args; <add> const internalInstance = args[0]; <ide> if (getElementType(internalInstance) === ElementTypeOtherOrUnknown) { <ide> return fn.apply(this, args); <ide> }
1
Text
Text
add cdnjs to readme
e03161ae2fa27308df9a200c83049b73ecfcb9c9
<ide><path>README.md <ide> var map = Immutable.Map({a:1, b:2, c:3}); <ide> <ide> ### Browser <ide> <del>To use `immutable` from a browser, download [dist/Immutable.min.js](./dist/Immutable.min.js) or use a CDN such as [jsDelivr](http://cdn.jsdelivr.net/immutable.js/latest/Immutable.min.js). <add>To use `immutable` from a browser, download [dist/Immutable.min.js](./dist/Immutable.min.js) <add>or use a CDN hosted version such as [CDNJS](//cdnjs.cloudflare.com/ajax/libs/immutable/2.5.1/immutable.min.js) <add>or [jsDelivr](//cdn.jsdelivr.net/immutable.js/2.5.1/Immutable.min.js). <ide> <ide> Then, add it as a script tag to your page: <ide>
1
Python
Python
add related_query_name to foreignkey/m2m. refs
99b467f272da91b8894dc90d793d8d2c40b78d8c
<ide><path>django/db/models/fields/related.py <ide> def related_query_name(self): <ide> # related object in a table-spanning query. It uses the lower-cased <ide> # object_name by default, but this can be overridden with the <ide> # "related_name" option. <del> return self.rel.related_name or self.opts.model_name <add> return self.rel.related_query_name or self.rel.related_name or self.opts.model_name <ide> <ide> <ide> class RenameRelatedObjectDescriptorMethods(RenameMethodsBase): <ide> def __set__(self, instance, value): <ide> <ide> class ForeignObjectRel(object): <ide> def __init__(self, field, to, related_name=None, limit_choices_to=None, <del> parent_link=False, on_delete=None): <add> parent_link=False, on_delete=None, related_query_name=None): <ide> try: <ide> to._meta <ide> except AttributeError: # to._meta doesn't exist, so it must be RECURSIVE_RELATIONSHIP_CONSTANT <ide> def __init__(self, field, to, related_name=None, limit_choices_to=None, <ide> self.field = field <ide> self.to = to <ide> self.related_name = related_name <add> self.related_query_name = related_query_name <ide> self.limit_choices_to = {} if limit_choices_to is None else limit_choices_to <ide> self.multiple = True <ide> self.parent_link = parent_link <ide> def set_field_name(self): <ide> <ide> class ManyToOneRel(ForeignObjectRel): <ide> def __init__(self, field, to, field_name, related_name=None, limit_choices_to=None, <del> parent_link=False, on_delete=None): <add> parent_link=False, on_delete=None, related_query_name=None): <ide> super(ManyToOneRel, self).__init__( <ide> field, to, related_name=related_name, limit_choices_to=limit_choices_to, <del> parent_link=parent_link, on_delete=on_delete) <add> parent_link=parent_link, on_delete=on_delete, related_query_name=related_query_name) <ide> self.field_name = field_name <ide> <ide> def get_related_field(self): <ide> def set_field_name(self): <ide> <ide> class OneToOneRel(ManyToOneRel): <ide> def __init__(self, field, to, field_name, related_name=None, limit_choices_to=None, <del> parent_link=False, on_delete=None): <add> parent_link=False, on_delete=None, related_query_name=None): <ide> super(OneToOneRel, self).__init__(field, to, field_name, <ide> related_name=related_name, limit_choices_to=limit_choices_to, <del> parent_link=parent_link, on_delete=on_delete <add> parent_link=parent_link, on_delete=on_delete, related_query_name=related_query_name, <ide> ) <ide> self.multiple = False <ide> <ide> <ide> class ManyToManyRel(object): <ide> def __init__(self, to, related_name=None, limit_choices_to=None, <del> symmetrical=True, through=None, db_constraint=True): <add> symmetrical=True, through=None, db_constraint=True, related_query_name=None): <ide> if through and not db_constraint: <ide> raise ValueError("Can't supply a through model and db_constraint=False") <ide> self.to = to <ide> self.related_name = related_name <add> self.related_query_name = related_query_name <ide> if limit_choices_to is None: <ide> limit_choices_to = {} <ide> self.limit_choices_to = limit_choices_to <ide> def __init__(self, to, from_fields, to_fields, **kwargs): <ide> kwargs['rel'] = ForeignObjectRel( <ide> self, to, <ide> related_name=kwargs.pop('related_name', None), <add> related_query_name=kwargs.pop('related_query_name', None), <ide> limit_choices_to=kwargs.pop('limit_choices_to', None), <ide> parent_link=kwargs.pop('parent_link', False), <ide> on_delete=kwargs.pop('on_delete', CASCADE), <ide> def __init__(self, to, to_field=None, rel_class=ManyToOneRel, <ide> kwargs['rel'] = rel_class( <ide> self, to, to_field, <ide> related_name=kwargs.pop('related_name', None), <add> related_query_name=kwargs.pop('related_query_name', None), <ide> limit_choices_to=kwargs.pop('limit_choices_to', None), <ide> parent_link=kwargs.pop('parent_link', False), <ide> on_delete=kwargs.pop('on_delete', CASCADE), <ide> def __init__(self, to, db_constraint=True, **kwargs): <ide> kwargs['verbose_name'] = kwargs.get('verbose_name', None) <ide> kwargs['rel'] = ManyToManyRel(to, <ide> related_name=kwargs.pop('related_name', None), <add> related_query_name=kwargs.pop('related_query_name', None), <ide> limit_choices_to=kwargs.pop('limit_choices_to', None), <ide> symmetrical=kwargs.pop('symmetrical', to == RECURSIVE_RELATIONSHIP_CONSTANT), <ide> through=kwargs.pop('through', None), <ide><path>tests/foreign_object/models.py <ide> class ArticleTranslation(models.Model): <ide> class Meta: <ide> unique_together = ('article', 'lang') <ide> ordering = ('active_translation__title',) <add> <add>class ArticleTag(models.Model): <add> article = models.ForeignKey(Article, related_name="tags", related_query_name="tag") <add> name = models.CharField(max_length=255) <add> <add>class ArticleIdea(models.Model): <add> articles = models.ManyToManyField(Article, related_name="ideas", related_query_name="idea_things") <add> name = models.CharField(max_length=255) <ide><path>tests/foreign_object/tests.py <ide> import datetime <ide> from operator import attrgetter <ide> <del>from .models import Country, Person, Group, Membership, Friendship, Article, ArticleTranslation <add>from .models import Country, Person, Group, Membership, Friendship, Article, ArticleTranslation, ArticleTag, ArticleIdea <ide> from django.test import TestCase <ide> from django.utils.translation import activate <add>from django.core.exceptions import FieldError <ide> from django import forms <ide> <ide> class MultiColumnFKTests(TestCase): <ide> def test_foreign_key_raises_informative_does_not_exist(self): <ide> with self.assertRaisesMessage(Article.DoesNotExist, 'ArticleTranslation has no article'): <ide> referrer.article <ide> <add> def test_foreign_key_related_query_name(self): <add> a1 = Article.objects.create(pub_date=datetime.date.today()) <add> ArticleTag.objects.create(article=a1, name="foo") <add> self.assertEqual(Article.objects.filter(tag__name="foo").count(), 1) <add> self.assertEqual(Article.objects.filter(tag__name="bar").count(), 0) <add> with self.assertRaises(FieldError): <add> Article.objects.filter(tags__name="foo") <add> <add> def test_many_to_many_related_query_name(self): <add> a1 = Article.objects.create(pub_date=datetime.date.today()) <add> i1 = ArticleIdea.objects.create(name="idea1") <add> a1.ideas.add(i1) <add> self.assertEqual(Article.objects.filter(idea_things__name="idea1").count(), 1) <add> self.assertEqual(Article.objects.filter(idea_things__name="idea2").count(), 0) <add> with self.assertRaises(FieldError): <add> Article.objects.filter(ideas__name="idea1") <add> <add> <ide> class FormsTests(TestCase): <ide> # ForeignObjects should not have any form fields, currently the user needs <ide> # to manually deal with the foreignobject relation.
3
Javascript
Javascript
reuse redux store in single test
8baab3895d9ec8a7c5da8ee44dbbb55d9a5b07d0
<ide><path>client/src/components/Map/components/SuperBlock.test.js <ide> import { SuperBlock } from './SuperBlock'; <ide> import mockChallengeNodes from '../../../__mocks__/challenge-nodes'; <ide> import mockIntroNodes from '../../../__mocks__/intro-nodes'; <ide> <del>function renderWithRedux(ui) { <del> return render(<Provider store={createStore()}>{ui}</Provider>); <add>function renderWithRedux(ui, store) { <add> return render(<Provider store={store || createStore()}>{ui}</Provider>); <ide> } <ide> <ide> test('<SuperBlock /> not expanded snapshot', () => { <ide> test('<SuperBlock should handle toggle clicks correctly', () => { <ide> toggleSuperBlock: toggleSpy <ide> }; <ide> <del> const { container, rerender } = renderWithRedux(<SuperBlock {...props} />); <add> const store = createStore(); <add> const { container, rerender } = renderWithRedux( <add> <SuperBlock {...props} />, <add> store <add> ); <ide> <ide> expect(toggleSpy).not.toHaveBeenCalled(); <ide> expect(container.querySelector('.map-title h4')).toHaveTextContent( <ide> test('<SuperBlock should handle toggle clicks correctly', () => { <ide> expect(toggleSpy).toHaveBeenCalledWith('Super Block One'); <ide> <ide> rerender( <del> <Provider store={createStore()}> <add> <Provider store={store}> <ide> <SuperBlock {...props} isExpanded={true} /> <ide> </Provider> <ide> );
1
Text
Text
remove console style from code blocks
5427d90fa48398684948067530cd8083f785c248
<ide><path>docs/api-guide/testing.md <ide> Extends [Django's existing `RequestFactory` class][requestfactory]. <ide> <ide> The `APIRequestFactory` class supports an almost identical API to Django's standard `RequestFactory` class. This means the that standard `.get()`, `.post()`, `.put()`, `.patch()`, `.delete()`, `.head()` and `.options()` methods are all available. <ide> <del>### Using the format arguments <add>#### Using the format arguments <ide> <ide> Methods which create a request body, such as `post`, `put` and `patch`, include a `format` argument, which make it easy to generate requests using a content type other than multipart form data. For example: <ide> <ide> If you need to explictly encode the request body, you can do so by explicitly se <ide> <ide> request = factory.post('/notes/', json.dumps({'title': 'new idea'}), content_type='application/json') <ide> <del>### PUT and PATCH with form data <add>#### PUT and PATCH with form data <ide> <ide> One difference worth noting between Django's `RequestFactory` and REST framework's `APIRequestFactory` is that multipart form data will be encoded for methods other than just `.post()`. <ide> <ide> To support a wider set of request formats, or change the default format, [see th <ide> <ide> ## Authenticating <ide> <del>### .login(**kwargs) <add>#### .login(**kwargs) <ide> <ide> The `login` method functions exactly as it does with Django's regular `Client` class. This allows you to authenticate requests against any views which include `SessionAuthentication`. <ide> <ide> # Make all requests in the context of a logged in session. <del> >>> client = APIClient() <del> >>> client.login(username='lauren', password='secret') <add> client = APIClient() <add> client.login(username='lauren', password='secret') <ide> <ide> To logout, call the `logout` method as usual. <ide> <ide> # Log out <del> >>> client.logout() <add> client.logout() <ide> <ide> The `login` method is appropriate for testing APIs that use session authentication, for example web sites which include AJAX interaction with the API. <ide> <del>### .credentials(**kwargs) <add>#### .credentials(**kwargs) <ide> <ide> The `credentials` method can be used to set headers that will then be included on all subsequent requests by the test client. <ide> <ide> # Include an appropriate `Authorization:` header on all requests. <del> >>> token = Token.objects.get(username='lauren') <del> >>> client = APIClient() <del> >>> client.credentials(HTTP_AUTHORIZATION='Token ' + token.key) <add> token = Token.objects.get(username='lauren') <add> client = APIClient() <add> client.credentials(HTTP_AUTHORIZATION='Token ' + token.key) <ide> <ide> Note that calling `credentials` a second time overwrites any existing credentials. You can unset any existing credentials by calling the method with no arguments. <ide> <ide> # Stop including any credentials <del> >>> client.credentials() <add> client.credentials() <ide> <ide> The `credentials` method is appropriate for testing APIs that require authentication headers, such as basic authentication, OAuth1a and OAuth2 authentication, and simple token authentication schemes. <ide> <del>### .force_authenticate(user=None, token=None) <add>#### .force_authenticate(user=None, token=None) <ide> <ide> Sometimes you may want to bypass authentication, and simple force all requests by the test client to be automatically treated as authenticated. <ide> <ide> This can be a useful shortcut if you're testing the API but don't want to have to construct valid authentication credentials in order to make test requests. <ide> <del> >>> user = User.objects.get(username='lauren') <del> >>> client = APIClient() <del> >>> client.force_authenticate(user=user) <add> user = User.objects.get(username='lauren') <add> client = APIClient() <add> client.force_authenticate(user=user) <ide> <ide> To unauthenticate subsequent requests, call `force_authenticate` setting the user and/or token to `None`. <ide> <del> >>> client.force_authenticate(user=None) <add> client.force_authenticate(user=None) <ide> <ide> ## CSRF validation <ide>
1
Python
Python
support variable batch size in detection generator
71c7b7f92dfb5853418ef8daa7b83e2b3f3b6d68
<ide><path>official/vision/beta/modeling/layers/detection_generator.py <ide> def _select_top_k_scores(scores_in: tf.Tensor, pre_nms_num_detections: int): <ide> `[batch_size, pre_nms_num_detections, num_classes]`. <ide> """ <ide> batch_size, num_anchors, num_class = scores_in.get_shape().as_list() <add> if batch_size is None: <add> batch_size = tf.shape(scores_in)[0] <ide> scores_trans = tf.transpose(scores_in, perm=[0, 2, 1]) <ide> scores_trans = tf.reshape(scores_trans, [-1, num_anchors]) <ide> <ide> def _generate_detections_v2(boxes: tf.Tensor, <ide> nmsed_scores = [] <ide> valid_detections = [] <ide> batch_size, _, num_classes_for_box, _ = boxes.get_shape().as_list() <add> if batch_size is None: <add> batch_size = tf.shape(boxes)[0] <ide> _, total_anchors, num_classes = scores.get_shape().as_list() <ide> # Selects top pre_nms_num scores and indices before NMS. <ide> scores, indices = _select_top_k_scores( <ide> def __call__(self, raw_boxes: tf.Tensor, raw_scores: tf.Tensor, <ide> <ide> # Removes the background class. <ide> box_scores_shape = tf.shape(box_scores) <add> box_scores_shape_list = box_scores.get_shape().as_list() <ide> batch_size = box_scores_shape[0] <del> num_locations = box_scores_shape[1] <del> num_classes = box_scores_shape[-1] <add> num_locations = box_scores_shape_list[1] <add> num_classes = box_scores_shape_list[-1] <ide> num_detections = num_locations * (num_classes - 1) <ide> <ide> box_scores = tf.slice(box_scores, [0, 0, 1], [-1, -1, -1]) <del> raw_boxes = tf.reshape( <del> raw_boxes, <del> tf.stack([batch_size, num_locations, num_classes, 4], axis=-1)) <del> raw_boxes = tf.slice( <del> raw_boxes, [0, 0, 1, 0], [-1, -1, -1, -1]) <add> raw_boxes = tf.reshape(raw_boxes, <add> [batch_size, num_locations, num_classes, 4]) <add> raw_boxes = tf.slice(raw_boxes, [0, 0, 1, 0], [-1, -1, -1, -1]) <ide> anchor_boxes = tf.tile( <ide> tf.expand_dims(anchor_boxes, axis=2), [1, 1, num_classes - 1, 1]) <del> raw_boxes = tf.reshape( <del> raw_boxes, <del> tf.stack([batch_size, num_detections, 4], axis=-1)) <del> anchor_boxes = tf.reshape( <del> anchor_boxes, <del> tf.stack([batch_size, num_detections, 4], axis=-1)) <add> raw_boxes = tf.reshape(raw_boxes, [batch_size, num_detections, 4]) <add> anchor_boxes = tf.reshape(anchor_boxes, [batch_size, num_detections, 4]) <ide> <ide> # Box decoding. <ide> decoded_boxes = box_ops.decode_boxes( <ide> def __call__(self, raw_boxes: tf.Tensor, raw_scores: tf.Tensor, <ide> decoded_boxes = box_ops.clip_boxes( <ide> decoded_boxes, tf.expand_dims(image_shape, axis=1)) <ide> <del> decoded_boxes = tf.reshape( <del> decoded_boxes, <del> tf.stack([batch_size, num_locations, num_classes - 1, 4], axis=-1)) <add> decoded_boxes = tf.reshape(decoded_boxes, <add> [batch_size, num_locations, num_classes - 1, 4]) <ide> <ide> if not self._config_dict['apply_nms']: <ide> return {
1
Python
Python
add spacy.en.lemmatizer to setup.py
aa8ff9257f5cad847b0a09bf8fe3d9c2bc7b17e3
<ide><path>setup.py <ide> 'spacy.sv', <ide> 'spacy.fi', <ide> 'spacy.bn', <add> 'spacy.en.lemmatizer', <ide> 'spacy.language_data', <ide> 'spacy.serialize', <ide> 'spacy.syntax',
1
Go
Go
fix display on test
b36dd3f9ccc61e42024cf1f2799c73f0efc77c75
<ide><path>utils/streamformatter.go <ide> func (sf *StreamFormatter) FormatProgress(id, action string, progress *JSONProgr <ide> } <ide> return b <ide> } <del> return []byte(action + " " + progress.String() + "\r") <add> endl := "\r" <add> if progress.String() == "" { <add> endl += "\n" <add> } <add> return []byte(action + " " + progress.String() + endl) <ide> } <ide> <ide> func (sf *StreamFormatter) Used() bool {
1
Javascript
Javascript
remove bad advice
26805fb968858b7d40f4d24c81f8e2b75ddc15f8
<ide><path>packages/container/lib/registry.js <ide> Registry.prototype = { <ide> var fullNameType = fullName.split(':')[0]; <ide> if (fullNameType === type) { <ide> throw new Error('Cannot inject a `' + fullName + <del> '` on other ' + type + <del> '(s). Register the `' + fullName + <del> '` as a different type and perform the typeInjection.'); <add> '` on other ' + type + '(s).'); <ide> } <ide> <ide> var injections = this._typeInjections[type] || <ide><path>packages/container/tests/registry_test.js <ide> QUnit.test("Throw exception when trying to inject `type:thing` on all type(s)", <ide> <ide> throws(function() { <ide> registry.typeInjection('controller', 'injected', 'controller:post'); <del> }, 'Cannot inject a `controller:post` on other controller(s). Register the `controller:post` as a different type and perform the typeInjection.'); <add> }, 'Cannot inject a `controller:post` on other controller(s).'); <ide> }); <ide> <ide> QUnit.test("The registry can take a hook to resolve factories lazily", function() {
2
Python
Python
create tensors on device
f82653874b67de5085971517849899e21bdd7c4b
<ide><path>src/transformers/models/t5/modeling_t5.py <ide> def _relative_position_bucket(relative_position, bidirectional=True, num_buckets <ide> <ide> def compute_bias(self, query_length, key_length): <ide> """Compute binned relative position bias""" <del> context_position = torch.arange(query_length, dtype=torch.long)[:, None] <del> memory_position = torch.arange(key_length, dtype=torch.long)[None, :] <add> context_position = torch.arange( <add> query_length, dtype=torch.long, device=self.relative_attention_bias.weight.device <add> )[:, None] <add> memory_position = torch.arange( <add> key_length, dtype=torch.long, device=self.relative_attention_bias.weight.device <add> )[None, :] <ide> relative_position = memory_position - context_position # shape (query_length, key_length) <ide> relative_position_bucket = self._relative_position_bucket( <ide> relative_position, # shape (query_length, key_length) <ide> bidirectional=(not self.is_decoder), <ide> num_buckets=self.relative_attention_num_buckets, <ide> ) <del> relative_position_bucket = relative_position_bucket.to(self.relative_attention_bias.weight.device) <ide> values = self.relative_attention_bias(relative_position_bucket) # shape (query_length, key_length, num_heads) <ide> values = values.permute([2, 0, 1]).unsqueeze(0) # shape (1, num_heads, query_length, key_length) <ide> return values
1
Text
Text
fix errors in config
25db82371eef40f54e1bd175ef72c479d368a798
<ide><path>docs/extend/config.md <ide> Config provides the base accessible fields for working with V0 plugin format <ide> <ide> - **`capabilities`** *string array* <ide> <del> capabilities of the plugin (*Linux only*), see list [`here`](https://github.com/opencontainers/runc/blob/master/libcontainer/SPEC.md#security) <add> capabilities of the plugin (*Linux only*), see list [`here`](https://github.com/opencontainers/runc/blob/master/libcontainer/SPEC.md#security) <ide> <ide> - **`allowAllDevices`** *boolean* <ide> <del> If `/dev` is bind mounted from the host, and allowAllDevices is set to true, the plugin will have `rwm` access to all devices on the host. <add> If `/dev` is bind mounted from the host, and allowAllDevices is set to true, the plugin will have `rwm` access to all devices on the host. <ide> <ide> - **`devices`** *PluginDevice array* <ide> <del> device of the plugin, (*Linux only*), struct consisting of the following fields, see [`DEVICES`](https://github.com/opencontainers/runtime-spec/blob/master/config-linux.md#devices) <add> device of the plugin, (*Linux only*), struct consisting of the following fields, see [`DEVICES`](https://github.com/opencontainers/runtime-spec/blob/master/config-linux.md#devices) <ide> <del> - **`name`** *string* <add> - **`name`** *string* <ide> <del> name of the device. <add> name of the device. <ide> <del> - **`description`** *string* <add> - **`description`** *string* <ide> <del> description of the device. <add> description of the device. <ide> <del> - **`path`** *string* <add> - **`path`** *string* <ide> <del> path of the device. <add> path of the device. <ide> <ide> ## Example Config <ide>
1
Python
Python
release version 2.0.0rc1
7df5db7b0c78b0588f82f2148b51461f94320b90
<ide><path>src/flask/__init__.py <ide> from .templating import render_template <ide> from .templating import render_template_string <ide> <del>__version__ = "2.0.0.dev" <add>__version__ = "2.0.0rc1"
1
Javascript
Javascript
reduce internal usage of public require of util
c97851dcd8c5e96a3601df52edd456922399a80b
<ide><path>lib/internal/js_stream_socket.js <ide> 'use strict'; <ide> <ide> const assert = require('internal/assert'); <del>const util = require('util'); <ide> const { Socket } = require('net'); <ide> const { JSStream } = internalBinding('js_stream'); <ide> const uv = internalBinding('uv'); <del>const debug = util.debuglog('stream_socket'); <add>const debug = require('internal/util/debuglog').debuglog('stream_socket'); <ide> const { owner_symbol } = require('internal/async_hooks').symbols; <ide> const { ERR_STREAM_WRAP } = require('internal/errors').codes; <ide> <ide><path>lib/internal/streams/buffer_list.js <ide> 'use strict'; <ide> <ide> const { Buffer } = require('buffer'); <del>const { inspect } = require('util'); <add>const { inspect } = require('internal/util/inspect'); <ide> <ide> function copyBuffer(src, target, offset) { <ide> Buffer.prototype.copy.call(src, target, offset); <ide><path>lib/internal/streams/lazy_transform.js <ide> 'use strict'; <ide> <ide> const stream = require('stream'); <del>const util = require('util'); <ide> <ide> const { <ide> getDefaultEncoding <ide> function LazyTransform(options) { <ide> this.writable = true; <ide> this.readable = true; <ide> } <del>util.inherits(LazyTransform, stream.Transform); <add>Object.setPrototypeOf(LazyTransform.prototype, stream.Transform.prototype); <add>Object.setPrototypeOf(LazyTransform, stream.Transform); <ide> <ide> function makeGetter(name) { <ide> return function() { <ide><path>lib/stream.js <ide> Stream.Stream = Stream; <ide> <ide> // Internal utilities <ide> try { <del> const types = require('util').types; <add> const types = require('internal/util/types'); <ide> if (types && typeof types.isUint8Array === 'function') { <ide> Stream._isUint8Array = types.isUint8Array; <ide> } else {
4
Go
Go
hide the mutex in formatter.containerstats
929a77b814dfe9ab7a11bffc2d16eebd27bd903a
<ide><path>cli/command/container/stats.go <ide> func runStats(dockerCli *command.DockerCli, opts *statsOptions) error { <ide> var errs []string <ide> cStats.mu.Lock() <ide> for _, c := range cStats.cs { <del> c.Mu.Lock() <del> if c.Err != nil { <del> errs = append(errs, fmt.Sprintf("%s: %v", c.Name, c.Err)) <add> cErr := c.GetError() <add> if cErr != nil { <add> errs = append(errs, fmt.Sprintf("%s: %v", c.Name, cErr)) <ide> } <del> c.Mu.Unlock() <ide> } <ide> cStats.mu.Unlock() <ide> if len(errs) > 0 { <ide> func runStats(dockerCli *command.DockerCli, opts *statsOptions) error { <ide> Format: formatter.NewStatsFormat(f, daemonOSType), <ide> } <ide> <del> cleanHeader := func() { <add> cleanScreen := func() { <ide> if !opts.noStream { <ide> fmt.Fprint(dockerCli.Out(), "\033[2J") <ide> fmt.Fprint(dockerCli.Out(), "\033[H") <ide> func runStats(dockerCli *command.DockerCli, opts *statsOptions) error { <ide> <ide> var err error <ide> for range time.Tick(500 * time.Millisecond) { <del> cleanHeader() <del> cStats.mu.RLock() <del> csLen := len(cStats.cs) <del> if err = formatter.ContainerStatsWrite(statsCtx, cStats.cs); err != nil { <add> cleanScreen() <add> ccstats := []formatter.StatsEntry{} <add> cStats.mu.Lock() <add> for _, c := range cStats.cs { <add> ccstats = append(ccstats, c.GetStatistics()) <add> } <add> cStats.mu.Unlock() <add> if err = formatter.ContainerStatsWrite(statsCtx, ccstats); err != nil { <ide> break <ide> } <del> cStats.mu.RUnlock() <del> if csLen == 0 && !showAll { <add> if len(cStats.cs) == 0 && !showAll { <ide> break <ide> } <ide> if opts.noStream { <ide><path>cli/command/container/stats_helpers.go <ide> import ( <ide> <ide> type stats struct { <ide> ostype string <del> mu sync.RWMutex <add> mu sync.Mutex <ide> cs []*formatter.ContainerStats <ide> } <ide> <ide> func collect(s *formatter.ContainerStats, ctx context.Context, cli client.APICli <ide> <ide> response, err := cli.ContainerStats(ctx, s.Name, streamStats) <ide> if err != nil { <del> s.Mu.Lock() <del> s.Err = err <del> s.Mu.Unlock() <add> s.SetError(err) <ide> return <ide> } <ide> defer response.Body.Close() <ide> func collect(s *formatter.ContainerStats, ctx context.Context, cli client.APICli <ide> cpuPercent = 0.0 <ide> blkRead, blkWrite uint64 // Only used on Linux <ide> mem = 0.0 <add> memLimit = 0.0 <add> memPerc = 0.0 <add> pidsStatsCurrent uint64 <ide> ) <ide> <ide> if err := dec.Decode(&v); err != nil { <ide> func collect(s *formatter.ContainerStats, ctx context.Context, cli client.APICli <ide> cpuPercent = calculateCPUPercentUnix(previousCPU, previousSystem, v) <ide> blkRead, blkWrite = calculateBlockIO(v.BlkioStats) <ide> mem = float64(v.MemoryStats.Usage) <del> <add> memLimit = float64(v.MemoryStats.Limit) <add> memPerc = memPercent <add> pidsStatsCurrent = v.PidsStats.Current <ide> } else { <ide> cpuPercent = calculateCPUPercentWindows(v) <ide> blkRead = v.StorageStats.ReadSizeBytes <ide> blkWrite = v.StorageStats.WriteSizeBytes <ide> mem = float64(v.MemoryStats.PrivateWorkingSet) <ide> } <del> <del> s.Mu.Lock() <del> s.CPUPercentage = cpuPercent <del> s.Memory = mem <del> s.NetworkRx, s.NetworkTx = calculateNetwork(v.Networks) <del> s.BlockRead = float64(blkRead) <del> s.BlockWrite = float64(blkWrite) <del> if daemonOSType != "windows" { <del> s.MemoryLimit = float64(v.MemoryStats.Limit) <del> s.MemoryPercentage = memPercent <del> s.PidsCurrent = v.PidsStats.Current <del> } <del> s.Mu.Unlock() <add> netRx, netTx := calculateNetwork(v.Networks) <add> s.SetStatistics(formatter.StatsEntry{ <add> CPUPercentage: cpuPercent, <add> Memory: mem, <add> MemoryPercentage: memPerc, <add> MemoryLimit: memLimit, <add> NetworkRx: netRx, <add> NetworkTx: netTx, <add> BlockRead: float64(blkRead), <add> BlockWrite: float64(blkWrite), <add> PidsCurrent: pidsStatsCurrent, <add> }) <ide> u <- nil <ide> if !streamStats { <ide> return <ide> func collect(s *formatter.ContainerStats, ctx context.Context, cli client.APICli <ide> case <-time.After(2 * time.Second): <ide> // zero out the values if we have not received an update within <ide> // the specified duration. <del> s.Mu.Lock() <del> s.CPUPercentage = 0 <del> s.Memory = 0 <del> s.MemoryPercentage = 0 <del> s.MemoryLimit = 0 <del> s.NetworkRx = 0 <del> s.NetworkTx = 0 <del> s.BlockRead = 0 <del> s.BlockWrite = 0 <del> s.PidsCurrent = 0 <del> s.Err = errors.New("timeout waiting for stats") <del> s.Mu.Unlock() <add> s.SetErrorAndReset(errors.New("timeout waiting for stats")) <ide> // if this is the first stat you get, release WaitGroup <ide> if !getFirst { <ide> getFirst = true <ide> waitFirst.Done() <ide> } <ide> case err := <-u: <ide> if err != nil { <del> s.Mu.Lock() <del> s.Err = err <del> s.Mu.Unlock() <add> s.SetError(err) <ide> continue <ide> } <del> s.Err = nil <add> s.SetError(nil) <ide> // if this is the first stat you get, release WaitGroup <ide> if !getFirst { <ide> getFirst = true <ide><path>cli/command/formatter/stats.go <ide> import ( <ide> "fmt" <ide> "sync" <ide> <del> "github.com/docker/go-units" <add> units "src/github.com/docker/go-units" <ide> ) <ide> <ide> const ( <del> defaultStatsTableFormat = "table {{.Container}}\t{{.CPUPrec}}\t{{.MemUsage}}\t{{.MemPrec}}\t{{.NetIO}}\t{{.BlockIO}}\t{{.PIDs}}" <del> winDefaultStatsTableFormat = "table {{.Container}}\t{{.CPUPrec}}\t{{{.MemUsage}}\t{.NetIO}}\t{{.BlockIO}}" <add> winOSType = "windows" <add> defaultStatsTableFormat = "table {{.Container}}\t{{.CPUPerc}}\t{{.MemUsage}}\t{{.MemPerc}}\t{{.NetIO}}\t{{.BlockIO}}\t{{.PIDs}}" <add> winDefaultStatsTableFormat = "table {{.Container}}\t{{.CPUPerc}}\t{{{.MemUsage}}\t{.NetIO}}\t{{.BlockIO}}" <ide> emptyStatsTableFormat = "Waiting for statistics..." <ide> <ide> containerHeader = "CONTAINER" <del> cpuPrecHeader = "CPU %" <add> cpuPercHeader = "CPU %" <ide> netIOHeader = "NET I/O" <ide> blockIOHeader = "BLOCK I/O" <del> winMemPrecHeader = "PRIV WORKING SET" // Used only on Window <del> memPrecHeader = "MEM %" // Used only on Linux <add> winMemPercHeader = "PRIV WORKING SET" // Used only on Window <add> memPercHeader = "MEM %" // Used only on Linux <ide> memUseHeader = "MEM USAGE / LIMIT" // Used only on Linux <ide> pidsHeader = "PIDS" // Used only on Linux <ide> ) <ide> <del>// ContainerStatsAttrs represents the statistics data collected from a container. <del>type ContainerStatsAttrs struct { <del> Windows bool <add>// StatsEntry represents represents the statistics data collected from a container <add>type StatsEntry struct { <ide> Name string <ide> CPUPercentage float64 <ide> Memory float64 // On Windows this is the private working set <ide> type ContainerStatsAttrs struct { <ide> BlockRead float64 <ide> BlockWrite float64 <ide> PidsCurrent uint64 // Not used on Windows <add> IsInvalid bool <add> OSType string <ide> } <ide> <del>// ContainerStats represents the containers statistics data. <add>// ContainerStats represents an entity to store containers statistics synchronously <ide> type ContainerStats struct { <del> Mu sync.RWMutex <del> ContainerStatsAttrs <del> Err error <add> mutex sync.Mutex <add> StatsEntry <add> err error <add>} <add> <add>// GetError returns the container statistics error. <add>// This is used to determine whether the statistics are valid or not <add>func (cs *ContainerStats) GetError() error { <add> cs.mutex.Lock() <add> defer cs.mutex.Unlock() <add> return cs.err <add>} <add> <add>// SetErrorAndReset zeroes all the container statistics and store the error. <add>// It is used when receiving time out error during statistics collecting to reduce lock overhead <add>func (cs *ContainerStats) SetErrorAndReset(err error) { <add> cs.mutex.Lock() <add> defer cs.mutex.Unlock() <add> cs.CPUPercentage = 0 <add> cs.Memory = 0 <add> cs.MemoryPercentage = 0 <add> cs.MemoryLimit = 0 <add> cs.NetworkRx = 0 <add> cs.NetworkTx = 0 <add> cs.BlockRead = 0 <add> cs.BlockWrite = 0 <add> cs.PidsCurrent = 0 <add> cs.err = err <add> cs.IsInvalid = true <add>} <add> <add>// SetError sets container statistics error <add>func (cs *ContainerStats) SetError(err error) { <add> cs.mutex.Lock() <add> defer cs.mutex.Unlock() <add> cs.err = err <add> if err != nil { <add> cs.IsInvalid = true <add> } <add>} <add> <add>// SetStatistics set the container statistics <add>func (cs *ContainerStats) SetStatistics(s StatsEntry) { <add> cs.mutex.Lock() <add> defer cs.mutex.Unlock() <add> s.Name = cs.Name <add> s.OSType = cs.OSType <add> cs.StatsEntry = s <add>} <add> <add>// GetStatistics returns container statistics with other meta data such as the container name <add>func (cs *ContainerStats) GetStatistics() StatsEntry { <add> cs.mutex.Lock() <add> defer cs.mutex.Unlock() <add> return cs.StatsEntry <ide> } <ide> <ide> // NewStatsFormat returns a format for rendering an CStatsContext <ide> func NewStatsFormat(source, osType string) Format { <ide> if source == TableFormatKey { <del> if osType == "windows" { <add> if osType == winOSType { <ide> return Format(winDefaultStatsTableFormat) <ide> } <ide> return Format(defaultStatsTableFormat) <ide> func NewStatsFormat(source, osType string) Format { <ide> // NewContainerStats returns a new ContainerStats entity and sets in it the given name <ide> func NewContainerStats(name, osType string) *ContainerStats { <ide> return &ContainerStats{ <del> ContainerStatsAttrs: ContainerStatsAttrs{ <del> Name: name, <del> Windows: (osType == "windows"), <del> }, <add> StatsEntry: StatsEntry{Name: name, OSType: osType}, <ide> } <ide> } <ide> <ide> // ContainerStatsWrite renders the context for a list of containers statistics <del>func ContainerStatsWrite(ctx Context, containerStats []*ContainerStats) error { <add>func ContainerStatsWrite(ctx Context, containerStats []StatsEntry) error { <ide> render := func(format func(subContext subContext) error) error { <ide> for _, cstats := range containerStats { <del> cstats.Mu.RLock() <del> cstatsAttrs := cstats.ContainerStatsAttrs <del> cstats.Mu.RUnlock() <ide> containerStatsCtx := &containerStatsContext{ <del> s: cstatsAttrs, <add> s: cstats, <ide> } <ide> if err := format(containerStatsCtx); err != nil { <ide> return err <ide> func ContainerStatsWrite(ctx Context, containerStats []*ContainerStats) error { <ide> <ide> type containerStatsContext struct { <ide> HeaderContext <del> s ContainerStatsAttrs <add> s StatsEntry <ide> } <ide> <ide> func (c *containerStatsContext) Container() string { <ide> c.AddHeader(containerHeader) <ide> return c.s.Name <ide> } <ide> <del>func (c *containerStatsContext) CPUPrec() string { <del> c.AddHeader(cpuPrecHeader) <add>func (c *containerStatsContext) CPUPerc() string { <add> c.AddHeader(cpuPercHeader) <add> if c.s.IsInvalid { <add> return fmt.Sprintf("--") <add> } <ide> return fmt.Sprintf("%.2f%%", c.s.CPUPercentage) <ide> } <ide> <ide> func (c *containerStatsContext) MemUsage() string { <ide> c.AddHeader(memUseHeader) <del> if !c.s.Windows { <del> return fmt.Sprintf("%s / %s", units.BytesSize(c.s.Memory), units.BytesSize(c.s.MemoryLimit)) <add> if c.s.IsInvalid || c.s.OSType == winOSType { <add> return fmt.Sprintf("-- / --") <ide> } <del> return fmt.Sprintf("-- / --") <add> return fmt.Sprintf("%s / %s", units.BytesSize(c.s.Memory), units.BytesSize(c.s.MemoryLimit)) <ide> } <ide> <del>func (c *containerStatsContext) MemPrec() string { <del> header := memPrecHeader <del> if c.s.Windows { <del> header = winMemPrecHeader <add>func (c *containerStatsContext) MemPerc() string { <add> header := memPercHeader <add> if c.s.OSType == winOSType { <add> header = winMemPercHeader <ide> } <ide> c.AddHeader(header) <add> if c.s.IsInvalid { <add> return fmt.Sprintf("--") <add> } <ide> return fmt.Sprintf("%.2f%%", c.s.MemoryPercentage) <ide> } <ide> <ide> func (c *containerStatsContext) NetIO() string { <ide> c.AddHeader(netIOHeader) <add> if c.s.IsInvalid { <add> return fmt.Sprintf("--") <add> } <ide> return fmt.Sprintf("%s / %s", units.HumanSizeWithPrecision(c.s.NetworkRx, 3), units.HumanSizeWithPrecision(c.s.NetworkTx, 3)) <ide> } <ide> <ide> func (c *containerStatsContext) BlockIO() string { <ide> c.AddHeader(blockIOHeader) <add> if c.s.IsInvalid { <add> return fmt.Sprintf("--") <add> } <ide> return fmt.Sprintf("%s / %s", units.HumanSizeWithPrecision(c.s.BlockRead, 3), units.HumanSizeWithPrecision(c.s.BlockWrite, 3)) <ide> } <ide> <ide> func (c *containerStatsContext) PIDs() string { <ide> c.AddHeader(pidsHeader) <del> if !c.s.Windows { <del> return fmt.Sprintf("%d", c.s.PidsCurrent) <add> if c.s.IsInvalid || c.s.OSType == winOSType { <add> return fmt.Sprintf("--") <ide> } <del> return fmt.Sprintf("-") <add> return fmt.Sprintf("%d", c.s.PidsCurrent) <ide> }
3
Ruby
Ruby
use an attr_reader for performance
b952470cc228ce4438226e180454bb141063b0ca
<ide><path>activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb <ide> def checkout_and_verify(c) <ide> # ActiveRecord::Base.connection_handler. Active Record models use this to <ide> # determine that connection pool that they should use. <ide> class ConnectionHandler <add> attr_reader :connection_pools <add> <ide> def initialize(pools = {}) <ide> @connection_pools = pools <ide> end <ide> <del> def connection_pools <del> @connection_pools ||= {} <del> end <del> <ide> def establish_connection(name, spec) <ide> @connection_pools[name] = ConnectionAdapters::ConnectionPool.new(spec) <ide> end
1
Javascript
Javascript
remove comment in eslint rule
a81443430b255af29462cd08b3f61f3e36a14592
<ide><path>tools/eslint-rules/align-multiline-assignment.js <ide> function testAssignment(context, node) { <ide> function testDeclaration(context, node) { <ide> node.declarations.forEach((declaration) => { <ide> const msg = checkExpressionAlignment(declaration.init); <del> // const start = declaration.init.loc.start; <ide> if (msg) <ide> context.report(node, msg); <ide> });
1
Go
Go
add memoryswappiness comment back
f41f62b6cc70a6afa533d11804d59d8bf5218ed8
<ide><path>runconfig/hostconfig.go <ide> func NewCapList(caps []string) *CapList { <ide> // Here, "non-portable" means "dependent of the host we are running on". <ide> // Portable information *should* appear in Config. <ide> type HostConfig struct { <del> Binds []string // List of volume bindings for this container <del> ContainerIDFile string // File (path) where the containerId is written <del> LxcConf *LxcConfig // Additional lxc configuration <del> Memory int64 // Memory limit (in bytes) <del> MemorySwap int64 // Total memory usage (memory + swap); set `-1` to disable swap <del> CPUShares int64 `json:"CpuShares"` // CPU shares (relative weight vs. other containers) <del> CPUPeriod int64 `json:"CpuPeriod"` // CPU CFS (Completely Fair Scheduler) period <del> CpusetCpus string // CpusetCpus 0-2, 0,1 <del> CpusetMems string // CpusetMems 0-2, 0,1 <del> CPUQuota int64 `json:"CpuQuota"` // CPU CFS (Completely Fair Scheduler) quota <del> BlkioWeight int64 // Block IO weight (relative weight vs. other containers) <del> OomKillDisable bool // Whether to disable OOM Killer or not <del> MemorySwappiness *int64 <add> Binds []string // List of volume bindings for this container <add> ContainerIDFile string // File (path) where the containerId is written <add> LxcConf *LxcConfig // Additional lxc configuration <add> Memory int64 // Memory limit (in bytes) <add> MemorySwap int64 // Total memory usage (memory + swap); set `-1` to disable swap <add> CPUShares int64 `json:"CpuShares"` // CPU shares (relative weight vs. other containers) <add> CPUPeriod int64 `json:"CpuPeriod"` // CPU CFS (Completely Fair Scheduler) period <add> CpusetCpus string // CpusetCpus 0-2, 0,1 <add> CpusetMems string // CpusetMems 0-2, 0,1 <add> CPUQuota int64 `json:"CpuQuota"` // CPU CFS (Completely Fair Scheduler) quota <add> BlkioWeight int64 // Block IO weight (relative weight vs. other containers) <add> OomKillDisable bool // Whether to disable OOM Killer or not <add> MemorySwappiness *int64 // Tuning container memory swappiness behaviour <ide> Privileged bool // Is the container in privileged mode <ide> PortBindings nat.PortMap // Port mapping between the exposed port (container) and the host <ide> Links []string // List of links (in the name:alias form)
1
Text
Text
update contact details
0418cebc583711263d983e0e3acbd474eb6f0fd2
<ide><path>README.md <ide> <ide> **A toolkit for building well-connected, self-describing web APIs.** <ide> <del>**Author:** Tom Christie. [Follow me on Twitter][twitter] <add>**Author:** Tom Christie. [Follow me on Twitter][twitter]. <add> <add>**Support:** [REST framework discussion group][group]. <ide> <ide> [![build-status-image]][travis] <ide> <ide> OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. <ide> [build-status-image]: https://secure.travis-ci.org/tomchristie/django-rest-framework.png?branch=restframework2 <ide> [travis]: http://travis-ci.org/tomchristie/django-rest-framework?branch=master <ide> [twitter]: https://twitter.com/_tomchristie <add>[group]: https://groups.google.com/forum/?fromgroups#!forum/django-rest-framework <ide> [0.4]: https://github.com/tomchristie/django-rest-framework/tree/0.4.X <ide> [sandbox]: http://restframework.herokuapp.com/ <ide> [rest-framework-2-announcement]: http://django-rest-framework.org/topics/rest-framework-2-announcement.html <ide><path>docs/topics/credits.md <ide> Development of REST framework 2.0 was sponsored by [DabApps]. <ide> <ide> ## Contact <ide> <del>To contact the author directly: <add>For usage questions please see the [REST framework discussion group][group]. <ide> <del>* twitter: [@_tomchristie][twitter] <del>* email: [tom@tomchristie.com][email] <add>You can also contact [@_tomchristie][twitter] directly on twitter. <ide> <ide> [email]: mailto:tom@tomchristie.com <ide> [twitter]: http://twitter.com/_tomchristie <ide> To contact the author directly: <ide> [dabapps]: http://lab.dabapps.com <ide> [sandbox]: http://restframework.herokuapp.com/ <ide> [heroku]: http://www.heroku.com/ <add>[group]: https://groups.google.com/forum/?fromgroups#!forum/django-rest-framework <ide> <ide> [tomchristie]: https://github.com/tomchristie <ide> [markotibold]: https://github.com/markotibold <ide><path>docs/tutorial/5-relationships-and-hyperlinked-apis.md <ide> You can review the final [tutorial code][repo] on GitHub, or try out a live exam <ide> <ide> We've reached the end of our tutorial. If you want to get more involved in the REST framework project, here's a few places you can start: <ide> <del>* Contribute on [GitHub][github] by reviewing and subitting issues, and making pull requests. <add>* Contribute on [GitHub][github] by reviewing and submitting issues, and making pull requests. <ide> * Join the [REST framework discussion group][group], and help build the community. <del>* Follow the author [on Twitter][twitter] and say hi. <add>* [Follow the author on Twitter][twitter] and say hi. <ide> <ide> **Now go build awesome things.** <ide>
3
Java
Java
orderedmessagesender throughput improvement
f5c287a6e66a76c12359ccfeb8a89f7495e7c18b
<ide><path>spring-messaging/src/main/java/org/springframework/messaging/simp/broker/OrderedMessageSender.java <ide> /* <del> * Copyright 2002-2018 the original author or authors. <add> * Copyright 2002-2020 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> <ide> package org.springframework.messaging.simp.broker; <ide> <add>import java.util.Collection; <add>import java.util.HashSet; <ide> import java.util.Queue; <add>import java.util.Set; <add>import java.util.concurrent.ConcurrentHashMap; <ide> import java.util.concurrent.ConcurrentLinkedQueue; <add>import java.util.concurrent.ConcurrentMap; <ide> import java.util.concurrent.atomic.AtomicBoolean; <ide> <ide> import org.apache.commons.logging.Log; <ide> import org.springframework.util.Assert; <ide> <ide> /** <del> * Submit messages to an {@link ExecutorSubscribableChannel}, one at a time. <del> * The channel must have been configured with {@link #configureOutboundChannel}. <add> * {@code MessageChannel} decorator that ensures messages from the same session <add> * are sent and processed in the same order. This would not normally be the case <add> * with an {@code Executor} backed {@code MessageChannel} since the executor <add> * is free to submit tasks in any order. <add> * <add> * <p>To provide ordering, inbound messages are placed in a queue and sent one <add> * one at a time per session. Once a message is processed, a callback is used to <add> * notify that the next message from the same session can be sent through. <ide> * <ide> * @author Rossen Stoyanchev <ide> * @since 5.1 <ide> class OrderedMessageSender implements MessageChannel { <ide> <ide> private final Log logger; <ide> <del> private final Queue<Message<?>> messages = new ConcurrentLinkedQueue<>(); <del> <del> private final AtomicBoolean sendInProgress = new AtomicBoolean(false); <add> private final Control control = new Control(); <ide> <ide> <ide> public OrderedMessageSender(MessageChannel channel, Log logger) { <ide> public boolean send(Message<?> message) { <ide> <ide> @Override <ide> public boolean send(Message<?> message, long timeout) { <del> this.messages.add(message); <add> this.control.addMessage(message); <ide> trySend(); <ide> return true; <ide> } <ide> <ide> private void trySend() { <del> // Take sendInProgress flag only if queue is not empty <del> if (this.messages.isEmpty()) { <del> return; <del> } <del> <del> if (this.sendInProgress.compareAndSet(false, true)) { <del> sendNextMessage(); <add> if (this.control.acquireSendLock()) { <add> sendMessages(); <ide> } <ide> } <ide> <del> private void sendNextMessage() { <del> for (;;) { <del> Message<?> message = this.messages.poll(); <del> if (message != null) { <add> private void sendMessages() { <add> for ( ; ; ) { <add> Set<String> skipSet = new HashSet<>(); <add> for (Message<?> message : this.control.getMessagesToSend()) { <add> String sessionId = SimpMessageHeaderAccessor.getSessionId(message.getHeaders()); <add> Assert.notNull(sessionId, () -> "No session id in " + message.getHeaders()); <add> if (skipSet.contains(sessionId)) { <add> continue; <add> } <add> if (!this.control.acquireSessionLock(sessionId)) { <add> skipSet.add(sessionId); <add> continue; <add> } <add> this.control.removeMessage(message); <ide> try { <del> addCompletionCallback(message); <add> getMutableAccessor(message).setHeader(COMPLETION_TASK_HEADER, (Runnable) () -> { <add> this.control.releaseSessionLock(sessionId); <add> if (this.control.hasRemainingWork()) { <add> trySend(); <add> } <add> }); <ide> if (this.channel.send(message)) { <del> return; <add> continue; <ide> } <ide> } <ide> catch (Throwable ex) { <ide> if (logger.isErrorEnabled()) { <ide> logger.error("Failed to send " + message, ex); <ide> } <ide> } <add> // We didn't send <add> this.control.releaseSessionLock(sessionId); <ide> } <del> else { <del> // We ran out of messages.. <del> this.sendInProgress.set(false); <del> trySend(); <del> break; <add> <add> if (this.control.shouldYield()) { <add> this.control.releaseSendLock(); <add> if (!this.control.shouldYield()) { <add> trySend(); <add> } <add> return; <ide> } <ide> } <ide> } <ide> <del> private void addCompletionCallback(Message<?> msg) { <del> SimpMessageHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(msg, SimpMessageHeaderAccessor.class); <add> private SimpMessageHeaderAccessor getMutableAccessor(Message<?> message) { <add> SimpMessageHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, SimpMessageHeaderAccessor.class); <ide> Assert.isTrue(accessor != null && accessor.isMutable(), "Expected mutable SimpMessageHeaderAccessor"); <del> accessor.setHeader(COMPLETION_TASK_HEADER, (Runnable) this::sendNextMessage); <add> return accessor; <ide> } <ide> <ide> <ide> static void configureOutboundChannel(MessageChannel channel, boolean preservePub <ide> Assert.isInstanceOf(ExecutorSubscribableChannel.class, channel, <ide> "An ExecutorSubscribableChannel is required for `preservePublishOrder`"); <ide> ExecutorSubscribableChannel execChannel = (ExecutorSubscribableChannel) channel; <del> if (execChannel.getInterceptors().stream().noneMatch(i -> i instanceof CallbackInterceptor)) { <del> execChannel.addInterceptor(0, new CallbackInterceptor()); <add> if (execChannel.getInterceptors().stream().noneMatch(i -> i instanceof CompletionTaskInterceptor)) { <add> execChannel.addInterceptor(0, new CompletionTaskInterceptor()); <ide> } <ide> } <ide> else if (channel instanceof ExecutorSubscribableChannel) { <ide> ExecutorSubscribableChannel execChannel = (ExecutorSubscribableChannel) channel; <del> execChannel.getInterceptors().stream().filter(i -> i instanceof CallbackInterceptor) <add> execChannel.getInterceptors().stream().filter(i -> i instanceof CompletionTaskInterceptor) <ide> .findFirst() <ide> .map(execChannel::removeInterceptor); <ide> <ide> } <ide> } <ide> <ide> <del> private static class CallbackInterceptor implements ExecutorChannelInterceptor { <add> /** <add> * Provides locks required for ordered message sending and execution within <add> * a session as well as storage for messages waiting to be sent. <add> */ <add> private static class Control { <add> <add> private final Queue<Message<?>> messages = new ConcurrentLinkedQueue<>(); <add> <add> private final ConcurrentMap<String, Boolean> sessionsInProgress = new ConcurrentHashMap<>(); <add> <add> private final AtomicBoolean workInProgress = new AtomicBoolean(false); <add> <add> <add> public void addMessage(Message<?> message) { <add> this.messages.add(message); <add> } <add> <add> public void removeMessage(Message<?> message) { <add> if (!this.messages.remove(message)) { <add> throw new IllegalStateException( <add> "Message " + message.getHeaders() + " was expected in the queue."); <add> } <add> } <add> <add> public Collection<Message<?>> getMessagesToSend() { <add> return this.messages; <add> } <add> <add> public boolean acquireSendLock() { <add> return this.workInProgress.compareAndSet(false, true); <add> } <add> <add> public void releaseSendLock() { <add> this.workInProgress.set(false); <add> } <add> <add> public boolean acquireSessionLock(String sessionId) { <add> if (this.sessionsInProgress.put(sessionId, Boolean.TRUE) != null) { <add> return false; <add> } <add> return true; <add> } <add> <add> public void releaseSessionLock(String sessionId) { <add> this.sessionsInProgress.remove(sessionId); <add> } <add> <add> public boolean hasRemainingWork() { <add> return !this.messages.isEmpty(); <add> } <add> <add> public boolean shouldYield() { <add> // No remaining work, or others can pick it up <add> return (!hasRemainingWork() || this.sessionsInProgress.size() > 0); <add> } <add> } <add> <add> <add> private static class CompletionTaskInterceptor implements ExecutorChannelInterceptor { <ide> <ide> @Override <ide> public void afterMessageHandled( <del> Message<?> msg, MessageChannel ch, MessageHandler handler, @Nullable Exception ex) { <add> Message<?> message, MessageChannel ch, MessageHandler handler, @Nullable Exception ex) { <ide> <del> Runnable task = (Runnable) msg.getHeaders().get(OrderedMessageSender.COMPLETION_TASK_HEADER); <add> Runnable task = (Runnable) message.getHeaders().get(OrderedMessageSender.COMPLETION_TASK_HEADER); <ide> if (task != null) { <ide> task.run(); <ide> } <ide><path>spring-messaging/src/test/java/org/springframework/messaging/simp/broker/OrderedMessageSenderTests.java <ide> /* <del> * Copyright 2002-2019 the original author or authors. <add> * Copyright 2002-2020 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> <ide> package org.springframework.messaging.simp.broker; <ide> <add>import java.time.Duration; <add>import java.util.Map; <add>import java.util.Random; <add>import java.util.concurrent.ConcurrentHashMap; <ide> import java.util.concurrent.CountDownLatch; <ide> import java.util.concurrent.TimeUnit; <ide> import java.util.concurrent.atomic.AtomicInteger; <ide> import org.junit.jupiter.api.AfterEach; <ide> import org.junit.jupiter.api.BeforeEach; <ide> import org.junit.jupiter.api.Test; <add>import org.reactivestreams.Publisher; <add>import reactor.core.publisher.Flux; <ide> <add>import org.springframework.messaging.Message; <add>import org.springframework.messaging.MessageHandler; <add>import org.springframework.messaging.MessagingException; <ide> import org.springframework.messaging.simp.SimpMessageHeaderAccessor; <ide> import org.springframework.messaging.simp.SimpMessageType; <ide> import org.springframework.messaging.support.ExecutorSubscribableChannel; <ide> public class OrderedMessageSenderTests { <ide> <ide> private static final Log logger = LogFactory.getLog(OrderedMessageSenderTests.class); <ide> <add> private static final Random random = new Random(); <add> <ide> <ide> private OrderedMessageSender sender; <ide> <ide> public void tearDown() { <ide> @Test <ide> public void test() throws InterruptedException { <ide> <del> int start = 1; <del> int end = 1000; <add> int sessionCount = 25; <add> int messagesPerSessionCount = 500; <add> <add> TestMessageHandler handler = new TestMessageHandler(sessionCount * messagesPerSessionCount); <add> this.channel.subscribe(handler); <add> <add> Publisher<Flux<Message<String>>> messageFluxes = <add> Flux.range(1, sessionCount).map(sessionId -> <add> Flux.range(1, messagesPerSessionCount) <add> .map(sequence -> createMessage(sessionId, sequence)) <add> .delayElements(Duration.ofMillis(Math.abs(random.nextLong()) % 5))); <add> <add> Flux.merge(messageFluxes) <add> .doOnNext(message -> this.sender.send(message)) <add> .blockLast(); <add> <add> handler.await(20, TimeUnit.SECONDS); <add> <add> assertThat(handler.getDescription()).isEqualTo("Total processed: " + sessionCount * messagesPerSessionCount); <add> assertThat(handler.getSequenceBySession()).hasSize(sessionCount); <add> handler.getSequenceBySession().forEach((key, value) -> <add> assertThat(value.get()).as(key).isEqualTo(messagesPerSessionCount)); <add> } <add> <add> private static Message<String> createMessage(Integer sessionId, Integer sequence) { <add> SimpMessageHeaderAccessor accessor = SimpMessageHeaderAccessor.create(SimpMessageType.MESSAGE); <add> accessor.setSessionId("session" + sessionId); <add> accessor.setHeader("seq", sequence); <add> accessor.setLeaveMutable(true); <add> return MessageBuilder.createMessage("payload", accessor.getMessageHeaders()); <add> } <add> <add> <add> private static class TestMessageHandler implements MessageHandler { <add> <add> private final int totalExpected; <add> <add> private final Map<String, AtomicInteger> sequenceBySession = new ConcurrentHashMap<>(); <add> <add> private final AtomicReference<String> description = new AtomicReference<>(); <add> <add> private final AtomicInteger totalReceived = new AtomicInteger(); <ide> <del> AtomicInteger index = new AtomicInteger(start); <del> AtomicReference<Object> result = new AtomicReference<>(); <del> CountDownLatch latch = new CountDownLatch(1); <add> private final CountDownLatch latch = new CountDownLatch(1); <ide> <del> this.channel.subscribe(message -> { <del> int expected = index.getAndIncrement(); <del> Integer actual = (Integer) message.getHeaders().getOrDefault("seq", -1); <del> if (actual != expected) { <del> result.set("Expected: " + expected + ", but was: " + actual); <add> TestMessageHandler(int totalExpected) { <add> this.totalExpected = totalExpected; <add> } <add> <add> public void await(long timeout, TimeUnit timeUnit) throws InterruptedException { <add> latch.await(timeout, timeUnit); <add> } <add> <add> public Map<String, AtomicInteger> getSequenceBySession() { <add> return sequenceBySession; <add> } <add> <add> public String getDescription() { <add> return description.get(); <add> } <add> <add> @Override <add> public void handleMessage(Message<?> message) throws MessagingException { <add> String id = SimpMessageHeaderAccessor.getSessionId(message.getHeaders()); <add> Integer seq = (Integer) message.getHeaders().getOrDefault("seq", -1); <add> <add> AtomicInteger prev = sequenceBySession.computeIfAbsent(id, i -> new AtomicInteger(0)); <add> if (!prev.compareAndSet(seq - 1, seq)) { <add> description.set("Out of order, session=" + id + ", prev=" + prev + ", next=" + seq); <ide> latch.countDown(); <ide> return; <ide> } <del> if (actual == 100 || actual == 200) { <add> <add> if (seq == 100) { <ide> try { <del> Thread.sleep(200); <add> // Processing delay to cause other session messages to queue up <add> Thread.sleep(50); <ide> } <ide> catch (InterruptedException ex) { <del> result.set(ex.toString()); <add> description.set(ex.toString()); <ide> latch.countDown(); <add> return; <ide> } <ide> } <del> if (actual == end) { <del> result.set("Done"); <add> <add> int total = totalReceived.incrementAndGet(); <add> description.set("Total processed: " + total); <add> if (total == totalExpected) { <ide> latch.countDown(); <ide> } <del> }); <del> <del> for (int i = start; i <= end; i++) { <del> SimpMessageHeaderAccessor accessor = SimpMessageHeaderAccessor.create(SimpMessageType.MESSAGE); <del> accessor.setHeader("seq", i); <del> accessor.setLeaveMutable(true); <del> this.sender.send(MessageBuilder.createMessage("payload", accessor.getMessageHeaders())); <ide> } <del> <del> latch.await(10, TimeUnit.SECONDS); <del> assertThat(result.get()).isEqualTo("Done"); <ide> } <del> <ide> } <ide>
2
Javascript
Javascript
use array.isarray exclusively
b0571517c5db009084f93fc70927a16b4ba01d20
<ide><path>src/Angular.js <ide> function isDate(value) { <ide> * @param {*} value Reference to check. <ide> * @returns {boolean} True if `value` is an `Array`. <ide> */ <del>var isArray = (function() { <del> if (!isFunction(Array.isArray)) { <del> return function(value) { <del> return toString.call(value) === '[object Array]'; <del> }; <del> } <del> return Array.isArray; <del>})(); <add>var isArray = Array.isArray; <ide> <ide> /** <ide> * @ngdoc function
1
Javascript
Javascript
fix unnecessary licenselint suppressions
75348acbfc7ae443a744e79a19b91b88568711d9
<ide><path>packages/react-native-codegen/src/parsers/flow/components/__test_fixtures__/failures.js <ide> * <ide> * @flow strict-local <ide> * @format <del> * @lint-ignore-every LICENSELINT <ide> */ <ide> <add>// @licenselint-loose-mode <add> <ide> 'use strict'; <ide> <ide> const COMMANDS_DEFINED_INLINE = ` <ide><path>packages/react-native-codegen/src/parsers/flow/components/__test_fixtures__/fixtures.js <ide> * <ide> * @flow strict-local <ide> * @format <del> * @lint-ignore-every LICENSELINT <ide> */ <ide> <add>// @licenselint-loose-mode <add> <ide> 'use strict'; <ide> <ide> const EVENT_DEFINITION = ` <ide><path>packages/react-native-codegen/src/parsers/flow/modules/__test_fixtures__/failures.js <ide> * <ide> * @flow strict-local <ide> * @format <del> * @lint-ignore-every LICENSELINT <ide> */ <ide> <add>// @licenselint-loose-mode <add> <ide> 'use strict'; <ide> <ide> const NATIVE_MODULES_WITH_ARRAY_WITH_NO_TYPE_FOR_CONTENT = ` <ide><path>packages/react-native-codegen/src/parsers/flow/modules/__test_fixtures__/fixtures.js <ide> * <ide> * @flow strict-local <ide> * @format <del> * @lint-ignore-every LICENSELINT <ide> */ <ide> <add>// @licenselint-loose-mode <add> <ide> 'use strict'; <ide> <ide> const EMPTY_NATIVE_MODULE = ` <ide><path>packages/react-native-codegen/src/parsers/typescript/components/__test_fixtures__/failures.js <ide> * <ide> * @flow strict-local <ide> * @format <del> * @lint-ignore-every LICENSELINT <ide> */ <ide> <add>// @licenselint-loose-mode <add> <ide> 'use strict'; <ide> <ide> const COMMANDS_DEFINED_INLINE = ` <ide><path>packages/react-native-codegen/src/parsers/typescript/components/__test_fixtures__/fixtures.js <ide> * <ide> * @flow strict-local <ide> * @format <del> * @lint-ignore-every LICENSELINT <ide> */ <ide> <add>// @licenselint-loose-mode <add> <ide> 'use strict'; <ide> <ide> const EVENT_DEFINITION = ` <ide><path>packages/react-native-codegen/src/parsers/typescript/modules/__test_fixtures__/failures.js <ide> * <ide> * @flow strict-local <ide> * @format <del> * @lint-ignore-every LICENSELINT <ide> */ <ide> <add>// @licenselint-loose-mode <add> <ide> const NATIVE_MODULES_WITH_ARRAY_WITH_NO_TYPE_FOR_CONTENT = ` <ide> /** <ide> * Copyright (c) Meta Platforms, Inc. and affiliates. <ide><path>packages/react-native-codegen/src/parsers/typescript/modules/__test_fixtures__/fixtures.js <ide> * <ide> * @flow strict-local <ide> * @format <del> * @lint-ignore-every LICENSELINT <ide> */ <ide> <add>// @licenselint-loose-mode <add> <ide> const EMPTY_NATIVE_MODULE = ` <ide> /** <ide> * Copyright (c) Meta Platforms, Inc. and affiliates.
8
Text
Text
add endoflife instructions to release procedure
1a087bca3d6ecceab96f9ab818b3b75262222d13
<ide><path>dev/README_RELEASE_AIRFLOW.md <ide> - [Update `main` with the latest release details](#update-main-with-the-latest-release-details) <ide> - [Update default Airflow version in the helm chart](#update-default-airflow-version-in-the-helm-chart) <ide> - [Update airflow/config_templates/config.yml file](#update-airflowconfig_templatesconfigyml-file) <add> - [Update EndOfLife data](#update-endoflife-data) <ide> <ide> <!-- END doctoc generated TOC please keep comment here to allow auto update --> <ide> <ide> File `airflow/config_templates/config.yml` contains documentation on all configu <ide> ``` <ide> <ide> - Update `airflow/config_templates/config.yml` with the details, and commit it. <add> <add>## Update EndOfLife data <add> <add>- Make a PR [EndOfLife](https://github.com/endoflife-date/endoflife.date) with release date, latest version and updated <add>changelog link.
1
Ruby
Ruby
add additional tests for
2a5ae2b714046d3f7eb1219eb366cf84c1cf9bb5
<ide><path>activesupport/test/core_ext/duration_test.rb <ide> def test_comparable <ide> assert_equal(1, (61 <=> 1.minute)) <ide> end <ide> <add> def test_twelve_months_equals_one_year <add> assert_equal 12.months, 1.year <add> end <add> <add> def test_thirty_days_does_not_equal_one_month <add> assert_not_equal 30.days, 1.month <add> end <add> <add> def test_adding_one_month_maintains_day_of_month <add> (1..11).each do |month| <add> [1, 14, 28].each do |day| <add> assert_equal Date.civil(2016, month + 1, day), Date.civil(2016, month, day) + 1.month <add> end <add> end <add> <add> assert_equal Date.civil(2017, 1, 1), Date.civil(2016, 12, 1) + 1.month <add> assert_equal Date.civil(2017, 1, 14), Date.civil(2016, 12, 14) + 1.month <add> assert_equal Date.civil(2017, 1, 28), Date.civil(2016, 12, 28) + 1.month <add> <add> assert_equal Date.civil(2015, 2, 28), Date.civil(2015, 1, 31) + 1.month <add> assert_equal Date.civil(2016, 2, 29), Date.civil(2016, 1, 31) + 1.month <add> end <add> <ide> # ISO8601 string examples are taken from ISO8601 gem at https://github.com/arnau/ISO8601/blob/b93d466840/spec/iso8601/duration_spec.rb <ide> # published under the conditions of MIT license at https://github.com/arnau/ISO8601/blob/b93d466840/LICENSE <ide> # <ide> def test_iso8601_parsing_across_autumn_dst_boundary <ide> travel_to Time.utc(2016, 11, 4) do <ide> assert_equal 604800, ActiveSupport::Duration.parse("P7D").to_i <ide> assert_equal 604800, ActiveSupport::Duration.parse("P1W").to_i <del> assert_equal ActiveSupport::Duration.parse(3.years.iso8601).to_i, 3.years.to_i <ide> end <ide> end <ide> end <ide> end <ide> <add> def test_iso8601_parsing_equivalence_with_numeric_extensions_over_long_periods <add> with_env_tz eastern_time_zone do <add> with_tz_default "Eastern Time (US & Canada)" do <add> assert_equal 3.months, ActiveSupport::Duration.parse("P3M") <add> assert_equal 3.months.to_i, ActiveSupport::Duration.parse("P3M").to_i <add> assert_equal 10.months, ActiveSupport::Duration.parse("P10M") <add> assert_equal 10.months.to_i, ActiveSupport::Duration.parse("P10M").to_i <add> assert_equal 3.years, ActiveSupport::Duration.parse("P3Y") <add> assert_equal 3.years.to_i, ActiveSupport::Duration.parse("P3Y").to_i <add> assert_equal 10.years, ActiveSupport::Duration.parse("P10Y") <add> assert_equal 10.years.to_i, ActiveSupport::Duration.parse("P10Y").to_i <add> end <add> end <add> end <add> <ide> def test_adding_durations_do_not_hold_prior_states <ide> time = Time.parse("Nov 29, 2016") <ide> # If the implementation adds and subtracts 3 months, the
1
Javascript
Javascript
add examples to the ember.nativearray docs
9b442d5205913ef3e58d4c653950bbdf03e60453
<ide><path>packages/ember-runtime/lib/system/native_array.js <ide> Ember.NativeArray = NativeArray; <ide> <ide> /** <ide> Creates an `Ember.NativeArray` from an Array like object. <del> Does not modify the original object. <add> Does not modify the original object. Ember.A is not needed if <add> `Ember.EXTEND_PROTOTYPES` is `true` (the default value). However, <add> it is recommended that you use Ember.A when creating addons for <add> ember or when you can not garentee that `Ember.EXTEND_PROTOTYPES` <add> will be `true`. <add> <add> Example <add> <add> ```js <add> var Pagination = Ember.CollectionView.extend({ <add> tagName: 'ul', <add> classNames: ['pagination'], <add> init: function() { <add> this._super(); <add> if (!this.get('content')) { <add> this.set('content', Ember.A([])); <add> } <add> } <add> }); <add> ``` <ide> <ide> @method A <ide> @for Ember <ide> Ember.A = function(arr) { <ide> <ide> /** <ide> Activates the mixin on the Array.prototype if not already applied. Calling <del> this method more than once is safe. <add> this method more than once is safe. This will be called when ember is loaded <add> unless you have `Ember.EXTEND_PROTOTYPES` or `Ember.EXTEND_PROTOTYPES.Array` <add> set to `false`. <add> <add> Example <add> <add> ```js <add> if (Ember.EXTEND_PROTOTYPES === true || Ember.EXTEND_PROTOTYPES.Array) { <add> Ember.NativeArray.activate(); <add> } <add> ``` <ide> <ide> @method activate <ide> @for Ember.NativeArray
1
Java
Java
add timer methods in observable.java
4deca78d518eb4acf8d33e840bba8b336ad10c6c
<ide><path>rxjava-core/src/main/java/rx/Observable.java <ide> import rx.operators.OperationThrottleFirst; <ide> import rx.operators.OperationTimeInterval; <ide> import rx.operators.OperationTimeout; <add>import rx.operators.OperationTimer; <ide> import rx.operators.OperationTimestamp; <ide> import rx.operators.OperationToMap; <ide> import rx.operators.OperationToMultimap; <ide> public static Observable<Long> interval(long interval, TimeUnit unit, Scheduler <ide> return create(OperationInterval.interval(interval, unit, scheduler)); <ide> } <ide> <add> /** <add> * Emits one item after a given delay, and then completes. <add> * <add> * @param interval <add> * interval size in time units <add> * @param unit <add> * time units to use for the interval size <add> */ <add> public static Observable<Void> timer(long interval, TimeUnit unit) { <add> return create(OperationTimer.timer(interval, unit)); <add> } <add> <add> /** <add> * Emits one item after a given delay, and then completes. <add> * <add> * @param interval <add> * interval size in time units <add> * @param unit <add> * time units to use for the interval size <add> * @param scheduler <add> * the scheduler to use for scheduling the item <add> */ <add> public static Observable<Void> timer(long interval, TimeUnit unit, <add> Scheduler scheduler) { <add> return create(OperationTimer.timer(interval, unit, scheduler)); <add> } <add> <ide> /** <ide> * Drops items emitted by an Observable that are followed by newer items <ide> * before a timeout value expires. The timer resets on each emission.
1
Javascript
Javascript
remove hikes from map
7eaccffd15c29faab720ef352e94630c67e74e32
<ide><path>server/boot/challenge.js <ide> module.exports = function(app) { <ide> name: blockArray[0].block, <ide> dashedName: dasherize(blockArray[0].block), <ide> challenges: blockArray <del> })); <add> })) <add> .filter(({ name })=> { <add> return name !== 'Hikes'; <add> }) <add> .shareReplay(); <ide> <ide> const User = app.models.User; <ide> const userCount$ = observeMethod(User, 'count'); <ide> module.exports = function(app) { <ide> const challengeId = req.user.currentChallenge.challengeId; <ide> // find challenge <ide> return challenge$ <add> .filter(({ block }) => block !== 'Hikes') <ide> .filter(({ id }) => id === challengeId) <ide> // now lets find the block it belongs to <ide> .flatMap(challenge => { <ide> module.exports = function(app) { <ide> completed: completedCount / blockArray.length * 100 <ide> }; <ide> }) <add> .filter(({ name }) => name !== 'Hikes') <ide> // turn stream of blocks into a stream of an array <ide> .toArray(); <ide>
1
Ruby
Ruby
add forgotten file
6fcc81b7f9a8b27b898794dfe4f0a8202393e8a3
<ide><path>activesupport/test/autoloading_fixtures/application.rb <add>ApplicationController = 10
1
Text
Text
add guide for gatsby.js styling
9181e6b3d0d921e7ed61dd2afa8c42b16025331a
<ide><path>guide/english/gatsbyjs/gatsbyjs-styling/index.md <add>--- <add>title: Gatsby.js Styling <add>--- <add> <add>## Gatsby.js Styling <add> <add>There are so many ways to add styles to your website — and Gatsby supports almost every possible option, through official and community plugins. <add> <add>NOTE: Gatsby doesn’t prescribe or dictate any single styling approach. Choose what works best for you! <add> <add>## Layout Components <add> <add>For sections of your site that you want to share across multiple pages. Creating and using the component as shown below. <add> <add>``` <add>// src/components/layout.js <add> <add>import React from "react" <add> <add>export default ({ children }) => ( <add> <div style={{ margin: `0 auto`, maxWidth: 650, padding: `0 1rem` }}> <add> {children} <add> </div> <add>) <add>``` <add> <add>``` <add>// src/pages/index.js <add> <add>import React from "react" <add>import Layout from "../components/layout" <add> <add>export default () => ( <add> <Layout> <add> <h1>I’m in a layout!</h1> <add> </Layout> <add>) <add>``` <add> <add>## CSS Modules <add> <add>CSS Modules are highly recommended for those new to building with Gatsby (and React in general). A CSS Module is a CSS file in which all class names and animation names are scoped locally by default. They are very popular as they let you write CSS like normal but with a lot more safety. The tool automatically makes class and animation names unique so you don’t have to worry about selector name collisions. <add> <add>Check (CSS Modules homepage here](https://github.com/css-modules/css-modules). <add> <add>## Typography.js <add> <add>Typography.js is a JavaScript library that enables you to define and explore the typographic design of your website and define beautiful custom and pre-existing typographic themes. It limits the number of tedious changes you need to make to your website just to change the font. <add> <add>Learn [how to use Typography.js on your Gatsby site here](https://www.gatsbyjs.org/docs/typography-js/). <add> <add>## Using CSS-in-JS <add> <add>With CSS-in-JS, you avoid all that as CSS selectors are scoped automatically to their component. Styles are tightly coupled with their components. This makes it easier to know how to edit a component’s CSS as there’s never any confusion about how and where CSS is being used. <add> <add>### Glamor <add> <add>Check out [walkthrough guide on setting up Glamor on your Gatsby site](https://www.gatsbyjs.org/docs/glamor/) <add> <add>### Styled components <add> <add>Check out [walkthrough guide on setting up Styled Components on your Gatsby site](https://www.gatsbyjs.org/docs/styled-components/) <add> <add>## Creating global styles <add> <add>In nearly every site, there will be some global styles, such as a reset or typography defaults. Check out the [guide at official Gatsby docs for creating global styles](https://www.gatsbyjs.org/docs/creating-global-styles/). <add> <add> <add>## PostCSS <add> <add>PostCSS transforms extended syntaxes and features into modern, browser-friendly CSS. Checkout guide will [show you how to get started with Gatsby and PostCSS](https://www.gatsbyjs.org/docs/post-css/). <add> <add>### More Information: <add>Check out the Gatsby.js official docs for styling at [Gatsby Styling](https://www.gatsbyjs.org/docs/styling/). For more information and learn more, visit: [Gatsby.js official site](https://www.gatsbyjs.org/tutorial/)
1
Text
Text
use correct link to contributing.md
14fad91084840886dd0f10825cf28d97e57f95b4
<ide><path>packages/next/README.md <ide> As we were researching options for server-rendering React that didn’t involve <ide> <ide> ## Contributing <ide> <del>Please see our [contributing.md](/packages/next/contributing.md) <add>Please see our [contributing.md](/contributing.md) <ide> <ide> ## Authors <ide>
1
Text
Text
remove loader hooks from unsupported features
d2e44d5e7fcc93c615ac5cef794bdfbcd32c3fc0
<ide><path>doc/api/esm.md <ide> points into ESM graphs at run time. <ide> | `require('./foo.mjs')` | ES Modules have differing resolution and timing, use language standard `import()` | <ide> | `import()` | pending newer V8 release used in Node.js | <ide> | `import.meta` | pending V8 implementation | <del>| Loader Hooks | pending Node.js EP creation/consensus | <ide> <ide> ## Notable differences between `import` and `require` <ide>
1
Text
Text
add ashcripps to collaborators
c8887e78dd709344e94d63ef5b19a4e40b2edb78
<ide><path>README.md <ide> For information about the governance of the Node.js project, see <ide> **Anto Aravinth** &lt;anto.aravinth.cse@gmail.com&gt; (he/him) <ide> * [apapirovski](https://github.com/apapirovski) - <ide> **Anatoli Papirovski** &lt;apapirovski@mac.com&gt; (he/him) <add>* [AshCripps](https://github.com/AshCripps) - <add>**Ash Cripps** &lt;ashley.cripps@ibm.com&gt; <ide> * [bcoe](https://github.com/bcoe) - <ide> **Ben Coe** &lt;bencoe@gmail.com&gt; (he/him) <ide> * [bengl](https://github.com/bengl) -
1
Python
Python
add a bigquerycheckoperator
0c66806072ac07234542dc42e87532715ce732ac
<ide><path>airflow/contrib/hooks/bigquery_hook.py <ide> def rollback(self): <ide> raise NotSupportedError("BigQueryConnection does not have transactions") <ide> <ide> class BigQueryBaseCursor(object): <add> # TODO pydocs <ide> def __init__(self, service, project_id): <add> # TODO pydocs <ide> self.service = service <ide> self.project_id = project_id <ide> <ide> def __init__(self, service, project_id): <ide> self.buffersize = None <ide> self.page_token = None <ide> self.job_id = None <del> self.buffer = None <add> self.buffer = [] <ide> <ide> @property <ide> def description(self): <ide> def next(self): <ide> if not self.job_id: <ide> return None <ide> <del> if not self.buffer or len(self.buffer) == 0: <add> if len(self.buffer) == 0: <ide> query_results = self.service.jobs().getQueryResults(projectId=self.project_id, jobId=self.job_id, pageToken=self.page_token).execute() <ide> <ide> if len(query_results['rows']) == 0: <ide> def next(self): <ide> self.page_token = None <ide> return None <ide> else: <del> self.page_token = query_results['page_token'] <add> self.page_token = query_results.get('pageToken') <add> fields = query_results['schema']['fields'] <add> col_types = [field['type'] for field in fields] <ide> rows = query_results['rows'] <ide> <del> for row in rows: <del> self.buffer.append(map(lambda vs: vs['v'], row['f'])) <add> for idx, dict_row in enumerate(rows): <add> typed_row = [_bq_cast(vs['v'], col_types[idx]) for vs in dict_row['f']] <add> self.buffer.append(typed_row) <ide> <ide> return self.buffer.pop(0) <ide> <ide> def fetchall(self): <ide> return result <ide> <ide> def get_arraysize(self): <add> # TODO pydocs <ide> # PEP 249 <ide> return self._buffersize if self.buffersize else 1 <ide> <ide> def set_arraysize(self, arraysize): <add> # TODO pydocs <ide> # PEP 249 <ide> self.buffersize = arraysize <ide> <ide> def setoutputsize(self, size, column=None): <ide> pass <ide> <ide> def _bind_parameters(operation, parameters): <add> # TODO pydocs <ide> # inspired by MySQL Python Connector (conversion.py) <ide> string_parameters = {} <ide> for (name, value) in parameters.iteritems(): <ide> def _bind_parameters(operation, parameters): <ide> return operation % string_parameters <ide> <ide> def _escape(s): <add> # TODO pydocs <ide> e = s <ide> e = e.replace('\\', '\\\\') <ide> e = e.replace('\n', '\\n') <ide> e = e.replace('\r', '\\r') <ide> e = e.replace("'", "\\'") <ide> e = e.replace('"', '\\"') <ide> return e <add> <add>def _bq_cast(string_field, bq_type): <add> # TODO pydocs <add> if bq_type == 'INTEGER' or bq_type == 'TIMESTAMP': <add> return int(string_field) <add> elif bq_type == 'FLOAT': <add> return float(string_field) <add> elif bq_type == 'BOOLEAN': <add> return bool(string_field) <add> else: <add> return string_field <ide>\ No newline at end of file <ide><path>airflow/contrib/operators/bigquery_check_operator.py <add>from airflow.contrib.hooks.bigquery_hook import BigQueryHook <add>from airflow.operators import CheckOperator, ValueCheckOperator, IntervalCheckOperator <add>from airflow.utils import apply_defaults <add> <add> <add>class BigQueryCheckOperator(CheckOperator): <add> # TODO pydocs <add> @apply_defaults <add> def __init__( <add> self, <add> sql, <add> bigquery_conn_id='bigquery_default', <add> *args, <add> **kwargs): <add> super(BigQueryCheckOperator, self).__init__(sql=sql, *args, **kwargs) <add> self.bigquery_conn_id = bigquery_conn_id <add> self.sql = sql <add> <add> def get_db_hook(self): <add> return BigQueryHook(bigquery_conn_id=self.bigquery_conn_id) <add> <add>class BigQueryValueCheckOperator(ValueCheckOperator): <add> # TODO pydocs <add> <add> @apply_defaults <add> def __init__( <add> self, sql, pass_value, tolerance=None, <add> bigquery_conn_id='bigquery_default', <add> *args, **kwargs): <add> super(BigQueryValueCheckOperator, self).__init__(sql=sql, pass_value=pass_value, tolerance=tolerance, *args, **kwargs) <add> self.bigquery_conn_id = bigquery_conn_id <add> <add> def get_db_hook(self): <add> return BigQueryHook(bigquery_conn_id=self.bigquery_conn_id) <add> <add> <add>class BigQueryIntervalCheckOperator(IntervalCheckOperator): <add> # TODO pydocs <add> <add> @apply_defaults <add> def __init__( <add> self, table, metrics_thresholds, <add> date_filter_column='ds', days_back=-7, <add> bigquery_conn_id='bigquery_default', <add> *args, **kwargs): <add> super(BigQueryIntervalCheckOperator, self).__init__( <add> table=table, metrics_thresholds=metrics_thresholds, date_filter_column=date_filter_column, days_back=days_back, <add> *args, **kwargs) <add> self.bigquery_conn_id = bigquery_conn_id <add> <add> def get_db_hook(self): <add> return BigQueryHook(bigquery_conn_id=self.bigquery_conn_id)
2
Java
Java
add support for non-standard status codes
29ef985411b480c0fbdb2b858585c3826e5e7b5b
<ide><path>spring-test/src/main/java/org/springframework/mock/http/client/reactive/MockClientHttpResponse.java <ide> /* <del> * Copyright 2002-2018 the original author or authors. <add> * Copyright 2002-2019 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> */ <ide> public class MockClientHttpResponse implements ClientHttpResponse { <ide> <del> private final HttpStatus status; <add> private final int status; <ide> <ide> private final HttpHeaders headers = new HttpHeaders(); <ide> <ide> public class MockClientHttpResponse implements ClientHttpResponse { <ide> <ide> public MockClientHttpResponse(HttpStatus status) { <ide> Assert.notNull(status, "HttpStatus is required"); <add> this.status = status.value(); <add> } <add> <add> public MockClientHttpResponse(int status) { <add> Assert.isTrue(status >= 100 && status < 600, "Status must be between 1xx and 5xx"); <ide> this.status = status; <ide> } <ide> <ide> <ide> @Override <ide> public HttpStatus getStatusCode() { <del> return this.status; <add> return HttpStatus.resolve(this.status); <ide> } <ide> <ide> @Override <ide> public int getRawStatusCode() { <del> return this.status.value(); <add> return this.status; <ide> } <ide> <ide> @Override <ide><path>spring-web/src/main/java/org/springframework/http/client/reactive/ClientHttpResponse.java <ide> /* <del> * Copyright 2002-2018 the original author or authors. <add> * Copyright 2002-2019 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> import org.springframework.http.HttpStatus; <ide> import org.springframework.http.ReactiveHttpInputMessage; <ide> import org.springframework.http.ResponseCookie; <add>import org.springframework.lang.Nullable; <ide> import org.springframework.util.MultiValueMap; <ide> <ide> /** <ide> public interface ClientHttpResponse extends ReactiveHttpInputMessage { <ide> * Return the HTTP status code of the response. <ide> * @return the HTTP status as an HttpStatus enum value <ide> * @throws IllegalArgumentException in case of an unknown HTTP status code <del> * @see HttpStatus#valueOf(int) <add> * @see HttpStatus#resolve(int) <ide> */ <add> @Nullable <ide> HttpStatus getStatusCode(); <ide> <ide> /** <ide><path>spring-web/src/main/java/org/springframework/http/client/reactive/JettyClientHttpResponse.java <ide> public JettyClientHttpResponse(ReactiveResponse reactiveResponse, Publisher<Data <ide> <ide> @Override <ide> public HttpStatus getStatusCode() { <del> return HttpStatus.valueOf(getRawStatusCode()); <add> return HttpStatus.resolve(getRawStatusCode()); <ide> } <ide> <ide> @Override <ide><path>spring-web/src/main/java/org/springframework/http/client/reactive/ReactorClientHttpResponse.java <ide> /* <del> * Copyright 2002-2018 the original author or authors. <add> * Copyright 2002-2019 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> public HttpHeaders getHeaders() { <ide> <ide> @Override <ide> public HttpStatus getStatusCode() { <del> return HttpStatus.valueOf(getRawStatusCode()); <add> return HttpStatus.resolve(getRawStatusCode()); <ide> } <ide> <ide> @Override <ide><path>spring-web/src/test/java/org/springframework/mock/http/client/reactive/test/MockClientHttpResponse.java <ide> /* <del> * Copyright 2002-2018 the original author or authors. <add> * Copyright 2002-2019 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> */ <ide> public class MockClientHttpResponse implements ClientHttpResponse { <ide> <del> private final HttpStatus status; <add> private final int status; <ide> <ide> private final HttpHeaders headers = new HttpHeaders(); <ide> <ide> public class MockClientHttpResponse implements ClientHttpResponse { <ide> <ide> public MockClientHttpResponse(HttpStatus status) { <ide> Assert.notNull(status, "HttpStatus is required"); <add> this.status = status.value(); <add> } <add> <add> public MockClientHttpResponse(int status) { <add> Assert.isTrue(status >= 100 && status < 600, "Status must be between 1xx and 5xx"); <ide> this.status = status; <ide> } <ide> <ide> <ide> @Override <ide> public HttpStatus getStatusCode() { <del> return this.status; <add> return HttpStatus.resolve(this.status); <ide> } <ide> <ide> @Override <ide> public int getRawStatusCode() { <del> return this.status.value(); <add> return this.status; <ide> } <ide> <ide> @Override <ide> public Flux<DataBuffer> getBody() { <ide> public Mono<String> getBodyAsString() { <ide> Charset charset = getCharset(); <ide> return Flux.from(getBody()) <del> .reduce(bufferFactory.allocateBuffer(), (previous, current) -> { <add> .reduce(this.bufferFactory.allocateBuffer(), (previous, current) -> { <ide> previous.write(current); <ide> DataBufferUtils.release(current); <ide> return previous; <ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/function/client/ClientResponse.java <ide> /* <del> * Copyright 2002-2018 the original author or authors. <add> * Copyright 2002-2019 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> import org.springframework.http.client.reactive.ClientHttpResponse; <ide> import org.springframework.http.codec.HttpMessageReader; <ide> import org.springframework.http.codec.HttpMessageWriter; <add>import org.springframework.lang.Nullable; <ide> import org.springframework.util.MultiValueMap; <ide> import org.springframework.web.reactive.function.BodyExtractor; <ide> <ide> public interface ClientResponse { <ide> * Return the status code of this response. <ide> * @return the status as an HttpStatus enum value <ide> * @throws IllegalArgumentException in case of an unknown HTTP status code <del> * @see HttpStatus#valueOf(int) <add> * @see HttpStatus#resolve(int) <ide> */ <add> @Nullable <ide> HttpStatus statusCode(); <ide> <ide> /** <ide> static Builder create(HttpStatus statusCode, ExchangeStrategies strategies) { <ide> return new DefaultClientResponseBuilder(strategies).statusCode(statusCode); <ide> } <ide> <add> /** <add> * Create a response builder with the given raw status code and strategies for reading the body. <add> * @param statusCode the status code <add> * @param strategies the strategies <add> * @return the created builder <add> * @since 5.1.9 <add> */ <add> static Builder create(int statusCode, ExchangeStrategies strategies) { <add> return new DefaultClientResponseBuilder(strategies).rawStatusCode(statusCode); <add> } <add> <ide> /** <ide> * Create a response builder with the given status code and message body readers. <ide> * @param statusCode the status code <ide> interface Builder { <ide> */ <ide> Builder statusCode(HttpStatus statusCode); <ide> <add> /** <add> * Set the raw status code of the response. <add> * @param statusCode the new status code. <add> * @return this builder <add> * @since 5.1.9 <add> */ <add> Builder rawStatusCode(int statusCode); <add> <ide> /** <ide> * Add the given header value(s) under the given name. <ide> * @param headerName the header name <ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/function/client/DefaultClientResponseBuilder.java <ide> final class DefaultClientResponseBuilder implements ClientResponse.Builder { <ide> <ide> private ExchangeStrategies strategies; <ide> <del> private HttpStatus statusCode = HttpStatus.OK; <add> private int statusCode = 200; <ide> <ide> private final HttpHeaders headers = new HttpHeaders(); <ide> <ide> public DefaultClientResponseBuilder(ExchangeStrategies strategies) { <ide> public DefaultClientResponseBuilder(ClientResponse other) { <ide> Assert.notNull(other, "ClientResponse must not be null"); <ide> this.strategies = other.strategies(); <del> statusCode(other.statusCode()); <add> this.statusCode = other.rawStatusCode(); <ide> headers(headers -> headers.addAll(other.headers().asHttpHeaders())); <ide> cookies(cookies -> cookies.addAll(other.cookies())); <ide> } <ide> <ide> <ide> @Override <ide> public DefaultClientResponseBuilder statusCode(HttpStatus statusCode) { <del> Assert.notNull(statusCode, "HttpStatus must not be null"); <add> return rawStatusCode(statusCode.value()); <add> } <add> <add> @Override <add> public DefaultClientResponseBuilder rawStatusCode(int statusCode) { <add> Assert.isTrue(statusCode >= 100 && statusCode < 600, "StatusCode must be between 1xx and 5xx"); <ide> this.statusCode = statusCode; <ide> return this; <ide> } <ide> public ClientResponse build() { <ide> <ide> private static class BuiltClientHttpResponse implements ClientHttpResponse { <ide> <del> private final HttpStatus statusCode; <add> private final int statusCode; <ide> <ide> private final HttpHeaders headers; <ide> <ide> private final MultiValueMap<String, ResponseCookie> cookies; <ide> <ide> private final Flux<DataBuffer> body; <ide> <del> public BuiltClientHttpResponse(HttpStatus statusCode, HttpHeaders headers, <add> public BuiltClientHttpResponse(int statusCode, HttpHeaders headers, <ide> MultiValueMap<String, ResponseCookie> cookies, Flux<DataBuffer> body) { <ide> <ide> this.statusCode = statusCode; <ide> public BuiltClientHttpResponse(HttpStatus statusCode, HttpHeaders headers, <ide> <ide> @Override <ide> public HttpStatus getStatusCode() { <del> return this.statusCode; <add> return HttpStatus.resolve(this.statusCode); <ide> } <ide> <ide> @Override <ide> public int getRawStatusCode() { <del> return this.statusCode.value(); <add> return this.statusCode; <ide> } <ide> <ide> @Override <ide><path>spring-webflux/src/test/java/org/springframework/web/reactive/function/client/DefaultClientResponseBuilderTests.java <ide> /* <del> * Copyright 2002-2018 the original author or authors. <add> * Copyright 2002-2019 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> import org.springframework.http.HttpStatus; <ide> import org.springframework.http.ResponseCookie; <ide> <del>import static org.junit.Assert.*; <add>import static org.junit.Assert.assertEquals; <add>import static org.junit.Assert.assertNotNull; <add>import static org.junit.Assert.assertNull; <ide> <ide> /** <ide> * @author Arjen Poutsma <ide> public void from() { <ide> .verifyComplete(); <ide> } <ide> <add> @Test <add> public void fromCustomStatus() { <add> <add> ClientResponse other = ClientResponse.create(499, ExchangeStrategies.withDefaults()) <add> .build(); <add> <add> ClientResponse result = ClientResponse.from(other) <add> .build(); <add> <add> assertEquals(499, result.rawStatusCode()); <add> assertNull(result.statusCode()); <add> <add> } <add> <ide> <ide> }
8
Javascript
Javascript
expose `options` arg in `debugger` hb helper
78f93856c9513edcc9d40e801c1f863d8e536a0c
<ide><path>packages/ember-handlebars/lib/helpers/debug.js <ide> Ember.Handlebars.registerHelper('log', function(property, options) { <ide> @for Ember.Handlebars.helpers <ide> @param {String} property <ide> */ <del>Ember.Handlebars.registerHelper('debugger', function() { <add>Ember.Handlebars.registerHelper('debugger', function(options) { <ide> debugger; <ide> });
1
Java
Java
improve webclient.builder javadoc
8a7bb494362e7a081e18e40726591656551f9922
<ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/function/client/WebClient.java <ide> interface Builder { <ide> * </pre> <ide> * <p><strong>Note:</strong> this method is mutually exclusive with <ide> * {@link #uriBuilderFactory(UriBuilderFactory)}. If both are used, the <del> * baseUrl value provided here will be ignored. <add> * defaultUriVariables value provided here will be ignored. <ide> * @see DefaultUriBuilderFactory#setDefaultUriVariables(Map) <ide> * @see #uriBuilderFactory(UriBuilderFactory) <ide> */
1
Text
Text
update the binary package links to x86/x64
f9df96b950885d6510ee6f5b4e525036fb4aba4e
<ide><path>tools/email-footer.md <ide> Windows x64 Installer: http://nodejs.org/dist/__VERSION__/x64/node-__VERSION__-x <ide> <ide> Windows x64 Files: http://nodejs.org/dist/__VERSION__/x64/ <ide> <del>Linux 32-bit Binary Package: http://nodejs.org/dist/__VERSION__/node-__VERSION__-linux-i686.tar.gz <add>Linux 32-bit Binary: http://nodejs.org/dist/__VERSION__/node-__VERSION__-linux-x86.tar.gz <ide> <del>Linux 64-bit Binary Package: http://nodejs.org/dist/__VERSION__/node-__VERSION__-linux-x86_64.tar.gz <add>Linux 64-bit Binary: http://nodejs.org/dist/__VERSION__/node-__VERSION__-linux-x64.tar.gz <ide> <del>Solaris 32-bit Binary Package: http://nodejs.org/dist/__VERSION__/node-__VERSION__-sunos-i386.tar.gz <add>Solaris 32-bit Binary: http://nodejs.org/dist/__VERSION__/node-__VERSION__-sunos-x86.tar.gz <ide> <del>Solaris 64-bit Binary Package: http://nodejs.org/dist/__VERSION__/node-__VERSION__-sunos-x86_64.tar.gz <add>Solaris 64-bit Binary: http://nodejs.org/dist/__VERSION__/node-__VERSION__-sunos-x64.tar.gz <ide> <ide> Other release files: http://nodejs.org/dist/__VERSION__/ <ide>
1
Javascript
Javascript
change permissions to node files on linux
fc95475d6e2ff4bc1a8e0382c11a0eb45a907f25
<ide><path>script/lib/package-application.js <ide> module.exports = function () { <ide> if (process.platform === 'darwin') { <ide> bundledResourcesPath = path.join(packagedAppPath, 'Contents', 'Resources') <ide> setAtomHelperVersion(packagedAppPath) <add> } else if (process.platform == 'linux') { <add> bundledResourcesPath = path.join(packagedAppPath, 'resources') <add> chmodNodeFiles(packagedAppPath) <ide> } else { <ide> bundledResourcesPath = path.join(packagedAppPath, 'resources') <ide> } <ide> function setAtomHelperVersion (packagedAppPath) { <ide> childProcess.spawnSync('/usr/libexec/PlistBuddy', ['-c', 'Set CFBundleShortVersionString', CONFIG.appMetadata.version, helperPListPath]) <ide> } <ide> <add>function chmodNodeFiles (packagedAppPath) { <add> console.log(`Changing permissions for node files in ${packagedAppPath}`) <add> childProcess.spawnSync('find', [packagedAppPath, '-type', 'f', '-name', '*.node', '-exec chmod a-x {};']) <add>} <add> <ide> function buildAsarUnpackGlobExpression () { <ide> const unpack = [ <ide> '*.node',
1
Python
Python
add default_model to about
780cb847c952ca2a836e90907c36836c53d3cf34
<ide><path>setup.py <ide> def write_version(path): <ide> full_version = '%(full_version)s' <ide> git_revision = '%(git_revision)s' <ide> release = %(isrelease)s <add>default_model = 'en_default==1.0.4' <ide> if not release: <ide> version = full_version <ide> """ <ide><path>spacy/en/download.py <ide> def link(package, path): <ide> force=("Force overwrite", "flag", "f", bool), <ide> ) <ide> def main(data_size='all', force=False): <del> package_name = 'en_default==1.0.4' <ide> path = os.path.dirname(os.path.abspath(__file__)) <ide> <ide> if force: <ide> sputnik.purge('spacy', about.short_version) <ide> <del> package = sputnik.install('spacy', about.short_version, package_name) <add> package = sputnik.install('spacy', about.short_version, about.default_model) <ide> <ide> try: <del> sputnik.package('spacy', about.short_version, package_name) <add> sputnik.package('spacy', about.short_version, about.default_model) <ide> except PackageNotFoundException, CompatiblePackageNotFoundException: <ide> print("Model failed to install. Please run 'python -m " <ide> "spacy.en.download --force'.", file=sys.stderr) <ide><path>spacy/language.py <ide> def __init__(self, <ide> via = data_dir <ide> <ide> if via is None: <del> package = util.get_package_by_name('en_default==1.0.4') <add> package = util.get_package_by_name(about.default_model) <ide> else: <ide> package = util.get_package(via) <ide>
3
PHP
PHP
tweak some code
866a8cfc58430830069bd24feacf2d81e99385a2
<ide><path>src/Illuminate/Foundation/Bootstrap/DetectEnvironment.php <ide> public function bootstrap(Application $app) <ide> { <ide> try <ide> { <del> Dotenv::makeMutable(); <del> <ide> Dotenv::load($app['path.base'], $app->environmentFile()); <add> <add> Dotenv::makeMutable(); <ide> } <ide> catch (InvalidArgumentException $e) <ide> {
1
Javascript
Javascript
remove unnecessary condition
3a6d6560903e882db8776017594ceab79e66a9da
<ide><path>src/backend/renderer.js <ide> export function attach( <ide> const nextFallbackChildSet = nextFiber.child.sibling; <ide> mountFiberRecursively(nextFallbackChildSet, nextFiber, true); <ide> shouldResetChildren = true; <del> } else if (!prevDidTimeout && !nextDidTimeOut) { <add> } else { <ide> // Common case: Primary -> Primary. <ide> // This is the same codepath as for non-Suspense fibers. <ide> if (nextFiber.child !== prevFiber.child) {
1
Javascript
Javascript
run eslint on simplehttpserver
4c91e53687252e2b7f5e59c9325c229a0aa758c5
<ide><path>utils/servers/simplehttpserver.js <ide> var port = 8000, <ide> "mp4": "video/mp4", <ide> "txt": "text/plain", <ide> "bin": "application/octet-stream" <del> }; <add> }; <ide> <ide> // https://github.com/parshap/node-sanitize-filename/blob/master/index.js#L33-L47 <ide> var illegalRe = /[\?<>:\*\|":]/g; <ide> var reservedRe = /^\.+$/; <ide> var windowsReservedRe = /^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\..*)?$/i; <ide> var windowsTrailingRe = /[\. ]+$/; <ide> <del>function sanitize(input) { <del> var sanitized = input <del> .replace(/\//g, "\\") <del> .replace(illegalRe, "") <del> .replace(controlRe, "") <del> .replace(reservedRe, "") <del> .replace(windowsReservedRe, "") <del> .replace(windowsTrailingRe, ""); <del> return sanitized; <add>function sanitize( input ) { <add> <add> var sanitized = input <add> .replace( /\//g, "\\" ) <add> .replace( illegalRe, "" ) <add> .replace( controlRe, "" ) <add> .replace( reservedRe, "" ) <add> .replace( windowsReservedRe, "" ) <add> .replace( windowsTrailingRe, "" ); <add> return sanitized; <add> <ide> } <ide> <ide> <ide> port = process.argv[ 2 ] ? parseInt( process.argv[ 2 ], 0 ) : port; <ide> <ide> function handleRequest( request, response ) { <ide> <del> var urlObject = urlParser.parse( request.url, true ); <del> var pathname = decodeURIComponent( sanitize( urlObject.pathname ) ); <add> var urlObject = urlParser.parse( request.url, true ); <add> var pathname = decodeURIComponent( sanitize( urlObject.pathname ) ); <ide> <ide> console.log( '[' + ( new Date() ).toUTCString() + '] ' + '"' + request.method + ' ' + pathname + '"' ); <ide> <ide> function handleRequest( request, response ) { <ide> files.forEach( function ( item ) { <ide> <ide> var urlpath = path.join( pathname, item ), <del> itemStats = fs.statSync( path.join( currentDir, urlpath ) ); <add> itemStats = fs.statSync( path.join( currentDir, urlpath ) ); <ide> <ide> if ( itemStats.isDirectory() ) { <ide> <ide> function handleRequest( request, response ) { <ide> <ide> http.createServer( handleRequest ).listen( port ); <ide> <del>require( 'dns' ).lookup( require( 'os' ).hostname(), function ( err, addr, fam ) { <add>require( 'dns' ).lookup( require( 'os' ).hostname(), function ( err, addr ) { <ide> <ide> console.log( 'Running at http://' + addr + ( ( port === 80 ) ? '' : ':' ) + port + '/' ); <ide>
1
Python
Python
get the bit at a given position
8d173438c38cb7d92f6daf2c0e3405067bf4166f
<ide><path>bit_manipulation/single_bit_manipulation_operations.py <ide> def is_bit_set(number: int, position: int) -> bool: <ide> return ((number >> position) & 1) == 1 <ide> <ide> <add>def get_bit(number: int, position: int) -> int: <add> """ <add> Get the bit at the given position <add> <add> Details: perform bitwise and for the given number and X, <add> Where X is a number with all the bits – zeroes and bit on given position – one. <add> If the result is not equal to 0, then the bit on the given position is 1, else 0. <add> <add> >>> get_bit(0b1010, 0) <add> 0 <add> >>> get_bit(0b1010, 1) <add> 1 <add> >>> get_bit(0b1010, 2) <add> 0 <add> >>> get_bit(0b1010, 3) <add> 1 <add> """ <add> return int((number & (1 << position)) != 0) <add> <add> <ide> if __name__ == "__main__": <ide> import doctest <ide>
1
Javascript
Javascript
force timezone to be utc for tests
cc79999a31b46e68a4dca5d536fc2fb4fe3d5199
<ide><path>client/jest-timezone-setup.js <add>module.exports = async () => { <add> process.env.TZ = 'UTC'; <add>}; <ide><path>client/jest.config.js <ide> module.exports = { <ide> globals: { <ide> __PATH_PREFIX__: '' <ide> }, <add> globalSetup: './jest-timezone-setup.js', <ide> verbose: true, <ide> transform: { <ide> '^.+\\.js$': '<rootDir>/jest.transform.js' <ide><path>client/jest.test.js <add>/* global expect */ <add>describe('Timezones', () => { <add> it('should always be UTC', () => { <add> expect(new Date().getTimezoneOffset()).toBe(0); <add> }); <add>});
3
PHP
PHP
fix seed method in foundation testcase
a8d35bf8fc44f2c73f4a58a6c32ab1edbdca85d6
<ide><path>src/Illuminate/Foundation/Testing/TestCase.php <ide> public function be(UserInterface $user, $driver = null) <ide> */ <ide> public function seed($class = 'DatabaseSeeder') <ide> { <del> $this->app['artisan']->call('seed', array('--class' => $class)); <add> $this->app['artisan']->call('db:seed', array('--class' => $class)); <ide> } <ide> <ide> /**
1
Text
Text
add document for http.outgoingmessage
53b673e92e851a4adae372fdc4945e174303996b
<ide><path>doc/api/http.md <ide> URL { <ide> } <ide> ``` <ide> <add>## Class: `http.OutgoingMessage` <add><!-- YAML <add>added: v0.1.17 <add>--> <add> <add>* Extends: {Stream} <add> <add>This class serves as the parent class of [`http.ClientRequest`][] <add>and [`http.ServerResponse`][]. It is an abstract of outgoing message from <add>the perspective of the participants of HTTP transaction. <add> <add>### Event: `drain` <add><!-- YAML <add>added: v0.3.6 <add>--> <add> <add>Emitted when the buffer of the message is free again. <add> <add>### Event: `finish` <add><!-- YAML <add>added: v0.1.17 <add>--> <add> <add>Emitted when transmission is finished successfully. <add> <add>### Event: `prefinish` <add><!-- YAML <add>added: v0.11.6 <add>--> <add> <add>Emitted when `outgoingMessage.end` was called. <add>When the event is emitted, all data has been processed but not necessarily <add>completely flushed. <add> <add>### `outgoingMessage.addTrailers(headers)` <add><!-- YAML <add>added: v0.3.0 <add>--> <add> <add>* `headers` {Object} <add> <add>Adds HTTP trailers (headers but at the end of the message) to the message. <add> <add>Trailers are **only** be emitted if the message is chunked encoded. If not, <add>trailer will be silently discarded. <add> <add>HTTP requires the `Trailer` header to be sent in order to emit trailers, <add>with a list of header fields in its value, e.g. <add> <add>```js <add>message.writeHead(200, { 'Content-Type': 'text/plain', <add> 'Trailer': 'Content-MD5' }); <add>message.write(fileData); <add>message.addTrailers({ 'Content-MD5': '7895bf4b8828b55ceaf47747b4bca667' }); <add>message.end(); <add>``` <add> <add>Attempting to set a header field name or value that contains invalid characters <add>will result in a `TypeError` being thrown. <add> <add>### `outgoingMessage.connection` <add><!-- YAML <add>added: v0.3.0 <add>deprecated: REPLACEME <add>--> <add> <add>> Stability: 0 - Deprecated: Use [`outgoingMessage.socket`][] instead. <add> <add>Aliases of `outgoingMessage.socket` <add>### `outgoingMessage.cork()` <add><!-- YAML <add>added: v14.0.0 <add>--> <add> <add>See [`writable.cork()`][]. <add> <add>### `outgoingMessage.destroy([error])` <add><!-- YAML <add>added: v0.3.0 <add>--> <add> <add>* `error` {Error} Optional, an error to emit with `error` event <add>* Returns: {this} <add> <add>Destroys the message. Once a socket is associated with the message <add>and is connected, that socket will be destroyed as well. <add> <add>### `outgoingMessage.end(chunk[, encoding][, callback])` <add><!-- YAML <add>added: v0.1.90 <add>changes: <add> - version: v0.11.6 <add> description: add `callback` argument. <add>--> <add> <add>* `chunk` {string | Buffer} <add>* `encoding` {string} Optional, **Default**: `utf-8` <add>* `callback` {Function} Optional <add>* Returns: {this} <add> <add>Finishes the outgoing message. If any parts of the body are unsent, it will <add>flush them to the underlying system. If the message is chunked, it will <add>send the terminating chunk `0\r\n\r\n`, and send the trailer (if any). <add> <add>If `chunk` is specified, it is equivalent to call <add>`outgoingMessage.write(chunk, encoding)`, followed by <add>`outgoingMessage.end(callback)`. <add> <add>If `callback` is provided, it will be called when the message is finished. <add>(equivalent to the callback to event `finish`) <add> <add>### `outgoingMessage.flushHeaders()` <add><!-- YAML <add>added: v1.6.0 <add>--> <add> <add>Compulsorily flushes the message headers <add> <add>For efficiency reason, Node.js normally buffers the message headers <add>until `outgoingMessage.end()` is called or the first chunk of message data <add>is written. It then tries to pack the headers and data into a single TCP <add>packet. <add> <add>It is usually desired (it saves a TCP round-trip), but not when the first <add>data is not sent until possibly much later. `outgoingMessage.flushHeaders()` <add>bypasses the optimization and kickstarts the request. <add> <add>### `outgoingMessage.getHeader(name)` <add><!-- YAML <add>added: v0.4.0 <add>--> <add> <add>* `name` {string} Name of header <add>* Returns {string | undefined} <add> <add>Gets value of HTTP header with given name. If such name doesn't exist in <add>message, it will be `undefined`. <add> <add>### `outgoingMessage.getHeaderNames()` <add><!-- YAML <add>added: v8.0.0 <add>--> <add> <add>* Returns {string[]} <add> <add>Returns an array of names of headers of the outgoing outgoingMessage. All <add>names are lowercase. <add> <add>### `outgoingMessage.getHeaders()` <add><!-- YAML <add>added: v8.0.0 <add>--> <add> <add>* Returns: {Object} <add> <add>Returns a shallow copy of the current outgoing headers. Since a shallow <add>copy is used, array values may be mutated without additional calls to <add>various header-related http module methods. The keys of the returned <add>object are the header names and the values are the respective header <add>values. All header names are lowercase. <add> <add>The object returned by the `outgoingMessage.getHeaders()` method does <add>not prototypically inherit from the JavaScript Object. This means that <add>typical Object methods such as `obj.toString()`, `obj.hasOwnProperty()`, <add>and others are not defined and will not work. <add> <add>```js <add>outgoingMessage.setHeader('Foo', 'bar'); <add>outgoingMessage.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']); <add> <add>const headers = outgoingMessage.getHeaders(); <add>// headers === { foo: 'bar', 'set-cookie': ['foo=bar', 'bar=baz'] } <add>``` <add> <add>### `outgoingMessage.hasHeader(name)` <add><!-- YAML <add>added: v8.0.0 <add>--> <add> <add>* `name` {string} <add>* Returns {boolean} <add> <add>Returns `true` if the header identified by `name` is currently set in the <add>outgoing headers. The header name is case-insensitive. <add> <add>```js <add>const hasContentType = outgoingMessage.hasHeader('content-type'); <add>``` <add> <add>### `outgoingMessage.headersSent` <add><!-- YAML <add>added: v0.9.3 <add>--> <add> <add>* {boolean} <add> <add>Read-only. `true` if the headers were sent, otherwise `false`. <add> <add>### `outgoingMessage.pipe()` <add><!-- YAML <add>added: v9.0.0 <add>--> <add> <add>Overrides the pipe method of legacy `Stream` which is the parent class of <add>`http.outgoingMessage`. <add> <add>Since `OutgoingMessage` should be a write-only stream, <add>call this function will throw an `Error`. Thus, it disabled the pipe method <add>it inherits from `Stream`. <add> <add>User should not call this function directly. <add> <add>### `outgoingMessage.removeHeader()` <add><!-- YAML <add>added: v0.4.0 <add>--> <add> <add>Removes a header that is queued for implicit sending. <add> <add>```js <add>outgoingMessage.removeHeader('Content-Encoding'); <add>``` <add> <add>### `outgoingMessage.setHeader(name, value)` <add><!-- YAML <add>added: v0.4.0 <add>--> <add> <add>* `name` {string} Header name <add>* `value` {string} Header value <add>* Returns: {this} <add> <add>Sets a single header value for header object. <add> <add>### `outgoingMessage.setTimeout(msesc[, callback])` <add><!-- YAML <add>added: v0.9.12 <add>--> <add> <add>* `msesc` {number} <add>* `callback` {Function} Optional function to be called when a timeout <add>occurs, Same as binding to the `timeout` event. <add>* Returns: {this} <add> <add>Once a socket is associated with the message and is connected, <add>[`socket.setTimeout()`][] will be called with `msecs` as the first parameter. <add> <add>### `outgoingMessage.socket` <add><!-- YAML <add>added: v0.3.0 <add>--> <add> <add>* {stream.Duplex} <add> <add>Reference to the underlying socket. Usually users will not want to access <add>this property. <add> <add>After calling `outgoingMessage.end()`, this property will be nulled. <add> <add>### `outgoingMessage.uncork()` <add><!-- YAML <add>added: v14.0.0 <add>--> <add> <add>See [`writable.uncork()`][] <add> <add>### `outgoingMessage.writableCorked` <add><!-- YAML <add>added: v14.0.0 <add>--> <add> <add>* {number} <add> <add>This `outgoingMessage.writableCorked` will return the time how many <add>`outgoingMessage.cork()` have been called. <add> <add>### `outgoingMessage.writableEnded` <add><!-- YAML <add>added: v13.0.0 <add>--> <add> <add>* {boolean} <add> <add>Readonly, `true` if `outgoingMessage.end()` has been called. Noted that <add>this property does not reflect whether the data has been flush. For that <add>purpose, use `message.writableFinished` instead. <add> <add>### `outgoingMessage.writableFinished` <add><!-- YAML <add>added: v13.0.0 <add>--> <add> <add>* {boolean} <add> <add>Readonly. `true` if all data has been flushed to the underlying system. <add> <add>### `outgoingMessage.writableHighWaterMark` <add><!-- YAML <add>added: v13.0.0 <add>--> <add> <add>* {number} <add> <add>This `outgoingMessage.writableHighWaterMark` will be the `highWaterMark` of <add>underlying socket if socket exists. Else, it would be the default <add>`highWaterMark`. <add> <add>`highWaterMark` is the maximum amount of data which can be potentially <add>buffered by socket. <add> <add>### `outgoingMessage.writableLength` <add><!-- YAML <add>added: v13.0.0 <add>--> <add> <add>* {number} <add> <add>Readonly, This `outgoingMessage.writableLength` contains the number of <add>bytes (or objects) in the buffer ready to send. <add> <add>### `outgoingMessage.writableObjectMode` <add><!-- YAML <add>added: v13.0.0 <add>--> <add> <add>* {boolean} <add> <add>Readonly, always returns `false`. <add> <add>### `outgoingMessage.write(chunk[, encoding][, callback])` <add><!-- YAML <add>added: v0.1.29 <add>changes: <add> - version: v0.11.6 <add> description: add `callback` argument. <add>--> <add> <add>* `chunk` {string | Buffer} <add>* `encoding` {string} **Default**: `utf-8` <add>* `callback` {Function} <add>* Returns {boolean} <add> <add>If this method is called and header is not sent, it will call <add>`this._implicitHeader` to flush implicit header. <add>If the message should not have a body (indicated by `this._hasBody`), <add>the call is ignored and `chunk` will not be sent. It could be useful <add>when handling particular message which must not include a body. <add>e.g. response to `HEAD` request, `204` and `304` response. <add> <add>`chunk` can be a string or a buffer. When `chunk` is a string, the <add>`encoding` parameter specifies how to encode `chunk` into a byte stream. <add>`callback` will be called when the `chunk` is flushed. <add> <add>If the message is transferred in chucked encoding <add>(indicated by `this.chunkedEncoding`), `chunk` will be flushed as <add>one chunk among a stream of chunks. Otherwise, it will be flushed as body <add>of message. <add> <add>This method handles the raw body of HTTP message and has nothing to do with <add>higher-level multi-part body encodings that may be used. <add> <add>If it is the first call to this method of a message, it will send the <add>buffered header first, then flush the the `chunk` as described above. <add> <add>The second and successive calls to this method, it will assume the data <add>will streamed and send the new data separately. It means that the response <add>is buffered up to the first chunk of the body. <add> <add>Returns `true` if the entire data was flushed successfully to the kernel <add>buffer. Returns `false` if all or part of the data was queued in user <add>memory. Event `drain` will be emitted when the buffer is free again. <add> <ide> ## `http.METHODS` <ide> <!-- YAML <ide> added: v0.11.8 <ide> try { <ide> [`http.ClientRequest`]: #http_class_http_clientrequest <ide> [`http.IncomingMessage`]: #http_class_http_incomingmessage <ide> [`http.Server`]: #http_class_http_server <add>[`http.ServerResponse`]: #http_class_http_serverresponse <ide> [`http.get()`]: #http_http_get_options_callback <ide> [`http.globalAgent`]: #http_http_globalagent <ide> [`http.request()`]: #http_http_request_options_callback <ide> try { <ide> [`net.createConnection()`]: net.md#net_net_createconnection_options_connectlistener <ide> [`new URL()`]: url.md#url_new_url_input_base <ide> [`message.socket`]: #http_message_socket <add>[`outgoingMessage.socket`]: #http_outgoingMessage.socket <ide> [`removeHeader(name)`]: #http_request_removeheader_name <ide> [`request.end()`]: #http_request_end_data_encoding_callback <ide> [`request.destroy()`]: #http_request_destroy_error
1