How to create a set vlan flow? - openflow

I want to do the equivalent of the following :
sudo ovs-ofctl add-flow s1 table=2,metadata=1379878762,actions=push_vlan:0x8100,mod_vlan_vid:4000,output:6,goto_table:4 -O openflow13
How can I do this in opendaylight java code? I tried based on some examples I could find, but no flows appeared or sometimes with enough tweaking I could get a part of the flow to appear (I could never see the output action). I am using Carbon (the latest version of carbon) for my development. Is it worth switching to the nightly snapshot?
When I do this with opendaylight, I find that any actions having to do with vlan do not appear in my flow. Only the goto appears in the flow.
=== UPDATE ===
I use the following java code to set and create the vlan tag (suggested by answer below):
private static Instruction createSetVlanAndOutputToPortInstructions( int vlanId,
String outputPortUri) {
List<Action> actionList = new ArrayList<>();
ActionBuilder ab = new ActionBuilder();
Integer VLAN_ETHERTYPE = 0x8100;
ActionBuilder actionBuilder = new ActionBuilder();
//push vlan
Action pushVlanAction = actionBuilder
.setOrder(0).setAction(new PushVlanActionCaseBuilder()
.setPushVlanAction(new PushVlanActionBuilder()
.setEthernetType(VLAN_ETHERTYPE)
.build())
.build())
.build();
actionList.add(pushVlanAction);
//set vlan id
SetVlanIdActionBuilder tab = new SetVlanIdActionBuilder();
tab.setVlanId(new VlanId((int) vlanId));
SetVlanIdActionCaseBuilder vidcb = new SetVlanIdActionCaseBuilder();
vidcb.setSetVlanIdAction(tab.build());
Action setVlanIdAction = actionBuilder.setOrder(1).setAction(vidcb.build()).build();
OutputActionBuilder output = new OutputActionBuilder();
output.setMaxLength(Integer.valueOf(0xffff));
Uri controllerPort = new Uri(outputPortUri);
output.setOutputNodeConnector(controllerPort);
ab = new ActionBuilder();
ab.setKey(new ActionKey(0));
ab.setAction(new OutputActionCaseBuilder().setOutputAction(output.build()).build());
ab.setOrder(2);
actionList.add(ab.build());
ApplyActionsBuilder aab = new ApplyActionsBuilder();
aab.setAction(actionList);
InstructionBuilder ib = new InstructionBuilder();
ib.setKey(new InstructionKey(0));
ib.setInstruction(new ApplyActionsCaseBuilder().setApplyActions(aab.build()).build());
return ib.build();
}
The code that creates a flow rule is here:
FlowBuilder tagPacketFlow = new FlowBuilder().setTableId((short) tableId)
.setFlowName("metadataMatchSetVlanTagSendToPortAndGoToStripVlanTagTable").setId(flowId)
.setKey(new FlowKey(flowId)).setCookie(flowCookie);
MatchBuilder matchBuilder = new MatchBuilder();
createMetadataMatch(matchBuilder, flowCookie.getValue());
InstructionBuilder ib = new InstructionBuilder();
Instruction createVlanTag = FlowUtils.createSetVlanAndOutputToPortInstructions(
SdnMudConstants.MUD_RULE_HIT_LABEL, outputPortUri);
InstructionsBuilder insb = new InstructionsBuilder();
ArrayList<Instruction> instructions = new ArrayList<Instruction>();
instructions.add(createVlanTag);
Instruction gotoInstruction = ib.setInstruction(new GoToTableCaseBuilder()
.setGoToTable(new GoToTableBuilder().setTableId(SdnMudConstants.STRIP_VLAN_RULE_TABLE).build()).build())
.setOrder(3)
.setKey(new InstructionKey(0)).build();
instructions.add(gotoInstruction);
insb.setInstruction(instructions);
tagPacketFlow.setMatch(matchBuilder.build()).setInstructions(insb.build())
.setPriority(35).setBufferId(OFConstants.ANY)
.setHardTimeout(time).setIdleTimeout(0).setFlags(new FlowModFlags(false, false, false, false, false));
Upon invoking the code I see this in openvswitch:
cookie=0x523f476a, duration=0.012s, table=2, n_packets=0, n_bytes=0, hard_timeout=30000, priority=35,metadata=0x523f476a actions=goto_table:3
And here's the dump from the config datastore corresponding to this flow:
{
"buffer_id": 4294967295,
"cookie": 1379878762,
"flags": "",
"flow-name": "metadataMatchSetVlanTagSendToPortAndGoToStripVlanTagTable",
"hard-timeout": 30000,
"id": "toaster.nist.gov/42",
"idle-timeout": 0,
"instructions": {
"instruction": [
{
"go-to-table": {
"table_id": 3
},
"order": 0
}
]
},
"match": {
"metadata": {
"metadata": 1379878762
}
},
"priority": 35,
"table_id": 2
}
So the Vlan Setting just disappeared.
==== End UPDATE ====
==== UPDATE 1 ====
I logged the flow before committing the transaction. Here's the set VLAN instruction :
ApplyActionsCase [_applyActions=ApplyActions
[_action=[Action [_action=PushVlanActionCase
[_pushVlanAction=PushVlanAction [_ethernetType=33024,
_vlanId=VlanId [_value=1001], augmentation=[]], augmentation=[]],
_key=ActionKey [_order=0], _order=0, augmentation=[]],
Action [_action=SetVlanIdActionCase[_setVlanIdAction=SetVlanIdAction
[_vlanId=VlanId [_value=1001], augmentation=[]],
augmentation=[]], _key=ActionKey [_order=1], _order=1,
augmentation=[]], Action [_action=OutputActionCase
[_outputAction=OutputAction [_maxLength=65535,
_outputNodeConnector=Uri [_value=openflow:1:6],
augmentation=[]], augmentation=[]],
_key=ActionKey [_order=2], _order=2,
augmentation=[]]], augmentation=[]], augmentation=[]]
I can't see anything wrong with it.
=== End UPDATE 1 ===
=== Update 2 ===
When I remove the goto and follow the pattern of the xml here:
https://wiki.opendaylight.org/view/Editing_OpenDaylight_OpenFlow_Plugin:End_to_End_Flows:Example_Flows#Push_VLAN
it only works WITHOUT the goto. In other words if I remove the goto I can see the push flow in the config datastore. If I put the goto in, ONLY the goto appears.
==== End Update 2 ====
I see an issue in the issue tracker about vlan flows in opendaylight soutbound being broken but it appears to have been fixed in 2014 (?).
Is this fixed in nitrogen and how can I go about filing a bug against opendaylight?

