问:
Url.Action is throwing error CS1026: ) expected
This is hopefully just a syntax error as I'm new to MVC and trying to edit something that already exists without having much experience. Having spent ages trying different syntax I'm obviously missing something.

My issue is that I have this:

```<code>var url = '<%= Url.Action("List") %>?page=' + pageNo;
</code>```

which is fine, but its not passing in all the required parameters as part of pager functionality.

What I want to use is something like:

```<code>var url = '<%= Html.RenderAction("List",
               "PlacementAgreementAgencyPlacementAgreementsPlacement",
               new { Domain = "Placement",
                     Id = Model.Item.PlacementAgreement.PlacementAgreementId,
                     agencyPlacementAgreementId = Model.Item.AgencyPlacementAgreementId,
                     Page = Model.PageNo
                });
           %>';
</code>```

But it always complains about error CS1026: ) expected

Same with trying

```<code><%= Url.Action("List", "PlacementAgreementAgencyPlacementAgreementsPlacement",
        new { Domain = "Placement",
              Id = ViewData.Model.AgencyPlacementAgreement.PlacementAgreement.PlacementAgreementId,
              agencyPlacementAgreementId = ViewData.Model.AgencyPlacementAgreement.AgencyPlacementAgreementId,
              Page = Model.PageNo }
    )%>
</code>```

If someone could point out what I'm doing wrong that would be great.  Basically I'm trying to call controller PlacementAgreementAgencyPlacementAgreementsPlacement with action List passing in all parameters Id, agencyPlacementAgreementId and Page.  It's being done in javascript so that I can use this:

```<code>    function loadAgreementPlacementPage(pageNo) {

        var url = '<%= Url.Action("List") %>?page=' + pageNo;
        $.get(url, function(data) {
            $("#agreementplacement_list_holder").html(data);
        });
</code>```

Thanks!!!

PS. Using MVC 1.0.

答:
It should be:

```<code>var url = '<%= Url.Action(
               "List",
               "PlacementAgreementAgencyPlacementAgreementsPlacement",
               new {
                   Domain = "Placement",
                   Id = Model.Item.PlacementAgreement.PlacementAgreementId,
                   agencyPlacementAgreementId = Model.Item.AgencyPlacementAgreementId,
                   Page = Model.PageNo
               }) %>';
</code>```

Use Url.Action instead of Html.RenderAction and remove the semicolon at the end.

Body:
This is hopefully just a syntax error as I'm new to MVC and trying to edit something that already exists without having much experience. Having spent ages trying different syntax I'm obviously missing something.

My issue is that I have this:

var url = '<%= Url.Action("List") %>?page=' + pageNo;

which is fine, but its not passing in all the required parameters as part of pager functionality.

What I want to use is something like:

var url = '<%= Html.RenderAction("List",
               "PlacementAgreementAgencyPlacementAgreementsPlacement",
               new { Domain = "Placement",
                     Id = Model.Item.PlacementAgreement.PlacementAgreementId,
                     agencyPlacementAgreementId = Model.Item.AgencyPlacementAgreementId,
                     Page = Model.PageNo
                });
           %>';

But it always complains about error CS1026: ) expected

Same with trying

<%= Url.Action("List", "PlacementAgreementAgencyPlacementAgreementsPlacement",
        new { Domain = "Placement",
              Id = ViewData.Model.AgencyPlacementAgreement.PlacementAgreement.PlacementAgreementId,
              agencyPlacementAgreementId = ViewData.Model.AgencyPlacementAgreement.AgencyPlacementAgreementId,
              Page = Model.PageNo }
    )%>

If someone could point out what I'm doing wrong that would be great.  Basically I'm trying to call controller PlacementAgreementAgencyPlacementAgreementsPlacement with action List passing in all parameters Id, agencyPlacementAgreementId and Page.  It's being done in javascript so that I can use this:

    function loadAgreementPlacementPage(pageNo) {

        var url = '<%= Url.Action("List") %>?page=' + pageNo;
        $.get(url, function(data) {
            $("#agreementplacement_list_holder").html(data);
        });

Thanks!!!

PS. Using MVC 1.0.

Body:
It should be:

var url = '<%= Url.Action(
               "List",
               "PlacementAgreementAgencyPlacementAgreementsPlacement",
               new {
                   Domain = "Placement",
                   Id = Model.Item.PlacementAgreement.PlacementAgreementId,
                   agencyPlacementAgreementId = Model.Item.AgencyPlacementAgreementId,
                   Page = Model.PageNo
               }) %>';

Use Url.Action instead of Html.RenderAction and remove the semicolon at the end.


来源: stackexchange

问:
Visual studio keyboard shortcut to go to end of line in Windows
I'm using visual studio community 2017. I want to remap the keyboard shortcut that moves the caret to the end of line (since I'm working on a laptop without the "End" key).

I know how to remap visual studio keys, but I can't find the menu item for it. Do you know what is the menu/action name for it so I can change it?

I can't find the answer on the web though it was asked several times.

答: I've tried to do something similar with key mappings in Visual Studio before, and I couldn't find any options. What I ended up using was AutoHotkey, and with it you can set up a key bind really quickly. Hope this helps!</p>

ContentLicense: CC BY-SA 4.0

ContentLicense: CC BY-SA 3.0


问:
localStorage as a service
Using angular 2. I am implementing a local storage service (with encryption). Currently, it's just my one module that's using it but I want to ensure it's reusable.

This is my page's .ts:

I'm providing a storage prefix. I'm assuming it should have an indication of what app it's associated with, so it's pre-prefixed with myApp-, followed by a prefix that would be unique to this module (Frequentclients).

```<code>export class SwitchClientComponent implements OnInit {

    storagePrefix = 'myApp-Frequentclients';

    getFrequentClients() {
        return this.encryptionService.getLocalStorage(this.storagePrefix);
    };
}
</code>```

My encrypted storage service:

```<code>import * as CryptoJS from "crypto-js";

@Injectable()
export class EncryptionService {

    constructor() {
    }

    secretKey: string = "fnord";

    setLocalStorage(storagePrefix: string, jsonObj) {
        localStorage.setItem(storagePrefix, this.encrypt(jsonObj));
    }

getLocalStorage(storagePrefix: string) {
    var recentClients = [],
        data: string = localStorage.getItem(storagePrefix);

    if (data !== null && data.length > 0) {
        data = this.decrypt(data);
        if (data !== null && data.length > 0) {
            recentClients = JSON.parse(data) || [];
        }
    }
    return recentClients;
}

encrypt(jsonObj) {
    return CryptoJS.AES.encrypt(JSON.stringify(jsonObj), this.secretKey);
}

decrypt(data) {
    if (data !== null && data.length > 0) {
        var bytes = CryptoJS.AES.decrypt(data.toString(), this.secretKey);
        return bytes.toString(CryptoJS.enc.Utf8);
    } else {
        return "";
    }
}
</code>```

If every module that used local storage just used the same prefix, they'd clobber each other, right?

So each use will have it's own, thus:

```<code>myApp-DavesModuleData : [{data:'foo'}]
myApp-OtherModuleData : [{data:'bar'}]
</code>```

Or, should I eschew littering the user's storage with a zillion local storage files, and just use one?

```<code>myApp : [{DavesModule:{data:'foo'}},{OtherModule:{data:'bar'}}]
</code>```

Then I'd have to read the entire thing every time local storage is read and then parse it to find the section I'm looking for - AND write it all back again.

(That means, if any module messes up its data, it potentially brings every other use of the local storage to a screeching halt - including loss-of-stored-data).

BTW, I'm using angular 2 native local storage. Now that I'm encountering these challenges, I'm beginning to wonder if perhaps someone has already written a plugin that does sophisticated local storage management.

答:
There's not a clear question here but i'll try to guess what is the answer that you want :)

Yes it is much better to reduce the amount of data that you will need to read from the localStorage by having different "modules" using different entries in the LS. For three main reasons:

Reading the local storage is a syncronous operation so it will block your code execution until is not finished

Reading/writing the local storage is one of the slower operations you can do in javascript.

Saving/retrieving data from the localstorage requires that you stringify/parse those data which is another one of the slower operations you can do in javascript.

I would tell you to read this and then this article about up to date localStorage performances.

Also note there are no "localStorage files" there's only one object in the browser so you can create as many entries as you want without performance loss, actually all the opposite.

As you said yes, if you store everything into one entry a single bad formatted data can make all the others objects unreacheable.

Title: localStorage as a service

Body:
Using angular 2. I am implementing a local storage service (with encryption). Currently, it's just my one module that's using it but I want to ensure it's reusable.

This is my page's .ts:

I'm providing a storage prefix. I'm assuming it should have an indication of what app it's associated with, so it's pre-prefixed with myApp-, followed by a prefix that would be unique to this module (Frequentclients).

export class SwitchClientComponent implements OnInit {

    storagePrefix = 'myApp-Frequentclients';

    getFrequentClients() {
        return this.encryptionService.getLocalStorage(this.storagePrefix);
    };
}

My encrypted storage service:

import * as CryptoJS from "crypto-js";

@Injectable()
export class EncryptionService {

    constructor() {
    }

    secretKey: string = "fnord";