Try this :
Integer VLAN_ETHERTYPE = 0x8100;
ActionBuilder actionBuilder = new ActionBuilder();
List<Action> actions = new ArrayList<>();
//push vlan
Action pushVlanAction = actionBuilder
.setOrder(0).setAction(new PushVlanActionCaseBuilder()
.setPushVlanAction(new PushVlanActionBuilder()
.setEthernetType(VLAN_ETHERTYPE)
.build())
.build())
.build();
actions.add(pushVlanAction);
//set vlan id
Action setVlanIdAction = actionBuilder
.setOrder(1).setAction(new SetFieldCaseBuilder()
.setSetField(new SetFieldBuilder()
.setVlanMatch(new VlanMatchBuilder()
.setVlanId(new VlanIdBuilder()
.setVlanId(new VlanId(vlanID))
.setVlanIdPresent(true)
.build())
.build())
.build())
.build())
.build();
actions.add(setVlanIdAction);
Then, you need to add your actions into your instructions in the following way:
//ApplyActions
ApplyActions applyActions = new ApplyActionsBuilder().setAction(actions).build();
//Instruction
Instruction applyActionsInstruction = new InstructionBuilder()
.setOrder(0).setInstruction(new ApplyActionsCaseBuilder()
.setApplyActions(applyActions)
.build())
.build();
Also take a look here.