    setLocalStorage(storagePrefix: string, jsonObj) {
        localStorage.setItem(storagePrefix, this.encrypt(jsonObj));
    }

getLocalStorage(storagePrefix: string) {
    var recentClients = [],
        data: string = localStorage.getItem(storagePrefix);

    if (data !== null && data.length > 0) {
        data = this.decrypt(data);
        if (data !== null && data.length > 0) {
            recentClients = JSON.parse(data) || [];
        }
    }
    return recentClients;
}

encrypt(jsonObj) {
    return CryptoJS.AES.encrypt(JSON.stringify(jsonObj), this.secretKey);
}

decrypt(data) {
    if (data !== null && data.length > 0) {
        var bytes = CryptoJS.AES.decrypt(data.toString(), this.secretKey);
        return bytes.toString(CryptoJS.enc.Utf8);
    } else {
        return "";
    }
}

If every module that used local storage just used the same prefix, they'd clobber each other, right?

So each use will have it's own, thus:

myApp-DavesModuleData : [{data:'foo'}]
myApp-OtherModuleData : [{data:'bar'}]

Or, should I eschew littering the user's storage with a zillion local storage files, and just use one?

myApp : [{DavesModule:{data:'foo'}},{OtherModule:{data:'bar'}}]

Then I'd have to read the entire thing every time local storage is read and then parse it to find the section I'm looking for - AND write it all back again.

(That means, if any module messes up its data, it potentially brings every other use of the local storage to a screeching halt - including loss-of-stored-data).

BTW, I'm using angular 2 native local storage. Now that I'm encountering these challenges, I'm beginning to wonder if perhaps someone has already written a plugin that does sophisticated local storage management.


问:
Facebook share not working(using direct uri)
I am trying to create an fb share button in my website.
When user clicks on button(fb image) it gets redirected to http://www.facebook.com/sharer.php?u=.
 I m setting url as location.href dynamically through js
url is encoded automatically and when i click on button i see http://www.facebook.com/sharer.php?u=http%3A%2F%2F ...
url has a parameter x. it is in the form http://website.com/?x=
after clicking i get facebook error saying this page isn't working. Unable to handle this request.

i tried encoding location.href through js (encodeURIComponent function) but still it doesn't get affected.

There are ways through fb sdk but i am trying the simpler way.
I am using same on twitter and its working fine. (Twitter url is http://www.twitter.com/intent/tweet?text=).
After searching on internet i am unable to come up with any solution yet.

Also tried opening http://www.facebook.com/sharer.php?u= and putting url manually. Still i get the error.

答:
There was no error in setup. But adding additional  tag for og:url which pointed to incorrect url was the problem.
Removing meta tag worked.</p>


问:
How to simulate process delay in NS-3/ndnSIM?
I want to add some process delay on a consumer node before Interest packets being sent out. And I find that Simulator::Schedule() functions may achieve this purpose. But I am not sure how to use it exactly because ndnSIM has its own protocol process and if I schedule a new event it may cause some unexpected results. Or is there some other way to insert a delay on a node in NS-3?</p>

答:
AFAIK, the way to introduce processing delay is with Simulator::Schedule().
In your example you mention you want to delay the send of an Interest packet. Instead of calling the method directly, you can schedule it after some (randon) time, ie. your process delay. This should not break the simulation.


问:
close gaps between back button and icon in android
I have added a back button and icon to my android action bar. There appears to be much gaps between the back button and the icon as shown in the image below

this is the code snipet I am using to arrive at the above

```<code>getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
        getSupportActionBar().setLogo(R.mipmap.ic_launcher);
        getSupportActionBar().setDisplayUseLogoEnabled(true);
</code>```

Please how can I close the gaps between the back button and launcher

答:
Make following changes in tool xml

```<code><android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:titleTextAppearance="@style/Toolbar.TitleText"
        app:popupTheme="@style/AppTheme.PopupOverlay"
        app:contentInsetLeft="0dp"
        app:contentInsetStart="0dp"
        app:contentInsetStartWithNavigation="0dp" />
</code>```

Since you aren't using toolbar in xml. You will have to create your own style which will have parent as current theme. I can't tell you how exactly since i don't know which theme you are using. Here is an example

```<code><style name="myToolbar" parent="Theme.AppCompat.Light.DarkActionBar">
    <item name="android:contentInsetLeft">0dp</item>
    <item name="android:contentInsetStart">0dp</item>
    <item name="android:contentInsetStartWithNavigation">0dp</item>
  </style>
</code>```

Then i will use myToolbar theme in application tag in manifest. I hope this will help you.

Body:
I have added a back button and icon to my android action bar. There appears to be much gaps between the back button and the icon as shown in the image below

this is the code snipet I am using to arrive at the above

getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
        getSupportActionBar().setLogo(R.mipmap.ic_launcher);
        getSupportActionBar().setDisplayUseLogoEnabled(true);

Please how can I close the gaps between the back button and launcher

Body:
Make following changes in tool xml

<android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:titleTextAppearance="@style/Toolbar.TitleText"
        app:popupTheme="@style/AppTheme.PopupOverlay"
        app:contentInsetLeft="0dp"
        app:contentInsetStart="0dp"
        app:contentInsetStartWithNavigation="0dp" />

Since you aren't using toolbar in xml. You will have to create your own style which will have parent as current theme. I can't tell you how exactly since i don't know which theme you are using. Here is an example

<style name="myToolbar" parent="Theme.AppCompat.Light.DarkActionBar">
    <item name="android:contentInsetLeft">0dp</item>
    <item name="android:contentInsetStart">0dp</item>
    <item name="android:contentInsetStartWithNavigation">0dp</item>
  </style>

Then i will use myToolbar theme in application tag in manifest. I hope this will help you.


问:
getUserMedia and WEBUSB over the same device Windows
We are developing a project based on Chrome (old USB API now migrating to WEBUSB) and a webcam. The USB Webcam has a button used for taking picture. In MAC and Linux I can show the live video of the webcam using getUserMedia () and on the same time I can use Web USB API to communicate with the device for detecting button press.
The problem is windows. On Windows Chorme can see the USB device as a Webcam accessible from getUserMedia (if I install the usb device original driver) or as USB device accessible form WebUSB (if I replace the original driver with WINUSB) but we are unable to use the two API toghether. This is a problem only on WINDOWS, in Mac or Linux all is working. How can we solve this?

N.B.
To make the javascript USB commands work on linux and OSX I had to replace "interface" with "endpoint" in transfer commands.

Linux lsusb dump:

```<code>Bus 001 Device 008: ID a168:0872 AnMo Electronics Corporation
Device Descriptor:
  bLength                18
  bDescriptorType         1
  bcdUSB               2.00
  bDeviceClass          239 Miscellaneous Device
  bDeviceSubClass         2
  bDeviceProtocol         1 Interface Association
  bMaxPacketSize0        64
  idVendor           0xa168 AnMo Electronics Corporation
  idProduct          0x0872
  bcdDevice           20.01
  iManufacturer           1 ANMO Electronics Corporation
  iProduct                2 Dino-Lite Premier
  iSerial                 3
  bNumConfigurations      1
  Configuration Descriptor:
    bLength                 9
    bDescriptorType         2
    wTotalLength          509
    bNumInterfaces          2
    bConfigurationValue     1
    iConfiguration          0
    bmAttributes         0x80
      (Bus Powered)
    MaxPower              500mA
    Interface Association:
      bLength                 8
      bDescriptorType        11
      bFirstInterface         0
      bInterfaceCount         2
      bFunctionClass         14 Video
      bFunctionSubClass       3 Video Interface Collection
      bFunctionProtocol       0
      iFunction               2 Dino-Lite Premier
    Interface Descriptor:
      bLength                 9
      bDescriptorType         4
      bInterfaceNumber        0
      bAlternateSetting       0
      bNumEndpoints           1
      bInterfaceClass        14 Video
      bInterfaceSubClass      1 Video Control
      bInterfaceProtocol      0
      iInterface              2 Dino-Lite Premier
      VideoControl Interface Descriptor:
        bLength                13
        bDescriptorType        36
        bDescriptorSubtype      1 (HEADER)
        bcdUVC               1.00
        wTotalLength           80
        dwClockFrequency        6.000000MHz
        bInCollection           1
        baInterfaceNr( 0)       1
      VideoControl Interface Descriptor:
        bLength                18
        bDescriptorType        36
        bDescriptorSubtype      2 (INPUT_TERMINAL)
        bTerminalID             1
        wTerminalType      0x0201 Camera Sensor
        bAssocTerminal          0
        iTerminal               0
        wObjectiveFocalLengthMin      0
        wObjectiveFocalLengthMax      0
        wOcularFocalLength            0
        bControlSize                  3
        bmControls           0x000200a2
          Auto-Exposure Mode
          Focus (Absolute)
          Iris (Absolute)
          Focus, Auto
      VideoControl Interface Descriptor:
        bLength                11
        bDescriptorType        36
        bDescriptorSubtype      5 (PROCESSING_UNIT)
      Warning: Descriptor too short
        bUnitID                 3
        bSourceID               1
        wMaxMultiplier          0
        bControlSize            2
        bmControls     0x0000147f
          Brightness
          Contrast
          Hue
          Saturation
          Sharpness
          Gamma
          White Balance Temperature
          Power Line Frequency
          White Balance Temperature, Auto
        iProcessing             0
        bmVideoStandards     0x1d
          None
          PAL - 625/50
          SECAM - 625/50
          NTSC - 625/50
      VideoControl Interface Descriptor:
        bLength                29
        bDescriptorType        36
        bDescriptorSubtype      6 (EXTENSION_UNIT)
        bUnitID                 4
        guidExtensionCode         {2652215a-8932-5641-894a-5c557cdf9664}
        bNumControl            16
        bNrPins                 1
        baSourceID( 0)          3
        bControlSize            4
        bmControls( 0)       0xff
        bmControls( 1)       0xff
        bmControls( 2)       0xff
        bmControls( 3)       0xff
        iExtension              0
      VideoControl Interface Descriptor:
        bLength                 9
        bDescriptorType        36
        bDescriptorSubtype      3 (OUTPUT_TERMINAL)
        bTerminalID             2
        wTerminalType      0x0101 USB Streaming
        bAssocTerminal          0
        bSourceID               4
        iTerminal               0
      Endpoint Descriptor:
        bLength                 7
        bDescriptorType         5
        bEndpointAddress     0x81  EP 1 IN
        bmAttributes            3
          Transfer Type            Interrupt
          Synch Type               None
          Usage Type               Data
        wMaxPacketSize     0x0008  1x 8 bytes
        bInterval               9
    Interface Descriptor:
      bLength                 9
      bDescriptorType         4
      bInterfaceNumber        1
      bAlternateSetting       0
      bNumEndpoints           1
      bInterfaceClass        14 Video
      bInterfaceSubClass      2 Video Streaming
      bInterfaceProtocol      0
      iInterface              0
      Endpoint Descriptor:
        bLength                 7
        bDescriptorType         5
        bEndpointAddress     0x82  EP 2 IN
        bmAttributes            5
          Transfer Type            Isochronous
          Synch Type               Asynchronous
          Usage Type               Data
        wMaxPacketSize     0x0000  1x 0 bytes
        bInterval               1
        INTERFACE CLASS:  0f 24 01 02 67 01 82 00 02 01 01 00 01 00 00
        INTERFACE CLASS:  0b 24 06 01 05 00 01 00 00 00 00
        INTERFACE CLASS:  1e 24 07 01 00 80 02 e0 01 00 00 08 ca 00 00 08 ca 00 60 09 00 15 16 05 00 01 15 16 05 00
        INTERFACE CLASS:  1e 24 07 02 00 40 01 f0 00 80 00 02 32 80 00 02 32 00 58 02 00 15 16 05 00 01 15 16 05 00
        INTERFACE CLASS:  1e 24 07 03 00 a0 00 78 00 a0 00 00 8c a0 00 00 8c 00 96 00 00 15 16 05 00 01 15 16 05 00
        INTERFACE CLASS:  1e 24 07 04 00 00 05 00 04 00 00 19 00 00 00 19 00 00 00 28 00 20 a1 07 00 01 20 a1 07 00
        INTERFACE CLASS:  1e 24 07 01 00 80 02 e0 01 00 00 08 ca 00 00 08 ca 00 60 09 00 15 16 05 00 01 15 16 05 00
        INTERFACE CLASS:  1b 24 04 02 05 59 55 59 32 00 00 10 00 80 00 00 aa 00 38 9b 71 10 01 00 00 00 00
        INTERFACE CLASS:  1e 24 05 01 00 80 02 e0 01 00 00 08 ca 00 00 08 ca 00 60 09 00 15 16 05 00 01 15 16 05 00
        INTERFACE CLASS:  1e 24 05 02 00 40 01 f0 00 80 00 02 32 80 00 02 32 00 58 02 00 15 16 05 00 01 15 16 05 00
        INTERFACE CLASS:  1e 24 05 03 00 a0 00 78 00 a0 00 00 8c a0 00 00 8c 00 96 00 00 15 16 05 00 01 15 16 05 00
        INTERFACE CLASS:  1e 24 05 04 00 00 05 00 04 00 00 19 00 00 00 19 00 00 00 28 00 20 a1 07 00 01 20 a1 07 00
        INTERFACE CLASS:  1e 24 05 01 00 80 02 e0 01 00 00 08 ca 00 00 08 ca 00 60 09 00 15 16 05 00 01 15 16 05 00
        INTERFACE CLASS:  06 24 0d 00 00 00
    Interface Descriptor:
      bLength                 9
      bDescriptorType         4
      bInterfaceNumber        1
      bAlternateSetting       1
      bNumEndpoints           1
      bInterfaceClass        14 Video
      bInterfaceSubClass      2 Video Streaming
      bInterfaceProtocol      0
      iInterface              0
      Endpoint Descriptor:
        bLength                 7
        bDescriptorType         5
        bEndpointAddress     0x82  EP 2 IN
        bmAttributes            5
          Transfer Type            Isochronous
          Synch Type               Asynchronous
          Usage Type               Data
        wMaxPacketSize     0x13fc  3x 1020 bytes
        bInterval               1
Device Qualifier (for other device speed):
  bLength                10
  bDescriptorType         6
  bcdUSB               2.00
  bDeviceClass          239 Miscellaneous Device
  bDeviceSubClass         2
  bDeviceProtocol         1 Interface Association
  bMaxPacketSize0        64
  bNumConfigurations      1
can't get debug descriptor: Resource temporarily unavailable
Device Status:     0x0000
  (Bus Powered)
</code>```

答:
Based on the output from lsusb -v above I can see that this device has a single function comprised of two USB interfaces. The Interface Association Descriptor (IAD) signals to the host operating system that these two interfaces are related and operating systems like Windows will treat them as a single interface for the purposes of driver binding.

My guess is that on Linux and macOS you are able to communicate with the EP 1 IN endpoint because only interface 1 is claimed by the USB video class (UVC) driver. On Windows, since it considers both interfaces a single entity "function 0", you are unable to claim interface 0 because interface 1 is already claimed as part of function 0.

Body:
We are developing a project based on Chrome (old USB API now migrating to WEBUSB) and a webcam. The USB Webcam has a button used for taking picture. In MAC and Linux I can show the live video of the webcam using getUserMedia () and on the same time I can use Web USB API to communicate with the device for detecting button press.
The problem is windows. On Windows Chorme can see the USB device as a Webcam accessible from getUserMedia (if I install the usb device original driver) or as USB device accessible form WebUSB (if I replace the original driver with WINUSB) but we are unable to use the two API toghether. This is a problem only on WINDOWS, in Mac or Linux all is working. How can we solve this?

N.B.
To make the javascript USB commands work on linux and OSX I had to replace "interface" with "endpoint" in transfer commands.

Linux lsusb dump:

Bus 001 Device 008: ID a168:0872 AnMo Electronics Corporation
Device Descriptor:
  bLength                18
  bDescriptorType         1
  bcdUSB               2.00
  bDeviceClass          239 Miscellaneous Device
  bDeviceSubClass         2
  bDeviceProtocol         1 Interface Association
  bMaxPacketSize0        64
  idVendor           0xa168 AnMo Electronics Corporation
  idProduct          0x0872
  bcdDevice           20.01
  iManufacturer           1 ANMO Electronics Corporation
  iProduct                2 Dino-Lite Premier
  iSerial                 3
  bNumConfigurations      1
  Configuration Descriptor:
    bLength                 9
    bDescriptorType         2
    wTotalLength          509
    bNumInterfaces          2
    bConfigurationValue     1
    iConfiguration          0
    bmAttributes         0x80
      (Bus Powered)
    MaxPower              500mA
    Interface Association:
      bLength                 8
      bDescriptorType        11
      bFirstInterface         0
      bInterfaceCount         2
      bFunctionClass         14 Video
      bFunctionSubClass       3 Video Interface Collection
      bFunctionProtocol       0
      iFunction               2 Dino-Lite Premier
    Interface Descriptor:
      bLength                 9
      bDescriptorType         4
      bInterfaceNumber        0
      bAlternateSetting       0
      bNumEndpoints           1
      bInterfaceClass        14 Video
      bInterfaceSubClass      1 Video Control
      bInterfaceProtocol      0
      iInterface              2 Dino-Lite Premier
      VideoControl Interface Descriptor:
        bLength                13
        bDescriptorType        36
        bDescriptorSubtype      1 (HEADER)
        bcdUVC               1.00
        wTotalLength           80
        dwClockFrequency        6.000000MHz
        bInCollection           1
        baInterfaceNr( 0)       1
      VideoControl Interface Descriptor:
        bLength                18
        bDescriptorType        36
        bDescriptorSubtype      2 (INPUT_TERMINAL)
        bTerminalID             1
        wTerminalType      0x0201 Camera Sensor
        bAssocTerminal          0
        iTerminal               0
        wObjectiveFocalLengthMin      0
        wObjectiveFocalLengthMax      0
        wOcularFocalLength            0
        bControlSize                  3
        bmControls           0x000200a2
          Auto-Exposure Mode
          Focus (Absolute)
          Iris (Absolute)
          Focus, Auto
      VideoControl Interface Descriptor:
        bLength                11
        bDescriptorType        36
        bDescriptorSubtype      5 (PROCESSING_UNIT)
      Warning: Descriptor too short
        bUnitID                 3
        bSourceID               1
        wMaxMultiplier          0
        bControlSize            2
        bmControls     0x0000147f
          Brightness
          Contrast
          Hue
          Saturation
          Sharpness
          Gamma
          White Balance Temperature
          Power Line Frequency
          White Balance Temperature, Auto
        iProcessing             0
        bmVideoStandards     0x1d
          None
          PAL - 625/50
          SECAM - 625/50
          NTSC - 625/50
      VideoControl Interface Descriptor:
        bLength                29
        bDescriptorType        36
        bDescriptorSubtype      6 (EXTENSION_UNIT)
        bUnitID                 4
        guidExtensionCode         {2652215a-8932-5641-894a-5c557cdf9664}
        bNumControl            16
        bNrPins                 1
        baSourceID( 0)          3
        bControlSize            4
        bmControls( 0)       0xff
        bmControls( 1)       0xff
        bmControls( 2)       0xff
        bmControls( 3)       0xff
        iExtension              0
      VideoControl Interface Descriptor:
        bLength                 9
        bDescriptorType        36
        bDescriptorSubtype      3 (OUTPUT_TERMINAL)
        bTerminalID             2
        wTerminalType      0x0101 USB Streaming
        bAssocTerminal          0
        bSourceID               4
        iTerminal               0
      Endpoint Descriptor:
        bLength                 7
        bDescriptorType         5
        bEndpointAddress     0x81  EP 1 IN
        bmAttributes            3
          Transfer Type            Interrupt
          Synch Type               None
          Usage Type               Data
        wMaxPacketSize     0x0008  1x 8 bytes
        bInterval               9
    Interface Descriptor:
      bLength                 9
      bDescriptorType         4
      bInterfaceNumber        1
      bAlternateSetting       0
      bNumEndpoints           1
      bInterfaceClass        14 Video
      bInterfaceSubClass      2 Video Streaming
      bInterfaceProtocol      0
      iInterface              0
      Endpoint Descriptor:
        bLength                 7
        bDescriptorType         5
        bEndpointAddress     0x82  EP 2 IN
        bmAttributes            5
          Transfer Type            Isochronous
          Synch Type               Asynchronous
          Usage Type               Data
        wMaxPacketSize     0x0000  1x 0 bytes
        bInterval               1
        INTERFACE CLASS:  0f 24 01 02 67 01 82 00 02 01 01 00 01 00 00
        INTERFACE CLASS:  0b 24 06 01 05 00 01 00 00 00 00
        INTERFACE CLASS:  1e 24 07 01 00 80 02 e0 01 00 00 08 ca 00 00 08 ca 00 60 09 00 15 16 05 00 01 15 16 05 00
        INTERFACE CLASS:  1e 24 07 02 00 40 01 f0 00 80 00 02 32 80 00 02 32 00 58 02 00 15 16 05 00 01 15 16 05 00
        INTERFACE CLASS:  1e 24 07 03 00 a0 00 78 00 a0 00 00 8c a0 00 00 8c 00 96 00 00 15 16 05 00 01 15 16 05 00
        INTERFACE CLASS:  1e 24 07 04 00 00 05 00 04 00 00 19 00 00 00 19 00 00 00 28 00 20 a1 07 00 01 20 a1 07 00
        INTERFACE CLASS:  1e 24 07 01 00 80 02 e0 01 00 00 08 ca 00 00 08 ca 00 60 09 00 15 16 05 00 01 15 16 05 00
        INTERFACE CLASS:  1b 24 04 02 05 59 55 59 32 00 00 10 00 80 00 00 aa 00 38 9b 71 10 01 00 00 00 00
        INTERFACE CLASS:  1e 24 05 01 00 80 02 e0 01 00 00 08 ca 00 00 08 ca 00 60 09 00 15 16 05 00 01 15 16 05 00
        INTERFACE CLASS:  1e 24 05 02 00 40 01 f0 00 80 00 02 32 80 00 02 32 00 58 02 00 15 16 05 00 01 15 16 05 00
        INTERFACE CLASS:  1e 24 05 03 00 a0 00 78 00 a0 00 00 8c a0 00 00 8c 00 96 00 00 15 16 05 00 01 15 16 05 00
        INTERFACE CLASS:  1e 24 05 04 00 00 05 00 04 00 00 19 00 00 00 19 00 00 00 28 00 20 a1 07 00 01 20 a1 07 00
        INTERFACE CLASS:  1e 24 05 01 00 80 02 e0 01 00 00 08 ca 00 00 08 ca 00 60 09 00 15 16 05 00 01 15 16 05 00
        INTERFACE CLASS:  06 24 0d 00 00 00
    Interface Descriptor:
      bLength                 9
      bDescriptorType         4
      bInterfaceNumber        1
      bAlternateSetting       1
      bNumEndpoints           1
      bInterfaceClass        14 Video
      bInterfaceSubClass      2 Video Streaming
      bInterfaceProtocol      0
      iInterface              0
      Endpoint Descriptor:
        bLength                 7
        bDescriptorType         5
        bEndpointAddress     0x82  EP 2 IN
        bmAttributes            5
          Transfer Type            Isochronous
          Synch Type               Asynchronous
          Usage Type               Data
        wMaxPacketSize     0x13fc  3x 1020 bytes
        bInterval               1
Device Qualifier (for other device speed):
  bLength                10
  bDescriptorType         6
  bcdUSB               2.00
  bDeviceClass          239 Miscellaneous Device
  bDeviceSubClass         2
  bDeviceProtocol         1 Interface Association
  bMaxPacketSize0        64
  bNumConfigurations      1
can't get debug descriptor: Resource temporarily unavailable
Device Status:     0x0000
  (Bus Powered)


问:
Retrieve real IP of user using codeigniter
My app tracks the IP address of users logging into the site. The tracking was working fine on a regular web server (we were on hostgator) but seemed to start tracking odd IP addresses when we switch to a PaaS platform (pagodabox) After speaking to pagodabox support they informed me that the IPs codeigniter was picking up was the IPs of the load balancers/routers of pagodabox and to get a user's actual IP address I would have to utilize HTTP_X_FORWARDED_FOR

I was using codeigniter's input class function $this->input->ip_address() to retreive the user's IP. I looked at the function and noticed they had some sort of features to retreive the  HTTP_X_FORWARDED_FOR IP value but I am not sure how to use it. Do i have to change/add something  in the config?

EDIT: After a few users have pointed out where I should add in the list of IP addresses of load balancers a new question came up: What would I do if the list of IP's change frequently? (ie no static IP, all dynamic)

答:
In your case, you can add specified Load-Balancer IP into $config['proxy_ips'] (application/config/config.php), for example:

```<code>$config['proxy_ips'] = ['192.168.1.2'];
</code>```

Dynamic proxy IP:

According to your dynamic IP problem, you can mask the IP range for the Load-Balancer network, for example:

```<code> $config['proxy_ips'] = '192.168.1.0/24';
</code>```

The mask function is able in Codeigniter 3

Get IP method:

```<code>$this->input->ip_address();
</code>```

While $this refers to CI instance.

This method takes into account the $config['proxy_ips'] setting and will return the reported HTTP_X_FORWARDED_FOR, HTTP_CLIENT_IP, HTTP_X_CLIENT_IP or HTTP_X_CLUSTER_CLIENT_IP address for the allowed IP addresses.

Body:
In your case, you can add specified Load-Balancer IP into $config['proxy_ips'] (application/config/config.php), for example:

$config['proxy_ips'] = ['192.168.1.2'];

Dynamic proxy IP:

According to your dynamic IP problem, you can mask the IP range for the Load-Balancer network, for example:

 $config['proxy_ips'] = '192.168.1.0/24';

The mask function is able in Codeigniter 3

Get IP method:

$this->input->ip_address();

While $this refers to CI instance.

This method takes into account the $config['proxy_ips'] setting and will return the reported HTTP_X_FORWARDED_FOR, HTTP_CLIENT_IP, HTTP_X_CLIENT_IP or HTTP_X_CLUSTER_CLIENT_IP address for the allowed IP addresses.


问:
How to make a non-modal Dialog window be always on top?
I am using an instance of a Dialog {} in my application to display a small controller window that the user can interact with to affect the functions in the main window (sort of a remote control). I can make this Dialog modal (modality: Qt.WindowModal or modality: Qt.ApplicationModal) or I can make it non-modal with modality: Qt.NonModal.

My problem is that I need to make it non-modal but be always on top of the main window. If I use Qt.NonModal I can still click on the main form but then my Dialog goes behind it. The Dialog class does not seem to have a flags: property, so I can't just set it to Qt.WindowsStaysOnTopHint.

Is there any way to set the flags of a Dialog like this purely from the QML side? Or is it possible to write a simple utility method in c++ that I could call from my Dialog's Component.onCompleted: and pass in the dialog to set its windows flags there?

Update: to illustrate what I'm talking about, here is my dialog on top of my main window:

Here is my dialog underneath my main window:

I want my dialog to not go underneath my main window like this, but I still want to be able to click on and interact with my main window. In other words, I want my dialog to be non-modal, but always-on-top.

答:
Try to use Window instead of Dialog this way you will have access to the flags property.

You can set flags to Qt.WindowStaysOnTopHint to have your window always on top of other ones. You can find the list of flags here. (Don't forget to replace the :: by . in QML)

Main.qml :

```<code>import QtQuick 2.5
import QtQuick.Controls 2.0
import QtQuick.Dialogs 1.2

ApplicationWindow {
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")

    Button {
        id: btn
        width: 100 ; height : 40
        text: "click me"
    }

    Text {
        anchors.top : btn.bottom
        text: "Button currently pressed"
        visible: btn.pressed
    }

    DialogOnTop {

    }
}
</code>```

DialogOnTop.qml :

```<code>import QtQuick 2.0
import QtQuick.Window 2.0
import QtQuick.Controls 1.4

Window {
    id: myWindow

    width: 200
    height: 200

    flags:  Qt.Window | Qt.WindowSystemMenuHint
            | Qt.WindowTitleHint | Qt.WindowMinimizeButtonHint
            | Qt.WindowMaximizeButtonHint | Qt.WindowStaysOnTopHint

    visible: true
    modality: Qt.NonModal // no need for this as it is the default value

    Rectangle {
        color: "lightskyblue"
        anchors.fill: parent
        Text {
            text: "Hello !"
            color: "navy"
            anchors.centerIn: parent
        }
    }
}
</code>```

Result :

Body:
Try to use Window instead of Dialog this way you will have access to the flags property.

You can set flags to Qt.WindowStaysOnTopHint to have your window always on top of other ones. You can find the list of flags here. (Don't forget to replace the :: by . in QML)

Main.qml :

import QtQuick 2.5
import QtQuick.Controls 2.0
import QtQuick.Dialogs 1.2

ApplicationWindow {
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")

    Button {
        id: btn
        width: 100 ; height : 40
        text: "click me"
    }

    Text {
        anchors.top : btn.bottom
        text: "Button currently pressed"
        visible: btn.pressed
    }

    DialogOnTop {

    }
}

DialogOnTop.qml :

import QtQuick 2.0
import QtQuick.Window 2.0
import QtQuick.Controls 1.4

Window {
    id: myWindow

    width: 200
    height: 200

    flags:  Qt.Window | Qt.WindowSystemMenuHint
            | Qt.WindowTitleHint | Qt.WindowMinimizeButtonHint
            | Qt.WindowMaximizeButtonHint | Qt.WindowStaysOnTopHint

    visible: true
    modality: Qt.NonModal // no need for this as it is the default value

    Rectangle {
        color: "lightskyblue"
        anchors.fill: parent
        Text {
            text: "Hello !"
            color: "navy"
            anchors.centerIn: parent
        }
    }
}

Result :


问:
How do you synchronously resolve a chain of es6 promises?
I have a function from a library that returns a promise. I need to run this function multiple times, but each iteration must wait until the previous task is done.

My assumption was that I could do this:

```<code>promiseReturner(1)
  .then(promiseReturner(2)
  .then(promiseReturner(3)
  .then(...)
</code>```

Which could be simplified using a loop:

```<code>var p = Promise.resolve();
for (var i=1; i<=10; i++) {
  p = p.then(promiseReturner(i));
}
</code>```

However, when I do this each promise in the chain is executed at the same time, instead of one after the other as .then() seems to imply. Clearly I'm missing something fundamental about promises -- but after reading several tutorials and blog posts I'm still lost.

Here's a codepen I wrote up to demonstrate my attempt.

答:
If you are using es6, you can achieve this using array.reduce. I think quite neatly.

const functions = [/* array of functions which return promises */];
const finalPromise = functions.reduce(async (promise, asyncFn) => {
  await promise;
  return asyncFn();
}, Promise.resolve());
```

Body:
I have a function from a library that returns a promise. I need to run this function multiple times, but each iteration must wait until the previous task is done.

My assumption was that I could do this:

promiseReturner(1)
  .then(promiseReturner(2)
  .then(promiseReturner(3)
  .then(...)

Which could be simplified using a loop:

var p = Promise.resolve();
for (var i=1; i<=10; i++) {
  p = p.then(promiseReturner(i));
}

However, when I do this each promise in the chain is executed at the same time, instead of one after the other as .then() seems to imply. Clearly I'm missing something fundamental about promises -- but after reading several tutorials and blog posts I'm still lost.

Here's a codepen I wrote up to demonstrate my attempt.


问:
After Adding "readonly" attribute on text box not able to remove it in one event
Steps to repro

USE Internet Explorer

Check unlimited check box

Click on text box (It will remove tick/check from check box)

Try to enter text in text box

We cannot enter in the text box

4. Click again on the text box. Now we will be able to enter text in the text box

We tried by

1. Making attribute readOnly to flase i.e.  $('#myinput').attr('readOnly', false);

2. Calling $('#myinput').click();

Below is the HTML code

```<code><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Make input read only</title>
    <script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.4.min.js"></script>
</head>
<body>
    <input id="myinput" type="text" />
    <input id="mycheck" type="checkbox" />
    <script type="text/javascript">
        /*oncheck box click*/
        $('#mycheck').click(function () {
            if ($(this).attr('checked')) {
                $('#myinput').attr('readOnly', 'readOnly');
            }
            else {
                $('#myinput').removeAttr('readOnly');
                /* also tried
                 * $('#myinput').attr('readOnly', false);
                 * $('#myinput').attr('readOnly', '');
                 */
            }
        });
        /*on text box click*/
        $('#myinput').click(function () {
            $('#mycheck').removeAttr('checked');
            $('#myinput').removeAttr('readOnly');
            /* also tried
             * $('#myinput').attr('readOnly', false);
             * $('#myinput').attr('readOnly', '');
             */
        });
    </script>
</body>
</html>
</code>```

Live copy

答:
You need to set the readonly attribute to nothing like so</p>

```<code>$('#myinput').attr('readOnly', '');
</code>```

OwnerDisplayName: Sreedhar K

LastEditorDisplayName: Sreedhar K

ContentLicense: CC BY-SA 2.5

Body:
Steps to repro

USE Internet Explorer

Check unlimited check box

Click on text box (It will remove tick/check from check box)

Try to enter text in text box

We cannot enter in the text box

4. Click again on the text box. Now we will be able to enter text in the text box

We tried by

1. Making attribute readOnly to flase i.e.  $('#myinput').attr('readOnly', false);

2. Calling $('#myinput').click();

Below is the HTML code

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

    <title>Make input read only</title>

    <input id="myinput" type="text" />
    <input id="mycheck" type="checkbox" />

Live copy

Body:
You need to set the readonly attribute to nothing like so

$('#myinput').attr('readOnly', '');


问:
csv to avro without apache spark in scala
Is there a way I can convert a scv file to Avro without using Apache Spark. I see most of the post suggests using spark which I cannot in my case. I have a schema in a separate file. I was thinking of some custom serializer and deserializer that will use the Schema and convert csv to avro. Any kind of reference would work for me.
Thanks</p>

答:
If you only have strings and primitives, you could put together a crude implementation like this fairly easily:

```<code>def csvToAvro(file: Sting, schema: Schema) = {
  val rec = new GenericData.Record(schema)
  val types = schema
    .getFields
    .map { f => f.pos -> f.schema.getType }

  Source.fromFile(file)
   .getLines
   .map(_.split("_").toSeq)
   .foreach { data =>
     (data zip types)
       .foreach {
         case (str, (idx, STRING)) => rec.put(idx, str)
         case (str, (idx, INT)) => rec.put(idx, str.toInt)
         case (str, (idx, LONG)) => rec.put(idx, str.toLong)
         case (str, (idx, FLOAT)) => rec.put(idx, str.toFloat)
         case (str, (idx, DOUBLE)) => rec.put(idx, str.toDouble)
         case (str, (idx, BOOLEAN)) => rec.put(idx, str.toBoolean)
         case (str, (idx, unknown)) => throw new IllegalArgumentException(s"Don't know how to convert $str to $unknown at $idx))
       }
  }
  rec
}
</code>```

Note this does not handle nullable fields: for those the type is going to be UNION, and you'll have to look inside the schema to find out the actual data type.

Also, "parsing csv" is very crude here (just splitting at the comma isn't really a good idea, because it'll break if a string field happens to contain , in the data, or if fields are escaped with double-quotes).

And also, you'll probably want to add some sanity-checking to make sure, for example, that the number of fields in the csv line matches the number of fields in the schema etc.

But the above considerations notwithstanding, this should be sufficient to illustrate the approach and get you started.

Body:
If you only have strings and primitives, you could put together a crude implementation like this fairly easily:

def csvToAvro(file: Sting, schema: Schema) = {
  val rec = new GenericData.Record(schema)
  val types = schema
    .getFields
    .map { f => f.pos -> f.schema.getType }

  Source.fromFile(file)
   .getLines
   .map(_.split("_").toSeq)
   .foreach { data =>
     (data zip types)
       .foreach {
         case (str, (idx, STRING)) => rec.put(idx, str)
         case (str, (idx, INT)) => rec.put(idx, str.toInt)
         case (str, (idx, LONG)) => rec.put(idx, str.toLong)
         case (str, (idx, FLOAT)) => rec.put(idx, str.toFloat)
         case (str, (idx, DOUBLE)) => rec.put(idx, str.toDouble)
         case (str, (idx, BOOLEAN)) => rec.put(idx, str.toBoolean)
         case (str, (idx, unknown)) => throw new IllegalArgumentException(s"Don't know how to convert $str to $unknown at $idx))
       }
  }
  rec
}

Note this does not handle nullable fields: for those the type is going to be UNION, and you'll have to look inside the schema to find out the actual data type.

Also, "parsing csv" is very crude here (just splitting at the comma isn't really a good idea, because it'll break if a string field happens to contain , in the data, or if fields are escaped with double-quotes).

And also, you'll probably want to add some sanity-checking to make sure, for example, that the number of fields in the csv line matches the number of fields in the schema etc.

But the above considerations notwithstanding, this should be sufficient to illustrate the approach and get you started.


问:
How can I remove these parts of my filenames?
I have some files I need to rename in bulk.   For example:

```<code>Jul-0961_S7_R2_001.fastq.gz
Jul-0967_S22_rep1_R1.fastq.gz
Jul-0974_S32_R2_001.fastq.gz
</code>```

I need to remove the S* part of the filename but I don't know the right regular regex to use.

Specifically:

```<code>Jul-0961_S7_R2_001.fastq.gz --> Jul-0961_R2_001.fastq.gz
</code>```

Something like, rename 's/S*//' *.gz is what I'm looking for.

Is there a regex wizard out there who can show me the way?  Thanks in advance.

答:
If the files are in the same format (i.e have the same number of underscores, you could use:

```<code>"ls" | awk -F_ '{ system("mv "$0" "$1"_"$3"_"$4) }'
</code>```

Here we are using underscore as the delimiter and then building a command to execute with the system function

Body:
I have some files I need to rename in bulk.   For example:

Jul-0961_S7_R2_001.fastq.gz
Jul-0967_S22_rep1_R1.fastq.gz
Jul-0974_S32_R2_001.fastq.gz

I need to remove the S* part of the filename but I don't know the right regular regex to use.

Specifically:

Jul-0961_S7_R2_001.fastq.gz --> Jul-0961_R2_001.fastq.gz

Something like, rename 's/S*//' *.gz is what I'm looking for.

Is there a regex wizard out there who can show me the way?  Thanks in advance.

Body:
If the files are in the same format (i.e have the same number of underscores, you could use:

"ls" | awk -F_ '{ system("mv "$0" "$1"_"$3"_"$4) }'

Here we are using underscore as the delimiter and then building a command to execute with the system function


问:
Citrus integration tests fail randomly
Following up on How to access variables in a (citrus) static-response-adapter

Test layout:

```<code>Citrus -> SUT
          SUT <-> MockServerOne
          SUT <-> MockServerTwo
Citrus <- SUT
</code>```

Applying the suggestions from the post above, I now see randomly occuring exceptions.

The test code:

```<code>@Test
@CitrusTest
public void testRequestNok() throws Exception {
    setDefaultTestVariables();
    http(builder -> builder
            .client("fooClient")
            .send()
            .post("/foo/bar")
            .payload(new ClassPathResource("foo/foo-sample-request.xml"))
            .messageType(MessageType.XML)
            .contentType("application/xml")
            .accept("application/xml")
            .fork(true));

    applyBehavior(new MockOneServerBehavior());
    applyBehavior(new MockTwoServerBehavior("bar/bar-error-response.xml"));

    http(builder -> builder.client("fooClient").receive().response(HttpStatus.BAD_GATEWAY));
}
</code>```

where the behaviors look like this

```<code>public class MockOneServerBehavior extends AbstractTestBehavior {
    public void apply() {
        http(builder -> builder.server("mockServerOne")
                               .receive()
                               .post());

        http(builder -> builder.server("mockServerOne")
                               .send()
                               .response()
                               .payload(new ClasspathResource("foo/bar.xml"));
    }
}
</code>```

The test fails (roughly in 5% of all cases) and so far I have seen two different kinds of exceptions:

A ConcurrentModificationException:

```<code>2017-03-02 11:00:54,836 main [DEBUG ] citrus.channel.ChannelConsumer - Receiving message from: mockServerOne.inbound
2017-03-02 11:00:54,831 qtp1185618138-20 [DEBUG ] http.servlet.CitrusDispatcherServlet - Could not complete request
org.springframework.messaging.MessageDeliveryException: failed to send Message to channel 'mockServerOne.inbound'; nested exception is java.util.ConcurrentModificationException
    at org.springframework.integration.channel.AbstractMessageChannel.send(AbstractMessageChannel.java:449) ~[spring-integration-core-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.integration.channel.AbstractMessageChannel.send(AbstractMessageChannel.java:373) ~[spring-integration-core-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.messaging.core.GenericMessagingTemplate.doSend(GenericMessagingTemplate.java:115) ~[spring-messaging-4.3.6.RELEASE.jar:4.3.6.RELEASE]
    at org.springframework.messaging.core.GenericMessagingTemplate.doSendAndReceive(GenericMessagingTemplate.java:150) ~[spring-messaging-4.3.6.RELEASE.jar:4.3.6.RELEASE]
    at org.springframework.messaging.core.GenericMessagingTemplate.doSendAndReceive(GenericMessagingTemplate.java:45) ~[spring-messaging-4.3.6.RELEASE.jar:4.3.6.RELEASE]
    at org.springframework.messaging.core.AbstractMessagingTemplate.sendAndReceive(AbstractMessagingTemplate.java:42) ~[spring-messaging-4.3.6.RELEASE.jar:4.3.6.RELEASE]
    at org.springframework.integration.core.MessagingTemplate.sendAndReceive(MessagingTemplate.java:97) ~[spring-integration-core-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at com.consol.citrus.channel.ChannelSyncProducer.send(ChannelSyncProducer.java:76) ~[citrus-core-2.7.jar:?]
    at com.consol.citrus.channel.ChannelEndpointAdapter.handleMessageInternal(ChannelEndpointAdapter.java:68) ~[citrus-core-2.7.jar:?]
    at com.consol.citrus.endpoint.AbstractEndpointAdapter.handleMessage(AbstractEndpointAdapter.java:55) ~[citrus-core-2.7.jar:?]
    at com.consol.citrus.http.controller.HttpMessageController.handleRequestInternal(HttpMessageController.java:137) ~[citrus-http-2.7.jar:?]
    at com.consol.citrus.http.controller.HttpMessageController.handlePostRequest(HttpMessageController.java:63) ~[citrus-http-2.7.jar:?]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[?:1.8.0_112]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[?:1.8.0_112]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[?:1.8.0_112]
    at java.lang.reflect.Method.invoke(Method.java:498) ~[?:1.8.0_112]
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205) ~[spring-web-4.3.6.RELEASE.jar:4.3.6.RELEASE]
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133) ~[spring-web-4.3.6.RELEASE.jar:4.3.6.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:116) ~[spring-webmvc-4.3.6.RELEASE.jar:4.3.6.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827) ~[spring-webmvc-4.3.6.RELEASE.jar:4.3.6.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738) ~[spring-webmvc-4.3.6.RELEASE.jar:4.3.6.RELEASE]
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85) ~[spring-webmvc-4.3.6.RELEASE.jar:4.3.6.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963) ~[spring-webmvc-4.3.6.RELEASE.jar:4.3.6.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897) ~[spring-webmvc-4.3.6.RELEASE.jar:4.3.6.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970) [spring-webmvc-4.3.6.RELEASE.jar:4.3.6.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872) [spring-webmvc-4.3.6.RELEASE.jar:4.3.6.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:707) [javax.servlet-api-3.1.0.jar:3.1.0]
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846) [spring-webmvc-4.3.6.RELEASE.jar:4.3.6.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:790) [javax.servlet-api-3.1.0.jar:3.1.0]
    at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:841) [jetty-servlet-9.4.1.v20170120.jar:9.4.1.v20170120]
    at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1634) [jetty-servlet-9.4.1.v20170120.jar:9.4.1.v20170120]
    at com.consol.citrus.http.servlet.GzipServletFilter.doFilterInternal(GzipServletFilter.java:43) [citrus-http-2.7.jar:?]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.3.6.RELEASE.jar:4.3.6.RELEASE]
    at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1621) [jetty-servlet-9.4.1.v20170120.jar:9.4.1.v20170120]
    at com.consol.citrus.http.servlet.RequestCachingServletFilter.doFilterInternal(RequestCachingServletFilter.java:41) [citrus-http-2.7.jar:?]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.3.6.RELEASE.jar:4.3.6.RELEASE]
    at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1621) [jetty-servlet-9.4.1.v20170120.jar:9.4.1.v20170120]
    at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:541) [jetty-servlet-9.4.1.v20170120.jar:9.4.1.v20170120]
    at org.eclipse.jetty.server.handler.ScopedHandler.nextHandle(ScopedHandler.java:188) [jetty-server-9.4.1.v20170120.jar:9.4.1.v20170120]
    at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1228) [jetty-server-9.4.1.v20170120.jar:9.4.1.v20170120]
    at org.eclipse.jetty.server.handler.ScopedHandler.nextScope(ScopedHandler.java:168) [jetty-server-9.4.1.v20170120.jar:9.4.1.v20170120]
    at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:481) [jetty-servlet-9.4.1.v20170120.jar:9.4.1.v20170120]
    at org.eclipse.jetty.server.handler.ScopedHandler.nextScope(ScopedHandler.java:166) [jetty-server-9.4.1.v20170120.jar:9.4.1.v20170120]
    at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1130) [jetty-server-9.4.1.v20170120.jar:9.4.1.v20170120]
    at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:141) [jetty-server-9.4.1.v20170120.jar:9.4.1.v20170120]
    at org.eclipse.jetty.server.handler.ContextHandlerCollection.handle(ContextHandlerCollection.java:213) [jetty-server-9.4.1.v20170120.jar:9.4.1.v20170120]
    at org.eclipse.jetty.server.handler.HandlerCollection.handle(HandlerCollection.java:118) [jetty-server-9.4.1.v20170120.jar:9.4.1.v20170120]
    at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:132) [jetty-server-9.4.1.v20170120.jar:9.4.1.v20170120]
    at org.eclipse.jetty.server.Server.handle(Server.java:564) [jetty-server-9.4.1.v20170120.jar:9.4.1.v20170120]
    at org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:320) [jetty-server-9.4.1.v20170120.jar:9.4.1.v20170120]
    at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:251) [jetty-server-9.4.1.v20170120.jar:9.4.1.v20170120]
    at org.eclipse.jetty.io.AbstractConnection$ReadCallback.succeeded(AbstractConnection.java:279) [jetty-io-9.4.1.v20170120.jar:9.4.1.v20170120]
    at org.eclipse.jetty.io.FillInterest.fillable(FillInterest.java:112) [jetty-io-9.4.1.v20170120.jar:9.4.1.v20170120]
    at org.eclipse.jetty.io.ChannelEndPoint$2.run(ChannelEndPoint.java:124) [jetty-io-9.4.1.v20170120.jar:9.4.1.v20170120]
    at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:672) [jetty-util-9.4.1.v20170120.jar:9.4.1.v20170120]
    at org.eclipse.jetty.util.thread.QueuedThreadPool$2.run(QueuedThreadPool.java:590) [jetty-util-9.4.1.v20170120.jar:9.4.1.v20170120]
    at java.lang.Thread.run(Thread.java:745) [?:1.8.0_112]