After upgrading to Nitrogen, I found that my problem goes away. So there appears to have been a bug in the Carbon release. Not sure when it got fixed.

Related

Call fetchgit without SSL Verify

I'm trying to use fetchgit to download source repos from my lab's private GitLab server, which currently self-signs its SSL certificate.
default.nix:
with (import <nixpkgs> {});
{ test-pkg = callPackage ./test-pkg.nix {
buildPythonPackage = python35Packages.buildPythonPackage;
};
}
test-pkg.nix:
{ buildPythonPackage,fetchgit }:
buildPythonPackage rec {
pname = "test-pkg";
version = "0.2.1";
src = fetchgit {
url = "https://gitlabserver/experiment-deployment/test-pkg";
rev = "refs/tags/v${version}";
sha256 = "43c2c9e5e7a16b6c88ba3088a9bfc82f7db8e13378be7c78d6c14a5f8ed05afd";
};
}
Which results in the error when I call nix-shell
fatal: unable to access 'https://gitlabserver/experiment-deployment/test-pkg/': SSL certificate problem: self signed certificate
Looking at, build-support/fetchgit, it seems that fetchgit is made with mkDerivation, so I tried to make a new fetchgit using overrideAttrs. I pass in the git environment variable to make git ignore SSL verification, expecting that the variable will be initialized during the setup phase.
revised default.nix:
with (import <nixpkgs> {});
let fetchgit-no-verify = fetchgit.overrideAttrs { GIT_SSL_NO_VERIFY=true;} ;
in rec {
test-pkg = callPackage ./test-pkg.nix {
buildPythonPackage = python35Packages.buildPythonPackage;
fetchgit = fetchgit-no-verify;
};
}
I thought I was really clever when I thought of this over the weekend, only to discover that when implemented my new error states that
error: attribute 'overrideAttrs' missing, at [...]/default.nix:2:26
Inspecting fetchgit in nix repl shows that it is a functor attribute set. I tried for a little bit to get to the overrideAttrs, without success. Trying again I saw that git could be passed to to fetchGit,
re-revised default.nix:
with (import <nixpkgs> {});
let git = git.overrideAttrs { GIT_SSL_NO_VERIFY=true;} ;
fetchgit-no-verify = fetchgit.override { git=git-no-verify;} ;
in rec {
test-pkg = callPackage ./test-pkg.nix {
buildPythonPackage = python35Packages.buildPythonPackage;
fetchgit = fetchgit-no-verify;
};
}
but the new error:
error: attempt to call something which is not a function but a set, at /nix/store/jmynn33vcn3mcscsch0zf46fz9wsw05y-nixpkgs-20.03pre193309.c4196cca9ac/nixpkgs/pkgs/stdenv/generic/make-derivation.nix:318:55
Finally, onto my questions. Is there a way to add the environment variable to the fetchgit or git derivations? Is there perhaps another way to connect--some builtin option I missed? I could use a private repository, using ssh and avoiding https, however due to how we deploy experiments I'd like to avoid that.
I was able to make this work with this ugly thing.
default.nix:
with (import <nixpkgs> {});
let fetchgit-no-verify = fetchgit // {
__functor = self : args :
(fetchgit.__functor self args).overrideAttrs (oldAttrs:{GIT_SSL_NO_VERIFY=true;});
} ;
in rec {
test-pkg = callPackage ./test-pkg.nix {
buildPythonPackage = python35Packages.buildPythonPackage;
fetchgit = fetchgit-no-verify;
};
}
fetchgit-no-verify uses the fetchgit functor set to begin with and overwrites the __functor attribute with a new function. The new functor just applies its arguments and then calls overrideAttrs.
This works, but I'm happy to award the answer to anybody who can add some insight or comes with another solution. For one, I'd like to know how the fetchgit derivation becomes a functor. Is this something callPackage does?.

softlayer api : How to upgrade a block storage volume size