Caused by: java.util.ConcurrentModificationException
    at java.util.HashMap$HashIterator.nextNode(HashMap.java:1437) ~[?:1.8.0_112]
    at java.util.HashMap$EntryIterator.next(HashMap.java:1471) ~[?:1.8.0_112]
    at java.util.HashMap$EntryIterator.next(HashMap.java:1469) ~[?:1.8.0_112]
    at java.util.AbstractMap.toString(AbstractMap.java:554) ~[?:1.8.0_112]
    at java.util.Formatter$FormatSpecifier.printString(Formatter.java:2886) ~[?:1.8.0_112]
    at java.util.Formatter$FormatSpecifier.print(Formatter.java:2763) ~[?:1.8.0_112]
    at java.util.Formatter.format(Formatter.java:2520) ~[?:1.8.0_112]
    at java.util.Formatter.format(Formatter.java:2455) ~[?:1.8.0_112]
    at java.lang.String.format(String.java:2940) ~[?:1.8.0_112]
    at com.consol.citrus.message.DefaultMessage.toString(DefaultMessage.java:108) ~[citrus-core-2.7.jar:?]
    at java.lang.String.valueOf(String.java:2994) ~[?:1.8.0_112]
    at java.lang.StringBuilder.append(StringBuilder.java:131) ~[?:1.8.0_112]
    at org.springframework.messaging.support.GenericMessage.toString(GenericMessage.java:111) ~[spring-messaging-4.3.6.RELEASE.jar:4.3.6.RELEASE]
    at java.lang.String.valueOf(String.java:2994) ~[?:1.8.0_112]
    at java.lang.StringBuilder.append(StringBuilder.java:131) ~[?:1.8.0_112]
    at org.springframework.integration.channel.AbstractMessageChannel.send(AbstractMessageChannel.java:430) ~[spring-integration-core-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    ... 56 more
</code>```

and a problem with TypeConversion, which leads to a XMLParseException:

```<code>2017-03-02 11:11:59,543 main [DEBUG ] citrus.validation.MessageValidatorRegistry - Found 3 message validators for message type: XML
2017-03-02 11:11:59,543 main [DEBUG ] validation.xml.DomXmlMessageValidator - Start message validation ...
2017-03-02 11:11:59,543 main [DEBUG ] validation.xml.DomXmlMessageValidator - Start XML message validation
2017-03-02 11:11:59,544 main [WARN  ] citrus.util.TypeConversionUtils - Using object toString representation: Failed to convert value of type 'java.io.ByteArrayInputStream' to required type 'java.lang.String'; nested exception is java.lang.IllegalStateException: Cannot convert value of type 'java.io.ByteArrayInputStream' to required type 'java.lang.String': no matching editors or conversion strategy found
2017-03-02 11:11:59,544 main [WARN  ] citrus.util.TypeConversionUtils - Using object toString representation: Failed to convert value of type 'java.io.ByteArrayInputStream' to required type 'java.lang.String'; nested exception is java.lang.IllegalStateException: Cannot convert value of type 'java.io.ByteArrayInputStream' to required type 'java.lang.String': no matching editors or conversion strategy found
[Fatal Error] :1:1: Content is not allowed in prolog.
2017-03-02 11:11:59,553 main [INFO  ] consol.citrus.Citrus -
2017-03-02 11:11:59,553 main [ERROR ] consol.citrus.Citrus - TEST FAILED FooTest.testBar <foo.bar.baz> Nested exception is:
com.consol.citrus.exceptions.CitrusRuntimeException: org.w3c.dom.ls.LSException: Content is not allowed in prolog.
    at com.consol.citrus.validation.xml.DomXmlMessageValidator.validateMessagePayload(DomXmlMessageValidator.java:116) ~[citrus-core-2.7.jar:?]
    at com.consol.citrus.validation.xml.DomXmlMessageValidator.validateMessagePayload(DomXmlMessageValidator.java:68) ~[citrus-core-2.7.jar:?]
    at com.consol.citrus.validation.AbstractMessageValidator.validateMessage(AbstractMessageValidator.java:65) ~[citrus-core-2.7.jar:?]
    at com.consol.citrus.validation.AbstractMessageValidator.validateMessage(AbstractMessageValidator.java:50) ~[citrus-core-2.7.jar:?]
    at com.consol.citrus.actions.ReceiveMessageAction.validateMessage(ReceiveMessageAction.java:216) ~[citrus-core-2.7.jar:?]
    at com.consol.citrus.actions.ReceiveMessageAction.doExecute(ReceiveMessageAction.java:133) ~[citrus-core-2.7.jar:?]
    at com.consol.citrus.actions.AbstractTestAction.execute(AbstractTestAction.java:42) ~[citrus-core-2.7.jar:?]
    at com.consol.citrus.dsl.actions.DelegatingTestAction.doExecute(DelegatingTestAction.java:54) ~[citrus-java-dsl-2.7.jar:?]
    at com.consol.citrus.actions.AbstractTestAction.execute(AbstractTestAction.java:42) ~[citrus-core-2.7.jar:?]
    at com.consol.citrus.TestCase.executeAction(TestCase.java:229) [citrus-core-2.7.jar:?]
    at com.consol.citrus.dsl.runner.DefaultTestRunner.run(DefaultTestRunner.java:198) ~[citrus-java-dsl-2.7.jar:?]
    at com.consol.citrus.dsl.runner.DefaultTestRunner.http(DefaultTestRunner.java:526) [citrus-java-dsl-2.7.jar:?]
    at com.consol.citrus.dsl.testng.TestNGCitrusTestRunner.http(TestNGCitrusTestRunner.java:360) ~[citrus-java-dsl-2.7.jar:?]
    at foo.bar.baz.FooTest.testFoo(FooTest.java:92) ~[integrationTest/:?]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[?:1.8.0_112]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[?:1.8.0_112]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[?:1.8.0_112]
    at java.lang.reflect.Method.invoke(Method.java:498) ~[?:1.8.0_112]
    at org.springframework.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:216) ~[spring-core-4.3.6.RELEASE.jar:4.3.6.RELEASE]
    at com.consol.citrus.dsl.testng.TestNGCitrusTest.invokeTestMethod(TestNGCitrusTest.java:139) ~[citrus-java-dsl-2.7.jar:?]
    at com.consol.citrus.dsl.testng.TestNGCitrusTest.run(TestNGCitrusTest.java:109) [citrus-java-dsl-2.7.jar:?]
    at com.consol.citrus.dsl.testng.TestNGCitrusTest.run(TestNGCitrusTest.java:58) [citrus-java-dsl-2.7.jar:?]
    at org.testng.internal.MethodInvocationHelper.invokeHookable(MethodInvocationHelper.java:209) [testng-6.9.10.jar:?]
    at org.testng.internal.Invoker.invokeMethod(Invoker.java:639) [testng-6.9.10.jar:?]
    at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:820) [testng-6.9.10.jar:?]
    at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1128) [testng-6.9.10.jar:?]
    at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:129) [testng-6.9.10.jar:?]
    at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:112) [testng-6.9.10.jar:?]
    at org.testng.TestRunner.privateRun(TestRunner.java:782) [testng-6.9.10.jar:?]
    at org.testng.TestRunner.run(TestRunner.java:632) [testng-6.9.10.jar:?]
    at org.testng.SuiteRunner.runTest(SuiteRunner.java:366) [testng-6.9.10.jar:?]
    at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:361) [testng-6.9.10.jar:?]
    at org.testng.SuiteRunner.privateRun(SuiteRunner.java:319) [testng-6.9.10.jar:?]
    at org.testng.SuiteRunner.run(SuiteRunner.java:268) [testng-6.9.10.jar:?]
    at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52) [testng-6.9.10.jar:?]
    at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86) [testng-6.9.10.jar:?]
    at org.testng.TestNG.runSuitesSequentially(TestNG.java:1244) [testng-6.9.10.jar:?]
    at org.testng.TestNG.runSuitesLocally(TestNG.java:1169) [testng-6.9.10.jar:?]
    at org.testng.TestNG.run(TestNG.java:1064) [testng-6.9.10.jar:?]
    at org.testng.IDEARemoteTestNG.run(IDEARemoteTestNG.java:72) [testng-plugin.jar:?]
    at org.testng.RemoteTestNGStarter.main(RemoteTestNGStarter.java:127) [testng-plugin.jar:?]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[?:1.8.0_112]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[?:1.8.0_112]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[?:1.8.0_112]
    at java.lang.reflect.Method.invoke(Method.java:498) ~[?:1.8.0_112]
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147) [idea_rt.jar:?]
Caused by: org.w3c.dom.ls.LSException: Content is not allowed in prolog.
    at org.apache.xerces.parsers.DOMParserImpl.parse(Unknown Source) ~[xercesImpl-2.11.0.jar:?]
    at com.consol.citrus.util.XMLUtils.parseMessagePayload(XMLUtils.java:356) ~[citrus-core-2.7.jar:?]
    at com.consol.citrus.validation.xml.DomXmlMessageValidator.validateXMLSchema(DomXmlMessageValidator.java:148) ~[citrus-core-2.7.jar:?]
    at com.consol.citrus.validation.xml.DomXmlMessageValidator.validateMessagePayload(DomXmlMessageValidator.java:91) ~[citrus-core-2.7.jar:?]
    ... 45 more