i tried to upgrade block(performance) storage volume and IOPs via API.
test code returns the error message :
"Error: com.softlayer.api.ApiException$Internal: Invalid price Block Storage (189443) provided on the order container.(code: SoftLayer_Exception_Order_Item_Invalid, status: 500)"
I am using placeOrder and verifyOrder method for order.
where can i find sample code to upgrade storage volume?
public void test03() throws Exception {
System.out.println("\nStorage Upgrade Test Start !!\n");
ApiClient client = new RestApiClient().withCredentials(username, apiKey);
com.softlayer.api.service.container.product.order.network.storage.asaservice.Upgrade storage = new com.softlayer.api.service.container.product.order.network.storage.asaservice.Upgrade();
Storage.Service service = Storage.service(client, 38366457L);
service.withMask().accountId();
service.withMask().id();
service.withMask().bytesUsed();
service.withMask().osTypeId();
service.withMask().iops();
service.withMask().username();
service.withMask().allowedIpAddresses();
service.withMask().replicationStatus();
service.withMask().parentVolume();
service.withMask().parentVolume().volumeStatus();
service.withMask().serviceResourceBackendIpAddress();
service.withMask().serviceResource().datacenter();
service.withMask().allowedHardware().allowedHost().credential().username().password();
service.withMask().allowedSubnets();
service.withMask().allowedVirtualGuests().allowedHost().credential().username().password();
service.withMask().allowedIpAddresses().allowedHost().credential().username().password();
service.withMask().snapshotCapacityGb();
service.withMask().snapshotSizeBytes();
service.withMask().snapshotSpaceAvailable();
service.withMask().parentVolume().snapshotSizeBytes();
service.withMask().parentVolume().snapshotSpaceAvailable();
service.withMask().properties().type();
service.withMask().billingItem();
service.withMask().billingItem().children().activeFlag();
service.withMask().billingItem().children().item();
service.withMask().properties().volume();
service.withMask().capacityGb();
service.withMask().nasType();
Storage storage1 = service.getObject();
Order order = null;
try {
// 1. Storage volume
storage.setVolumeSize(80L);
storage.setIops(400L);
storage1.setUpgradableFlag(true);
storage.setVolume(storage1);
order = storage;
// Set SoftLayer Package Id
order.setPackageId(759L);
order.setUseHourlyPricing(true);
// Set Data Center Location
order.setLocation("1854895");
List<Price> S_prices = new ArrayList<Price>();
//International Services
Price price1 = new Price();
price1.setId(189433L);
// 2. Block/File Storage
Price price2 = new Price();
price2.setId(189443L); //Block Storage
//Storage Space
Price price3 = new Price();
price3.setId(189753L);
//IOPS
Price price4 = new Price();
price4.setId(189813L);
S_prices.add(price1);
S_prices.add(price2);
S_prices.add(price3);
S_prices.add(price4);
// Set Item Prices
order.getPrices().addAll(S_prices);
Order baseContainer = new Order();
baseContainer.getOrderContainers().add(order);
// verify
Order verifiedOrder = com.softlayer.api.service.product.Order.service(client).verifyOrder(baseContainer);
// placeorder
com.softlayer.api.service.container.product.order.Receipt receipt = com.softlayer.api.service.product.Order.service(client).placeOrder(baseContainer, false);
} catch (Exception e) {
System.out.println("Error: " + e);
} finally {
System.out.println("\nTest End !!\n");
}
}
try deleting this price:
// 2. Block/File Storage
Price price2 = new Price();
price2.setId(189443L); //Block Storage
As you are upgrading a "storage_as_a_service" you only need that price (189433) and the prices for the volume size and IOPS
This is the RESTFul request that I used:
POST https://$USERNAME:$APIKEY#api.softlayer.com/rest/v3/SoftLayer_Product_Order/placeOrder
{
"parameters": [{
"complexType": "SoftLayer_Container_Product_Order_Network_Storage_AsAService_Upgrade",
"packageId": 759,
"volume": {
"id": 38740447
},
"volumeSize": 2000,
"iops": 1000,
"useHourlyPricing": true,
"prices": [{
"id": 190233
}, {
"id": 190293
}, {
"id": 189433
}],
"quantity": 1
}]
}
So I recommend you:
1.- Try upgrading your block storage using the control portal, it may an issue with your account or your block storage.
2.- Try the upgrading using the RESTFul request, maybe the java client is sending wrong the request.
3.- Try Looging your Java code and see if the RESTFul request that your Java code is sending is similar to the RESTFUL request that I posted for that you need to this:
Logging Logging the requests and response to stdout can be enabled by
invoking withLoggingEnabled on the RestApiClient. In order to log
elsewhere, simply make your own implementation of RestApiClient with
logRequest and logResponse overridden.
e.g.
ApiClient client = new RestApiClient().withCredentials(username, apiKey).withLoggingEnabled();
Regards
I solved a problem.
my code had two issue.
first, in case of upgrading a storage(Block/File), the Type isn't need
// 2. Block/File Storage
Price price2 = new Price();
price2.setId(189443L); //Block Storage
two, Wrapping Order of the upgrade's container isn't need
because to upgrade storage, the ComplexType must be "SoftLayer_Container_Product_Order_Network_Storage_AsAService_Upgrade"
but Order's ComplexType is "SoftLayer_Container_Product_Order"
Order baseContainer = new Order(); <-- ComplextType : SoftLayer_Container_Product_Order
baseContainer.getOrderContainers().add(order);
so i deleted them and I modifed the verifyOrder and placeOrder parameters to order variable.
Order verifiedOrder = com.softlayer.api.service.product.Order.service(client).verifyOrder(order);
// placeorder
com.softlayer.api.service.container.product.order.Receipt receipt = com.softlayer.api.service.product.Order.service(client).placeOrder(order, false);
this is a final code
public void test03() throws Exception {
System.out.println("\nStorage Upgrade Test Start !!\n");
ApiClient client = new RestApiClient().withCredentials(username, apiKey);
com.softlayer.api.service.container.product.order.network.storage.asaservice.Upgrade storage = new com.softlayer.api.service.container.product.order.network.storage.asaservice.Upgrade();
Storage.Service service = Storage.service(client, 38366457L);
service.withMask().id();
Storage storage1 = service.getObject();
Order order = null;
try {
// 1. Storage volume
storage.setVolumeSize(80L);
storage.setIops(400L);
storage1.setUpgradableFlag(true);
storage.setVolume(storage1);
order = storage;
// Set SoftLayer Package Id
order.setPackageId(759L);
order.setUseHourlyPricing(true);
// Set Data Center Location
order.setLocation("1854895");
List<Price> S_prices = new ArrayList<Price>();
//International Services
Price price1 = new Price();
price1.setId(189433L);
//Storage Space
Price price3 = new Price();
price3.setId(189753L);
//IOPS
Price price4 = new Price();
price4.setId(189813L);
S_prices.add(price1);
S_prices.add(price3);
S_prices.add(price4);
// Set Item Prices
order.getPrices().addAll(S_prices);
// verify
Order verifiedOrder = com.softlayer.api.service.product.Order.service(client).verifyOrder(order);
// placeorder
com.softlayer.api.service.container.product.order.Receipt receipt = com.softlayer.api.service.product.Order.service(client).placeOrder(order, false);
} catch (Exception e) {
System.out.println("Error: " + e);
} finally {
System.out.println("\nTest End !!\n");
}
}

EPiServer 9 - Add block to new page programmatically

I have found some suggestions on how to add a block to a page, but can't get it to work the way I want, so perhaps someone can help out.
What I want to do is to have a scheduled job that reads through a file, creating new pages with a certain pagetype and in the new page adding some blocks to a content property. The blocks fields will be updated with data from the file that is read.
I have the following code in the scheduled job, but it fails at
repo.Save((IContent) newBlock, SaveAction.Publish);
giving the error
The page name must contain at least one visible character.
This is my code:
public override string Execute()
{
//Call OnStatusChanged to periodically notify progress of job for manually started jobs
OnStatusChanged(String.Format("Starting execution of {0}", this.GetType()));
//Create Person page
PageReference parent = PageReference.StartPage;
//IContentRepository contentRepository = EPiServer.ServiceLocation.ServiceLocator.Current.GetInstance<IContentRepository>();
//IContentTypeRepository contentTypeRepository = EPiServer.ServiceLocation.ServiceLocator.Current.GetInstance<IContentTypeRepository>();
//var repository = EPiServer.ServiceLocation.ServiceLocator.Current.GetInstance<IContentRepository>();
//var slaegtPage = repository.GetDefault<SlaegtPage>(ContentReference.StartPage);
IContentRepository contentRepository = EPiServer.ServiceLocation.ServiceLocator.Current.GetInstance<IContentRepository>();
IContentTypeRepository contentTypeRepository = EPiServer.ServiceLocation.ServiceLocator.Current.GetInstance<IContentTypeRepository>();
SlaegtPage slaegtPage = contentRepository.GetDefault<SlaegtPage>(parent, contentTypeRepository.Load("SlaegtPage").ID);
if (slaegtPage.MainContentArea == null) {
slaegtPage.MainContentArea = new ContentArea();
}
slaegtPage.PageName = "001 Kim";
//Create block
var repo = ServiceLocator.Current.GetInstance<IContentRepository>();
var newBlock = repo.GetDefault<SlaegtPersonBlock1>(ContentReference.GlobalBlockFolder);
newBlock.PersonId = "001";
newBlock.PersonName = "Kim";
newBlock.PersonBirthdate = "01 jan 1901";
repo.Save((IContent) newBlock, SaveAction.Publish);
//Add block
slaegtPage.MainContentArea.Items.Add(new ContentAreaItem
{
ContentLink = ((IContent) newBlock).ContentLink
});
slaegtPage.URLSegment = UrlSegment.CreateUrlSegment(slaegtPage);
contentRepository.Save(slaegtPage, EPiServer.DataAccess.SaveAction.Publish);
_stopSignaled = true;
//For long running jobs periodically check if stop is signaled and if so stop execution
if (_stopSignaled) {
return "Stop of job was called";
}
return "Change to message that describes outcome of execution";
}
You can set the Name by
((IContent) newBlock).Name = "MyName";