Caused by: org.apache.xerces.xni.parser.XMLParseException: Content is not allowed in prolog.
    at org.apache.xerces.impl.XMLErrorReporter.reportError(Unknown Source) ~[xercesImpl-2.11.0.jar:?]
    at org.apache.xerces.impl.XMLErrorReporter.reportError(Unknown Source) ~[xercesImpl-2.11.0.jar:?]
    at org.apache.xerces.impl.XMLErrorReporter.reportError(Unknown Source) ~[xercesImpl-2.11.0.jar:?]
    at org.apache.xerces.impl.XMLScanner.reportFatalError(Unknown Source) ~[xercesImpl-2.11.0.jar:?]
    at org.apache.xerces.impl.XMLDocumentScannerImpl$PrologDispatcher.dispatch(Unknown Source) ~[xercesImpl-2.11.0.jar:?]
    at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl.scanDocument(Unknown Source) ~[xercesImpl-2.11.0.jar:?]
    at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source) ~[xercesImpl-2.11.0.jar:?]
    at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source) ~[xercesImpl-2.11.0.jar:?]
    at org.apache.xerces.parsers.XMLParser.parse(Unknown Source) ~[xercesImpl-2.11.0.jar:?]
    at org.apache.xerces.parsers.DOMParserImpl.parse(Unknown Source) ~[xercesImpl-2.11.0.jar:?]
    at com.consol.citrus.util.XMLUtils.parseMessagePayload(XMLUtils.java:356) ~[citrus-core-2.7.jar:?]
    at com.consol.citrus.validation.xml.DomXmlMessageValidator.validateXMLSchema(DomXmlMessageValidator.java:148) ~[citrus-core-2.7.jar:?]
    at com.consol.citrus.validation.xml.DomXmlMessageValidator.validateMessagePayload(DomXmlMessageValidator.java:91) ~[citrus-core-2.7.jar:?]
    ... 45 more