Acumatica: How do I get an attachment file from SO Screen using Web API?

I'd folow the example From I200 pdf for a stock item, but I dont' know how to download the file from an Sales Order. Does anybody has a clue?
IN202500Content stockItemSchema = context.IN202500GetSchema();
var commands = new Command[]
{
new Value
{
Value = "AAMACHINE1",
LinkedCommand = stockItemSchema.StockItemSummary.InventoryID
},
new Value
{
FieldName = "T2MCRO.jpg",
LinkedCommand =
stockItemSchema.StockItemSummary.ServiceCommands.Attachment
}
};
var stockItemAttachment =
context.IN202500Export(commands, null, 1, false, true);
You were almost there, in the "stockItemAttachment" variable you should have the content of the file "T2MCRO.jpg" in byte format.
The only thing you have left to do is to write it to your file system.
You can use the following command :
File.WriteAllBytes(Path, Convert.FromBase64String(stockItemAttachment[0][0]));

jmeter testcases which can handle captcha?

We are trying to build a jmeter testcase which does the following:
login to a system
obtain some information and check whether correct.
Where we are facing issues is because there is a captcha while logging into the system. What we had planned to do was to download the captcha link and display, and wait for user to type in the value. Once done, everything goes as usual.
We couldnt find any plugin that can do the same? Other than writing our own plugin, is there any option here?
I was able to solve it myself. The solution is as follows:
Create a JSR223 PostProcessor (using Groovy)
more practical CAPTCHA example with JSESSIONID handling and proxy setting
using image.flush() to prevent stale CAPTCHA image in dialog box
JSR223 Parameters for proxy connection setting:
Parameters: proxy 10.0.0.1 8080
In it, the following code displays the captcha and waits for user input
import java.awt.Image;
import java.awt.Toolkit;
import javax.swing.Icon;
import javax.swing.JOptionPane;
import org.apache.jmeter.threads.JMeterContextService;
import org.apache.jmeter.threads.JMeterContext;
import org.apache.jmeter.protocol.http.control.CookieManager;
import org.apache.jmeter.protocol.http.control.Cookie;
URL urlTemp ;
urlTemp = new URL( "https://your.domainname.com/endpoint/CAPTCHACode");
HttpURLConnection myGetContent = null;
if(args[0]=="proxy" ){
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(args[1], Integer.parseInt(args[2])));
myGetContent = (HttpURLConnection) urlTemp.openConnection(proxy);
}else{
myGetContent = (HttpURLConnection) urlTemp.openConnection();
}
// false for http GET
myGetContent.setDoOutput(false);
myGetContent.connect();
int status = myGetContent.getResponseCode();
log.info("HTTP Status Code: "+Integer.toString(status));
if (status == HttpURLConnection.HTTP_OK) {
//We have 2 Set-Cookie headers in response message but 1 Set-Cookie entry in Map
String[] parts2;
for (Map.Entry<String, List<String>> entries : myGetContent.getHeaderFields().entrySet()) {
if( entries.getKey() == "Set-Cookie" ){
for (String value : entries.getValue()) {
if ( value.contains("JSESSIONID") == true ){
String[] parts = value.split(";",2);
log.info("Response header: "+ entries.getKey() + " - " + parts[0] );
JMeterContext context = JMeterContextService.getContext();
CookieManager manager = context.getCurrentSampler().getCookieManager();
parts2 = parts[0].split("=",2)
Cookie cookie = new Cookie("JSESSIONID",parts2[1],"your.domainname.com","/endpoint",true,0, true, true, 0);
manager.add(cookie);
log.info( cookie.toString() );
log.info("CookieCount "+ manager.getCookieCount().toString() );
}
}
}
}//end of outer for loop
if ( parts2.find() == null ) {
throw new Exception("The Response Header not contain Set-Cookie:JSESSIONID= .");
}
}else{
throw new Exception("The Http Status Code was ${status} , not expected 200 OK.");
}
BufferedInputStream bins = new BufferedInputStream(myGetContent.getInputStream());
String destFile = "number.png";
File f = new File(destFile);
if(f.exists() ) {
boolean fileDeleted = f.delete();
log.info("delete file ... ");
log.info(String.valueOf(fileDeleted));
}
FileOutputStream fout =new FileOutputStream(destFile);
int m = 0;
byte[] bytesIn = new byte[1024];
while ((m = bins.read(bytesIn)) != -1) {
fout.write(bytesIn, 0, m);
}
fout.close();
bins.close();
log.info("File " +destFile +" downloaded successfully");
Image image = Toolkit.getDefaultToolkit().getImage(destFile);
image.flush(); // release the prior cache of Captcha image
Icon icon = new javax.swing.ImageIcon(image);
JOptionPane pane = new JOptionPane("Enter Captcha", 0, 0, null);
String captcha = pane.showInputDialog(null, "Captcha", "Captcha", 0, icon, null, null);
captcha = captcha.trim();
captcha = captcha.replaceAll("\r\n", "");
log.info(captcha);
vars.put("captcha", captcha);
myGetContent.disconnect();
By vars.put method we can use the captcha variable in any way we want. Thank you everyone who tried to help.
Since CAPTHA used to detect non-humans, JMeter will always fail it.
You have to make a workaround in your software: either disable captcha requesting or print somewhere on page correct captcha. Of course, only for JMeter tests.
Dirty workaround? Print the captcha value in alt image for the tests. And then you can retrieve the value and go on.