</code>```

In case of the XMLParseException, I have verified on HTTP level that the response is identical to when the test actually passes.

Both exceptions look like threading issues to me.

I would be grateful for any feedback or alternative approach I might try.

答:
Indeed this has been an issue located in the default message implementation when converting its payload to a String for logging purpose. The issue has been fixed with the mentioned github commit:

https://github.com/christophd/citrus/commit/2c0e70c4db9af102c2544ad60fb9447afb8a7b9c

Mentioned behavior is fixed since Citrus 2.7.2.

Title: Citrus integration tests fail randomly

Body:
Following up on How to access variables in a (citrus) static-response-adapter

Test layout:

Citrus -> SUT
          SUT <-> MockServerOne
          SUT <-> MockServerTwo
Citrus <- SUT

Applying the suggestions from the post above, I now see randomly occuring exceptions.

The test code:

@Test
@CitrusTest
public void testRequestNok() throws Exception {
    setDefaultTestVariables();
    http(builder -> builder
            .client("fooClient")
            .send()
            .post("/foo/bar")
            .payload(new ClassPathResource("foo/foo-sample-request.xml"))
            .messageType(MessageType.XML)
            .contentType("application/xml")
            .accept("application/xml")
            .fork(true));

    applyBehavior(new MockOneServerBehavior());
    applyBehavior(new MockTwoServerBehavior("bar/bar-error-response.xml"));

    http(builder -> builder.client("fooClient").receive().response(HttpStatus.BAD_GATEWAY));
}

where the behaviors look like this

public class MockOneServerBehavior extends AbstractTestBehavior {
    public void apply() {
        http(builder -> builder.server("mockServerOne")
                               .receive()
                               .post());

        http(builder -> builder.server("mockServerOne")
                               .send()
                               .response()
                               .payload(new ClasspathResource("foo/bar.xml"));
    }
}

The test fails (roughly in 5% of all cases) and so far I have seen two different kinds of exceptions:

A ConcurrentModificationException:

2017-03-02 11:00:54,836 main [DEBUG ] citrus.channel.ChannelConsumer - Receiving message from: mockServerOne.inbound
2017-03-02 11:00:54,831 qtp1185618138-20 [DEBUG ] http.servlet.CitrusDispatcherServlet - Could not complete request
org.springframework.messaging.MessageDeliveryException: failed to send Message to channel 'mockServerOne.inbound'; nested exception is java.util.ConcurrentModificationException
    at org.springframework.integration.channel.AbstractMessageChannel.send(AbstractMessageChannel.java:449) ~[spring-integration-core-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.integration.channel.AbstractMessageChannel.send(AbstractMessageChannel.java:373) ~[spring-integration-core-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.messaging.core.GenericMessagingTemplate.doSend(GenericMessagingTemplate.java:115) ~[spring-messaging-4.3.6.RELEASE.jar:4.3.6.RELEASE]
    at org.springframework.messaging.core.GenericMessagingTemplate.doSendAndReceive(GenericMessagingTemplate.java:150) ~[spring-messaging-4.3.6.RELEASE.jar:4.3.6.RELEASE]
    at org.springframework.messaging.core.GenericMessagingTemplate.doSendAndReceive(GenericMessagingTemplate.java:45) ~[spring-messaging-4.3.6.RELEASE.jar:4.3.6.RELEASE]
    at org.springframework.messaging.core.AbstractMessagingTemplate.sendAndReceive(AbstractMessagingTemplate.java:42) ~[spring-messaging-4.3.6.RELEASE.jar:4.3.6.RELEASE]
    at org.springframework.integration.core.MessagingTemplate.sendAndReceive(MessagingTemplate.java:97) ~[spring-integration-core-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at com.consol.citrus.channel.ChannelSyncProducer.send(ChannelSyncProducer.java:76) ~[citrus-core-2.7.jar:?]
    at com.consol.citrus.channel.ChannelEndpointAdapter.handleMessageInternal(ChannelEndpointAdapter.java:68) ~[citrus-core-2.7.jar:?]
    at com.consol.citrus.endpoint.AbstractEndpointAdapter.handleMessage(AbstractEndpointAdapter.java:55) ~[citrus-core-2.7.jar:?]
    at com.consol.citrus.http.controller.HttpMessageController.handleRequestInternal(HttpMessageController.java:137) ~[citrus-http-2.7.jar:?]
    at com.consol.citrus.http.controller.HttpMessageController.handlePostRequest(HttpMessageController.java:63) ~[citrus-http-2.7.jar:?]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[?:1.8.0_112]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[?:1.8.0_112]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[?:1.8.0_112]
    at java.lang.reflect.Method.invoke(Method.java:498) ~[?:1.8.0_112]
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205) ~[spring-web-4.3.6.RELEASE.jar:4.3.6.RELEASE]
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133) ~[spring-web-4.3.6.RELEASE.jar:4.3.6.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:116) ~[spring-webmvc-4.3.6.RELEASE.jar:4.3.6.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827) ~[spring-webmvc-4.3.6.RELEASE.jar:4.3.6.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738) ~[spring-webmvc-4.3.6.RELEASE.jar:4.3.6.RELEASE]
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85) ~[spring-webmvc-4.3.6.RELEASE.jar:4.3.6.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963) ~[spring-webmvc-4.3.6.RELEASE.jar:4.3.6.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897) ~[spring-webmvc-4.3.6.RELEASE.jar:4.3.6.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970) [spring-webmvc-4.3.6.RELEASE.jar:4.3.6.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872) [spring-webmvc-4.3.6.RELEASE.jar:4.3.6.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:707) [javax.servlet-api-3.1.0.jar:3.1.0]
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846) [spring-webmvc-4.3.6.RELEASE.jar:4.3.6.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:790) [javax.servlet-api-3.1.0.jar:3.1.0]
    at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:841) [jetty-servlet-9.4.1.v20170120.jar:9.4.1.v20170120]
    at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1634) [jetty-servlet-9.4.1.v20170120.jar:9.4.1.v20170120]
    at com.consol.citrus.http.servlet.GzipServletFilter.doFilterInternal(GzipServletFilter.java:43) [citrus-http-2.7.jar:?]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.3.6.RELEASE.jar:4.3.6.RELEASE]
    at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1621) [jetty-servlet-9.4.1.v20170120.jar:9.4.1.v20170120]
    at com.consol.citrus.http.servlet.RequestCachingServletFilter.doFilterInternal(RequestCachingServletFilter.java:41) [citrus-http-2.7.jar:?]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.3.6.RELEASE.jar:4.3.6.RELEASE]
    at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1621) [jetty-servlet-9.4.1.v20170120.jar:9.4.1.v20170120]
    at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:541) [jetty-servlet-9.4.1.v20170120.jar:9.4.1.v20170120]
    at org.eclipse.jetty.server.handler.ScopedHandler.nextHandle(ScopedHandler.java:188) [jetty-server-9.4.1.v20170120.jar:9.4.1.v20170120]
    at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1228) [jetty-server-9.4.1.v20170120.jar:9.4.1.v20170120]
    at org.eclipse.jetty.server.handler.ScopedHandler.nextScope(ScopedHandler.java:168) [jetty-server-9.4.1.v20170120.jar:9.4.1.v20170120]
    at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:481) [jetty-servlet-9.4.1.v20170120.jar:9.4.1.v20170120]
    at org.eclipse.jetty.server.handler.ScopedHandler.nextScope(ScopedHandler.java:166) [jetty-server-9.4.1.v20170120.jar:9.4.1.v20170120]
    at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1130) [jetty-server-9.4.1.v20170120.jar:9.4.1.v20170120]
    at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:141) [jetty-server-9.4.1.v20170120.jar:9.4.1.v20170120]
    at org.eclipse.jetty.server.handler.ContextHandlerCollection.handle(ContextHandlerCollection.java:213) [jetty-server-9.4.1.v20170120.jar:9.4.1.v20170120]
    at org.eclipse.jetty.server.handler.HandlerCollection.handle(HandlerCollection.java:118) [jetty-server-9.4.1.v20170120.jar:9.4.1.v20170120]
    at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:132) [jetty-server-9.4.1.v20170120.jar:9.4.1.v20170120]
    at org.eclipse.jetty.server.Server.handle(Server.java:564) [jetty-server-9.4.1.v20170120.jar:9.4.1.v20170120]
    at org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:320) [jetty-server-9.4.1.v20170120.jar:9.4.1.v20170120]
    at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:251) [jetty-server-9.4.1.v20170120.jar:9.4.1.v20170120]
    at org.eclipse.jetty.io.AbstractConnection$ReadCallback.succeeded(AbstractConnection.java:279) [jetty-io-9.4.1.v20170120.jar:9.4.1.v20170120]
    at org.eclipse.jetty.io.FillInterest.fillable(FillInterest.java:112) [jetty-io-9.4.1.v20170120.jar:9.4.1.v20170120]
    at org.eclipse.jetty.io.ChannelEndPoint$2.run(ChannelEndPoint.java:124) [jetty-io-9.4.1.v20170120.jar:9.4.1.v20170120]
    at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:672) [jetty-util-9.4.1.v20170120.jar:9.4.1.v20170120]
    at org.eclipse.jetty.util.thread.QueuedThreadPool$2.run(QueuedThreadPool.java:590) [jetty-util-9.4.1.v20170120.jar:9.4.1.v20170120]
    at java.lang.Thread.run(Thread.java:745) [?:1.8.0_112]
Caused by: java.util.ConcurrentModificationException
    at java.util.HashMap$HashIterator.nextNode(HashMap.java:1437) ~[?:1.8.0_112]
    at java.util.HashMap$EntryIterator.next(HashMap.java:1471) ~[?:1.8.0_112]
    at java.util.HashMap$EntryIterator.next(HashMap.java:1469) ~[?:1.8.0_112]
    at java.util.AbstractMap.toString(AbstractMap.java:554) ~[?:1.8.0_112]
    at java.util.Formatter$FormatSpecifier.printString(Formatter.java:2886) ~[?:1.8.0_112]
    at java.util.Formatter$FormatSpecifier.print(Formatter.java:2763) ~[?:1.8.0_112]
    at java.util.Formatter.format(Formatter.java:2520) ~[?:1.8.0_112]
    at java.util.Formatter.format(Formatter.java:2455) ~[?:1.8.0_112]
    at java.lang.String.format(String.java:2940) ~[?:1.8.0_112]
    at com.consol.citrus.message.DefaultMessage.toString(DefaultMessage.java:108) ~[citrus-core-2.7.jar:?]
    at java.lang.String.valueOf(String.java:2994) ~[?:1.8.0_112]
    at java.lang.StringBuilder.append(StringBuilder.java:131) ~[?:1.8.0_112]
    at org.springframework.messaging.support.GenericMessage.toString(GenericMessage.java:111) ~[spring-messaging-4.3.6.RELEASE.jar:4.3.6.RELEASE]
    at java.lang.String.valueOf(String.java:2994) ~[?:1.8.0_112]
    at java.lang.StringBuilder.append(StringBuilder.java:131) ~[?:1.8.0_112]
    at org.springframework.integration.channel.AbstractMessageChannel.send(AbstractMessageChannel.java:430) ~[spring-integration-core-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    ... 56 more

and a problem with TypeConversion, which leads to a XMLParseException:

2017-03-02 11:11:59,543 main [DEBUG ] citrus.validation.MessageValidatorRegistry - Found 3 message validators for message type: XML
2017-03-02 11:11:59,543 main [DEBUG ] validation.xml.DomXmlMessageValidator - Start message validation ...
2017-03-02 11:11:59,543 main [DEBUG ] validation.xml.DomXmlMessageValidator - Start XML message validation
2017-03-02 11:11:59,544 main [WARN  ] citrus.util.TypeConversionUtils - Using object toString representation: Failed to convert value of type 'java.io.ByteArrayInputStream' to required type 'java.lang.String'; nested exception is java.lang.IllegalStateException: Cannot convert value of type 'java.io.ByteArrayInputStream' to required type 'java.lang.String': no matching editors or conversion strategy found
2017-03-02 11:11:59,544 main [WARN  ] citrus.util.TypeConversionUtils - Using object toString representation: Failed to convert value of type 'java.io.ByteArrayInputStream' to required type 'java.lang.String'; nested exception is java.lang.IllegalStateException: Cannot convert value of type 'java.io.ByteArrayInputStream' to required type 'java.lang.String': no matching editors or conversion strategy found
[Fatal Error] :1:1: Content is not allowed in prolog.
2017-03-02 11:11:59,553 main [INFO  ] consol.citrus.Citrus -
2017-03-02 11:11:59,553 main [ERROR ] consol.citrus.Citrus - TEST FAILED FooTest.testBar <foo.bar.baz> Nested exception is:
com.consol.citrus.exceptions.CitrusRuntimeException: org.w3c.dom.ls.LSException: Content is not allowed in prolog.
    at com.consol.citrus.validation.xml.DomXmlMessageValidator.validateMessagePayload(DomXmlMessageValidator.java:116) ~[citrus-core-2.7.jar:?]
    at com.consol.citrus.validation.xml.DomXmlMessageValidator.validateMessagePayload(DomXmlMessageValidator.java:68) ~[citrus-core-2.7.jar:?]
    at com.consol.citrus.validation.AbstractMessageValidator.validateMessage(AbstractMessageValidator.java:65) ~[citrus-core-2.7.jar:?]
    at com.consol.citrus.validation.AbstractMessageValidator.validateMessage(AbstractMessageValidator.java:50) ~[citrus-core-2.7.jar:?]
    at com.consol.citrus.actions.ReceiveMessageAction.validateMessage(ReceiveMessageAction.java:216) ~[citrus-core-2.7.jar:?]
    at com.consol.citrus.actions.ReceiveMessageAction.doExecute(ReceiveMessageAction.java:133) ~[citrus-core-2.7.jar:?]
    at com.consol.citrus.actions.AbstractTestAction.execute(AbstractTestAction.java:42) ~[citrus-core-2.7.jar:?]
    at com.consol.citrus.dsl.actions.DelegatingTestAction.doExecute(DelegatingTestAction.java:54) ~[citrus-java-dsl-2.7.jar:?]
    at com.consol.citrus.actions.AbstractTestAction.execute(AbstractTestAction.java:42) ~[citrus-core-2.7.jar:?]
    at com.consol.citrus.TestCase.executeAction(TestCase.java:229) [citrus-core-2.7.jar:?]
    at com.consol.citrus.dsl.runner.DefaultTestRunner.run(DefaultTestRunner.java:198) ~[citrus-java-dsl-2.7.jar:?]
    at com.consol.citrus.dsl.runner.DefaultTestRunner.http(DefaultTestRunner.java:526) [citrus-java-dsl-2.7.jar:?]
    at com.consol.citrus.dsl.testng.TestNGCitrusTestRunner.http(TestNGCitrusTestRunner.java:360) ~[citrus-java-dsl-2.7.jar:?]
    at foo.bar.baz.FooTest.testFoo(FooTest.java:92) ~[integrationTest/:?]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[?:1.8.0_112]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[?:1.8.0_112]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[?:1.8.0_112]
    at java.lang.reflect.Method.invoke(Method.java:498) ~[?:1.8.0_112]
    at org.springframework.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:216) ~[spring-core-4.3.6.RELEASE.jar:4.3.6.RELEASE]
    at com.consol.citrus.dsl.testng.TestNGCitrusTest.invokeTestMethod(TestNGCitrusTest.java:139) ~[citrus-java-dsl-2.7.jar:?]
    at com.consol.citrus.dsl.testng.TestNGCitrusTest.run(TestNGCitrusTest.java:109) [citrus-java-dsl-2.7.jar:?]
    at com.consol.citrus.dsl.testng.TestNGCitrusTest.run(TestNGCitrusTest.java:58) [citrus-java-dsl-2.7.jar:?]
    at org.testng.internal.MethodInvocationHelper.invokeHookable(MethodInvocationHelper.java:209) [testng-6.9.10.jar:?]
    at org.testng.internal.Invoker.invokeMethod(Invoker.java:639) [testng-6.9.10.jar:?]
    at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:820) [testng-6.9.10.jar:?]
    at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1128) [testng-6.9.10.jar:?]
    at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:129) [testng-6.9.10.jar:?]
    at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:112) [testng-6.9.10.jar:?]
    at org.testng.TestRunner.privateRun(TestRunner.java:782) [testng-6.9.10.jar:?]
    at org.testng.TestRunner.run(TestRunner.java:632) [testng-6.9.10.jar:?]
    at org.testng.SuiteRunner.runTest(SuiteRunner.java:366) [testng-6.9.10.jar:?]
    at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:361) [testng-6.9.10.jar:?]
    at org.testng.SuiteRunner.privateRun(SuiteRunner.java:319) [testng-6.9.10.jar:?]
    at org.testng.SuiteRunner.run(SuiteRunner.java:268) [testng-6.9.10.jar:?]
    at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52) [testng-6.9.10.jar:?]
    at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86) [testng-6.9.10.jar:?]
    at org.testng.TestNG.runSuitesSequentially(TestNG.java:1244) [testng-6.9.10.jar:?]
    at org.testng.TestNG.runSuitesLocally(TestNG.java:1169) [testng-6.9.10.jar:?]
    at org.testng.TestNG.run(TestNG.java:1064) [testng-6.9.10.jar:?]
    at org.testng.IDEARemoteTestNG.run(IDEARemoteTestNG.java:72) [testng-plugin.jar:?]
    at org.testng.RemoteTestNGStarter.main(RemoteTestNGStarter.java:127) [testng-plugin.jar:?]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[?:1.8.0_112]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[?:1.8.0_112]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[?:1.8.0_112]
    at java.lang.reflect.Method.invoke(Method.java:498) ~[?:1.8.0_112]
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147) [idea_rt.jar:?]
Caused by: org.w3c.dom.ls.LSException: Content is not allowed in prolog.
    at org.apache.xerces.parsers.DOMParserImpl.parse(Unknown Source) ~[xercesImpl-2.11.0.jar:?]
    at com.consol.citrus.util.XMLUtils.parseMessagePayload(XMLUtils.java:356) ~[citrus-core-2.7.jar:?]
    at com.consol.citrus.validation.xml.DomXmlMessageValidator.validateXMLSchema(DomXmlMessageValidator.java:148) ~[citrus-core-2.7.jar:?]
    at com.consol.citrus.validation.xml.DomXmlMessageValidator.validateMessagePayload(DomXmlMessageValidator.java:91) ~[citrus-core-2.7.jar:?]
    ... 45 more
Caused by: org.apache.xerces.xni.parser.XMLParseException: Content is not allowed in prolog.
    at org.apache.xerces.impl.XMLErrorReporter.reportError(Unknown Source) ~[xercesImpl-2.11.0.jar:?]
    at org.apache.xerces.impl.XMLErrorReporter.reportError(Unknown Source) ~[xercesImpl-2.11.0.jar:?]
    at org.apache.xerces.impl.XMLErrorReporter.reportError(Unknown Source) ~[xercesImpl-2.11.0.jar:?]
    at org.apache.xerces.impl.XMLScanner.reportFatalError(Unknown Source) ~[xercesImpl-2.11.0.jar:?]
    at org.apache.xerces.impl.XMLDocumentScannerImpl$PrologDispatcher.dispatch(Unknown Source) ~[xercesImpl-2.11.0.jar:?]
    at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl.scanDocument(Unknown Source) ~[xercesImpl-2.11.0.jar:?]
    at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source) ~[xercesImpl-2.11.0.jar:?]
    at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source) ~[xercesImpl-2.11.0.jar:?]
    at org.apache.xerces.parsers.XMLParser.parse(Unknown Source) ~[xercesImpl-2.11.0.jar:?]
    at org.apache.xerces.parsers.DOMParserImpl.parse(Unknown Source) ~[xercesImpl-2.11.0.jar:?]
    at com.consol.citrus.util.XMLUtils.parseMessagePayload(XMLUtils.java:356) ~[citrus-core-2.7.jar:?]
    at com.consol.citrus.validation.xml.DomXmlMessageValidator.validateXMLSchema(DomXmlMessageValidator.java:148) ~[citrus-core-2.7.jar:?]
    at com.consol.citrus.validation.xml.DomXmlMessageValidator.validateMessagePayload(DomXmlMessageValidator.java:91) ~[citrus-core-2.7.jar:?]
    ... 45 more

In case of the XMLParseException, I have verified on HTTP level that the response is identical to when the test actually passes.

Both exceptions look like threading issues to me.

I would be grateful for any feedback or alternative approach I might try.