remove commented block in xml ruby - ruby

I'm required to write a script that can remove a commented block in xml file, and save it back to its directory.
<Configure id="Server" class="org.eclipse.jetty.server.Server">
<!-- =========================================================== -->
<!-- Server Thread Pool -->
<!-- =========================================================== -->
<Set name="ThreadPool">
<!-- Default queued blocking threadpool -->
<New class="org.eclipse.jetty.util.thread.QueuedThreadPool">
<Set name="minThreads">10</Set>
<Set name="maxThreads">10000</Set>
<Set name="detailedDump">false</Set>
</New>
</Set>
<!-- =========================================================== -->
<!-- Set connectors -->
<!-- =========================================================== -->
<!--
<Call name="addConnector">
<Arg>
<New class="org.eclipse.jetty.server.nio.SelectChannelConnector">
<Set name="host"><SystemProperty name="jetty.host" /></Set>
<Set name="port"><SystemProperty name="jetty.port" default="8983"/></Set>
<Set name="maxIdleTime">50000</Set>
<Set name="Acceptors">2</Set>
<Set name="statsOn">false</Set>
<Set name="confidentialPort">8443</Set>
<Set name="lowResourcesConnections">5000</Set>
<Set name="lowResourcesMaxIdleTime">5000</Set>
</New>
</Arg>
</Call>
-->
<Call name="addConnector">
<Arg>
<New class="org.eclipse.jetty.server.bio.SocketConnector">
<Set name="host"><SystemProperty name="jetty.host" /></Set>
<Set name="port"><SystemProperty name="jetty.port" default="8983"/></Set>
<Set name="maxIdleTime">50000</Set>
<Set name="lowResourceMaxIdleTime">1500</Set>
<Set name="statsOn">false</Set>
</New>
</Arg>
</Call>
</Configure>
on this xml
How can I comment out this block only?
<!--
<Call name="addConnector">
<Arg>
<New class="org.eclipse.jetty.server.nio.SelectChannelConnector">
<Set name="host"><SystemProperty name="jetty.host" /></Set>
<Set name="port"><SystemProperty name="jetty.port" default="8983"/></Set>
<Set name="maxIdleTime">50000</Set>
<Set name="Acceptors">2</Set>
<Set name="statsOn">false</Set>
<Set name="confidentialPort">8443</Set>
<Set name="lowResourcesConnections">5000</Set>
<Set name="lowResourcesMaxIdleTime">5000</Set>
</New>
</Arg>
</Call>
-->
I have tried it with this but
require 'nokogiri'
file = File.read("jetty.xml")
xml = Nokogiri::XML(file)
#replace <!-- --> with a space
xml.xpath("//comment()").each do |node|
node.content =node.content.gsub!(/(^\D\W[<!\-\-}]\W[\-\->])/,' ')
end
File.open("newjetty.xml","w") do |f|
f.write xml.to_xml
end
this code only remove the text within the comment
Output:
<!---->
<!---->
<!---->
<Set name="ThreadPool">
<!---->
<New class="org.eclipse.jetty.util.thread.QueuedThreadPool">
<Set name="minThreads">10</Set>
<Set name="maxThreads">10000</Set>
<Set name="detailedDump">false</Set>
</New>
</Set>
<!---->
<!---->
<!---->
<!---->
<!---->

You should delete the node, as it is a comment node. You can use the inner text to parse it and add it again.
require 'nokogiri'
file = File.read("jetty.xml")
xml = Nokogiri::XML(file)
#replace <!-- --> with a space
xml.xpath("//comment()").each do |node|
t = Nokogiri::XML::DocumentFragment.parse(node.content)
node.add_next_sibling(t)
node.remove
end
File.open("newjetty.xml","w") do |f|
f.write xml.to_xml
end
Here you are parsing the comments content, add it as the next sibling and remove the node itself.
This basically works, however the string-only contents are also added as nodes, making this a mixed content document, which you most certainly do not want for a jetty configuration file.
So there should also be some logic included that checks for the node type (text versus element) and only includes elements.

Related

NLog is not logging on Oracle database, Please how can I get it right

I want to log into Oracle database table using NLog but nothing gets logged. Below is NLog.config file am using. Please what am I doing wrongly?
<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
autoReload="true"
throwConfigExceptions="true"
internalLogLevel="info"
internalLogFile="Logtxt.txt">
<extensions>
<add assembly="NLog.Web.AspNetCore"/>
</extensions>
<targets>
<target name="database" xsi:type="Database" keepConnection="false" useTransactions="true"
dbProvider="System.Data.OracleClient.OracleConnection,System.Data.OracleClient, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
connectionString="Data Source=#####;User ID=######;password=******;Integrated Security=no;"
commandText="insert into DBO_ERRORLOGS(LOGID,LEVEL,CALLSITE,TYPE,MESSAGE,STACKTRACE,INNEREXCEPTION,ADDITINALINFO,LOGGEDONDATE,USERNAME) values('',:LEVEL,:CALLSITE,:TYPE,:MESSAGE,:STACKTRACE,:INNEREXCEPTION,:ADDITIONALINFO,:DATE,:USERNAME)">
<parameter name="LEVEL" layout="${Level}" />
<parameter name="CALLSITE" layout="${Callsite}" />
<parameter name="DATE" layout="${date}" />
<parameter name="TYPE" layout="${exception:format=Type}" />
<parameter name="MESSAGE" layout="${exception:format=Message}" />
<parameter name="STACKTRACE" layout="${exception:format=StackTrace}" />
<parameter name="INNEREXCEPTION" layout="${exception:format=:innerFormat=ShortType,Message,Method:MaxInnerExceptionLevel=1:InnerExceptionSeparator=}" />
<parameter name="ADDITIONALINFO" layout="${Message}" />
<parameter name="USERNAME" layout="${identity}" />
</target>
</targets>
<rules>
<logger name="*" minlevel="Debug" writeTo="database" />
</rules>
</nlog>
Without an error message (see below how to find it), it's a bit guessing. But I think it's an issue you are sending all the parameters as strings. So add the dbType to the parameters, like:
<parameter name="DATE" layout="${date}" dbType="DateTime" />
For the actual error, you should check the internal log. It should be there!
Check Logtxt.txt. See internalLogFile="Logtxt.txt". And you can't find it, change it to an absolute path, e.g. internalLogFile="C:\temp\Logtxt.txt"

not able to get the flow scope variable from one state transition to another state transition junit

When I transit from view state to decision state or action state all the input set is lost while transitioning to another state. How to do I get the flow scope variable for decision state or action state on transitioning from view state to decision state and action state in junit ?
In my flow definition right now I am in view state when I set the event Id as submit it moves to registerEnroll decision state where it needs flowScope.regform.loyaltyLookUp value. When I see the flow execution variable map there is nothing inside apart from RegForm object, even though I have set variable in MutableAttributeMap.
How to set the flow scope variable which will be always available on transitioning to state on junit test case for spring webflow?
In second test case flow is going to else part of decision state even though I have provide flowScope.regform.loyaltyLookUp in input. What mistake I am doing I am not able to figure out .
xml
<?xml version="1.0" encoding="UTF-8"?>
<flow xmlns="http://www.springframework.org/schema/webflow"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/webflow
http://www.springframework.org/schema/webflow/spring-webflow-2.4.xsd"
start-state="confirmsuccess">
<var name="regform" class="com.shc.ecom.usr.form.Regform" />
<var name="enrollresponse" class="com.shc.ecom.usr.service.adapter.ResponseVO" />
<!-- <input-mapper> <input-attribute name="service" /> <input-attribute
name="regform" /> <input-attribute name="success" /> </input-mapper> <start-state
idref="confirmsuccess" /> -->
<input name="service" />
<input name="regform" />
<input name="success" />
<input name="enrollresponse"/>
<decision-state id="confirmsuccess">
<if test="flowScope.success!=null" then="serviceticketvalidation"
else="saveQueryParamInSession" />
</decision-state>
<decision-state id="serviceticketvalidation">
<if test="flowScope.success=='yes'" then="sywNumAction" else="ssoerrorredirect" />
</decision-state>
<!-- <action-state id="enterCustInfo"> <action bean="regEnrollFormAction"
method="setupForm" > </action> <transition on="success" to="renderform"/>
</action-state> -->
<!-- save query parameter in session -->
<action-state id="saveQueryParamInSession">
<evaluate expression="saveQueryParamInSession.doExecute(flowRequestContext)" />
<transition on="success" to="renderform" />
</action-state>
<view-state id="renderform" view="/regenroll" >
<on-entry>
<evaluate expression="regEnrollFormAction.setupForm(flowRequestContext)" />
<set name="flowScope.sourceSite" value="requestParameters.sid" /> <!-- scope="flow" -->
<set name="flowScope.service" value="requestParameters.service" />
<set name="flowScope.clienthost" value="requestParameters.clienthost" />
<set name="flowScope.target" value="requestParameters.target" />
<set name="flowScope.switchForm" value="requestParameters.switchForm" />
<set name="flowScope.oldlogin" value="requestParameters.oldlogin" />
<set name="flowScope.emailId" value="requestParameters.emailId" />
<set name="flowScope.confirmEmail" value="requestParameters.emailConfirm" />
<set name="flowScope.fname" value="requestParameters.fname" />
<set name="flowScope.lname" value="requestParameters.lname" />
<set name="flowScope.zipCode" value="requestParameters.zip" />
<set name="flowScope.modifyservice" value="requestParameters.modifyservice" />
<set name="flowScope.ocpPage" value="requestParameters.ocpPage" />
<set name="flowScope.fullpage" value="requestParameters.fullpage" />
<set name="flowScope.emailValidateFlag" value="requestParameters.emailValidateFlag" />
<set name="flowScope.mode" value="requestParameters.mode" />
<set name="flowScope.phone" value="requestParameters.phone" />
<set name="flowScope.number" value="requestParameters.number" />
<set name="flowScope.irp" value="requestParameters.irp" />
<set name="flowScope.sywmax" value="requestParameters.sywmax" />
</on-entry>
<transition on="submit" to="registerEnroll">
<evaluate expression="regEnrollFormAction.bindAndValidate(flowRequestContext)"></evaluate>
</transition>
</view-state>
<decision-state id="registerEnroll">
<if test="flowScope.regform.loyaltyLookUp!=null" then="processEnroll"
else="activateEnroll" />
</decision-state>
<action-state id="processEnroll">
<evaluate
expression="ssoGatewayService.register(flowScope.regform,externalContext)" result="flowScope.enrollresponse" result-type="com.shc.ecom.usr.service.adapter.ResponseVO" />
<transition on="success" to="postenroll" />
</action-state>
<decision-state id="postenroll">
<if test="flowScope.enrollresponse.responseCode ==200" then="ccenroll"
else="enrollerror" />
</decision-state>
<decision-state id="ccenroll">
<if test="flowScope.regform.craftsmanAffinity!=null" then="ccAffinityUpdate"
else="go_to_login_flow" />
</decision-state>
<action-state id="ccAffinityUpdate">
<evaluate
expression="ssoGatewayService.updateCCAffinity(flowScope.regform, flowScope.enrollresponse)"
result="enrollresponse" />
<transition on="success" to="postccupdate" />
</action-state>
<decision-state id="postccupdate">
<if test="flowScope.enrollresponse.responseCode==200" then="go_to_login_flow"
else="ccupdateerror" />
</decision-state>
<decision-state id="enrollerror">
<if test="flowScope.enrollresponse.existingUserInd!=null" then="existingUserLogin"
else="captchaValidation" />
</decision-state>
<decision-state id="captchaValidation">
<if test="flowScope.enrollresponse.errorCode eq '401.1'" then="captchaValidationError"
else="loyaltydown" />
</decision-state>
<decision-state id="loyaltydown">
<if test="flowScope.enrollresponse.loyaltyDown!=null" then="loyaltydownerror"
else="showerror" />
</decision-state>
<action-state id="activateEnroll">
<evaluate expression="ssoGatewayService.onlineActivation(flowScope.regform, requestParameters.clienthost,
externalContext, requestParameters.mode, requestParameters.number, requestParameters.phone)"
result = "enrollresponse" />
<transition on="success" to="postenroll" />
</action-state>
<subflow-state id="go_to_login_flow" subflow="shclogin-flow">
<input value="flowScope.regform.password" name="logonPassword"/>
<input value="flowScope.regform.email" name="loginId"/>
<input value="flowScope.regform.sid" name="sourceSiteId"/>
<input value="flowScope.regform.service" name="service"/>
<input value="flowScope.regform.redirectUrl" name="redirectUrl"/>
<input value="flowScope.reglogin" name="reglogin"/>
<input value="flowScope.enrollresponse" name="enrollresponse"/>
<transition on="finish" to="process_and_redirect" />
<transition on="redirect" to="process_and_redirect" />
<transition on="sendtickettomodal_reg" to="sendtickettomodal">
<set name="clienthost" value="requestParameters.clienthost" /> <!-- scope="flow" -->
</transition>
<transition on="pickup_error_redirect_reg" to="ssoerrorredirect" />
<transition on="pickup_error_redirect_login" to="ssoerrorredirect" />
</subflow-state>
<!--
<attribute-mapper>
<input-mapper>
<mapping source="${flowScope.regform.email}" target="loginId" />
<mapping source="${flowScope.regform.password}" target="logonPassword" />
<mapping source="${flowScope.regform.sid}" target="sourceSiteId" />
<mapping source="${flowScope.regform.service}" target="service" />
<mapping source="${flowScope.regform.redirectUrl}" target="redirectUrl" />
<mapping source="${flowScope.reglogin}" target="reglogin" />
<mapping source="${flowScope.enrollresponse}" target="enrollresponse" />
</input-mapper>
</attribute-mapper>
-->
<action-state id="sywNumAction">
<evaluate expression="sywNumSetupAction" />
<transition on="success" to="process_and_redirect" />
</action-state>
<end-state id="process_and_redirect" view="/successconfirmation">
<on-entry>
<set name="sourceSiteId" value="flowScope.regform.sid" />
<set name="sywrNumber" value="flowScope.sywrNumber" />
<set name ="softLinkFlow" value="requestParameters.softLinkFlow" />
<set name ="fullpage" value="requestParameters.fullpage" />
<set name="targetUrl" value="requestParameters.targetUrl" />
</on-entry>
</end-state>
<view-state id="showerror" view="/displayerror">
<on-entry>
<set name="errorCode" value="flowScope.enrollresponse.responseCode" />
<set name="responseString" value="flowScope.enrollresponse.responseString" />
</on-entry>
</view-state>
<view-state id="captchaValidationError" view="/displayerror">
<on-entry>
<set name="errorCode" value="401.1" />
<set name="responseString" value="flowScope.enrollresponse.errorDescription" />
</on-entry>
</view-state>
<view-state id="loyaltydownerror" view="/displayerror">
<on-entry>
<set name="errorCode" value="500.2" />
<set name="responseString" value="flowScope.enrollresponse.responseString" />
</on-entry>
</view-state>
<end-state id="existingUserLogin" view="/existingUserLogin">
<on-entry>
<set name="returnCode" value="'500.110'" />
<set name="clienthost" value="requestParameters.clienthost" />
<set name="emailId" value="flowScope.regform.email" />
</on-entry>
</end-state>
<view-state id="ccupdateerror" view="/ccEnrollError">
<on-entry>
<set name="returnCode" value="'500.111'" />
<set name="clienthost" value="requestParameters.clienthost" />
<set name="emailId" value="flowScope.regform.email" />
</on-entry>
</view-state>
<!-- redirect the next step from login flow -->
<end-state id="ssoerrorredirect" view="/successconfirmationwithssoerror">
<on-entry>
<set name="sourceSiteId" value="flowScope.regform.sid" />
<set name="sywrNumber" value="flowScope.sywrNumber" />
<set name="softLinkFlow" value="requestParameters.softLinkFlow" />
<set name="fullpage" value="requestParameters.fullpage" />
</on-entry>
</end-state>
<!-- adding sywmax parameter for registration flow -->
<end-state id="sendtickettomodal" view="/displayserviceticketandcookie">
<output value="requestScope.syw" name="sywmax"/>
</end-state>
<!--
<output-mapper>
<mapping source="${requestScope.syw" x } target="sywmax" />
</output-mapper>
-->
<global-transitions>
<transition to="showerror"
on-exception="org.springframework.webflow.execution.repository.NoSuchFlowExecutionException" />
<transition to="showerror"
on-exception="org.jasig.cas.services.UnauthorizedSsoServiceException" />
<transition to="showerror"
on-exception="org.jasig.cas.services.UnauthorizedServiceException" />
<transition to="showerror"
on-exception="org.springframework.webflow.execution.FlowExecutionException" />
</global-transitions>
<!-- <bean-import resource="regenroll-beans.xml" /> -->
</flow>
Test case
Second Test is failing
public class TestRegEnrollFlow extends AbstractXmlFlowExecutionTests {
SavingQueryParamInSessionAction saveQueryParamInSession;
SSOGatewayServiceImpl ssoGatewayService;
#Override
protected FlowDefinitionResource getResource(FlowDefinitionResourceFactory resourceFactory) {
return resourceFactory.createFileResource("src/main/webapp/WEB-INF/usr/flows/regEnroll-flow.xml");
}
#Override
protected void configureFlowBuilderContext(MockFlowBuilderContext builderContext) {
// I Have tried even mocking using Easy Mock
saveQueryParamInSession = EasyMock.createMock("saveQueryParamInSession", SavingQueryParamInSessionAction.class);
ssoGatewayService = EasyMock.createMock("ssoGatewayService", SSOGatewayServiceImpl.class);
builderContext.registerBean("saveQueryParamInSession", saveQueryParamInSession);
builderContext.registerBean("sywNumSetupAction", new SywNumSetupAction());
builderContext.registerBean("ssoGatewayService", ssoGatewayService);
builderContext.registerBean("regEnrollFormAction", new RegEnrollFormAction());
}
public void testAction() {
MockExternalContext ctx = new MockExternalContext();
MutableAttributeMap input = new LocalAttributeMap();
input.put("service", "");
input.put("regform", createRegistrationForm());
// this is the line where we are changing the state flow
input.put("success", null);
input.put("externalContext", ctx);
input.put("enrollresponse.responseCode", 200);
input.put("regform.craftsmanAffinity", "any");
startFlow(input, ctx);
assertFlowExecutionActive();
assertCurrentStateEquals("renderform");
assertResponseWrittenEquals("/regenroll", ctx);
}
public void testREgForm() throws Exception {
setCurrentState("renderform");
MockExternalContext context = new MockExternalContext();
context.putRequestParameter("sid", "3");
context.putRequestParameter("service", "qa.ecom.s.com:4380");
context.putRequestParameter("clienthost", "qa.ecom.s.com:4380");
context.putRequestParameter("target", "http://qa.ecom.sears.com:4380/?storeId=10153&catalogId=12605");
context.putRequestParameter("switchForm", "Donald");
context.putRequestParameter("oldlogin", "Donald");
context.putRequestParameter("emailId", "jadiya#gmail.com");
context.putRequestParameter("emailConfirm", "jadiya#gmail.com");
context.putRequestParameter("fname", "Ankur");
context.putRequestParameter("lname", "Jadiya");
context.putRequestParameter("zip", "56005");
context.putRequestParameter("modifyservice", "no");
context.putRequestParameter("ocpPage", "no");
context.putRequestParameter("fullpage", "no");
context.putRequestParameter("emailValidateFlag", "true");
context.putRequestParameter("mode", "active");
context.putRequestParameter("phone", "8884911391");
context.putRequestParameter("number", "883427");
context.putRequestParameter("irp", "true");
context.putRequestParameter("sywmax", "1234567");
context.putRequestParameter("enrollresponse.responseCode","200");
FlowExecution flowExecution = getFlowExecution();
FlowSession session = flowExecution.getActiveSession();
//flowExecution.getConversationScope().put("flowScope.enrollresponse.responseCode", 200);
session.getScope().put("flowScope.regform.loyaltyLookUp", true);
//session.getScope().put("flowScope.enrollresponse.responseCode", "200");
// session.getScope().put("flowScope.enrollresponse", 200);
//session.getScope().put("responseCode", 200);
session.getScope().put("flowScope.regform.craftsmanAffinity", "check");
/*session.getScope().put("enrollresponse.responseCode", 200);*/
// session..put("flowScope.enrollresponse.responseCode", 200);
updateFlowExecution(flowExecution);
ResponseVO value = new ResponseVO(200, "success");
session.getScope().put("enrollresponse", value);
session.getScope().put("flowScope.enrollresponse.responseCode", value);
context.setEventId("submit");
// EasyMock.expect(ssoGatewayService.register(createRegistrationForm(), context)).andReturn(value);
flowExecution.resume(context);
assertCurrentStateEquals("showerror");
}
private Regform createRegistrationForm() {
Regform regform = new Regform();
regform.setEmail("20130410111#gmail.com");
regform.setLname("mike");
regform.setFname("sun");
regform.setPassword("test11");
regform.setSid("3");
regform.setZip("60179");
regform.setLoyaltyLookUp(true);
return regform;
}
}
Error
Caused by: org.springframework.binding.expression.PropertyNotFoundException: Property not found
at org.springframework.binding.expression.spel.SpringELExpression.setValue(SpringELExpression.java:117)
at org.springframework.webflow.action.EvaluateAction.doExecute(EvaluateAction.java:80)
at org.springframework.webflow.action.AbstractAction.execute(AbstractAction.java:188)
at org.springframework.webflow.execution.AnnotatedAction.execute(AnnotatedAction.java:145)
at org.springframework.webflow.execution.ActionExecutor.execute(ActionExecutor.java:51)
... 36 more
Caused by: org.springframework.expression.spel.SpelEvaluationException: EL1010E:(pos 0): Property or field 'enrollresponse' cannot be set on object of type 'org.springframework.webflow.engine.impl.RequestControlContextImpl' - maybe not public?
at org.springframework.expression.spel.ast.PropertyOrFieldReference.writeProperty(PropertyOrFieldReference.java:270)
at org.springframework.expression.spel.ast.PropertyOrFieldReference.setValue(PropertyOrFieldReference.java:159)
at org.springframework.expression.spel.standard.SpelExpression.setValue(SpelExpression.java:411)
at org.springframework.binding.expression.spel.SpringELExpression.setValue(SpringELExpression.java:114)
... 40 more
you are setting this property:
input.put("enrollresponse.responseCode", "200");
but:
I don't see it anywhere in your flow (maybe in the part you omitted)
You have to first create the enrollresponse object before setting "responseCode" on it. I think that is causing the error you are having
[EDIT]
you also need to specify the scope for variable in <set> element (showrror state). replace:
<set name="errorCode" value="flowScope.enrollresponse.responseCode" />
by
<set name="viewScope.errorCode" value="flowScope.enrollresponse.responseCode" />
fix all those issues and try again

Spring Webflow: Securing An Individual Binding

So, I am implementing a <binder> in my various flow definitions in order to secure what gets bound to the model from each page in the flow. So, a <binder> section might look like this:
<binder>
<binding property="name" />
<binding property="departmentId" />
<binding property="phoneNumber" />
<binding property="qualificationOverride" />
</binder>
My problem is that I don't want the "qualificationOverride" to bind to the model unless the user has a specified role (ROLE_MANAGER).
Anyone have any ideas?
Jason
What you could do is not bind it, and on submit get the value from requestParameters, then go to a decision state where you can use secured to check permission and set the value.
something like this (I haven't tested it):
<view-state id="view" model="model">
<binder>
<binding property="name" />
<binding property="departmentId" />
<binding property="phoneNumber" />
<!--<binding property="qualificationOverride" />-->
</binder>
<transition on="submit" to="bindIfManager">
<set name="flowScope.qualificationOverride" value="requestParameters.qualificationOverride/>
</transition>
</view-state>
<action-state id="bindIfManager">
<!-- you will have to implement this, basically user.getAuthorities.contains(new SimpleGrantedAuthority(role))-->
<evaluate expression="securityAction.isUserInRole(currentUser, 'ROLE_MANAGER')"/>
<transition on="yes" to="finish">
<set name="model.qualificationOverride" value="flowScope.qualificationOverride"/>
</transition>
<transition on="no" to="finish"/>
</action-state>

Jasig CAS, how to redirect view after successful login

in my scenario, user need to change password before first times login.
how to make cas redirect url before login page?
in my app, i already define my own controller to handle certain URL, and also implement my own custom authentication under authenticationHandlers.
now only left this mechanism reset password before login.
can anyone give me a clue how to do it?
my maven project file:
https://qeyg6a.bay.livefilestore.com/y2msQyFts1aCgGkYR4ybMses2mGFVNJBLCX_xQ9pDi8gVdnhx9P5ibVVBlg6p6T9RM3BAN8Qcz2Izo5JGdQzbyU-kSMTIwBVOYhkdG1RvsyE50/cas-server-webapp.rar?download&psid=1
My login-webflow.xml
<?xml version="1.0" encoding="UTF-8"?>
<!--
Licensed to Jasig under one or more contributor license
agreements. See the NOTICE file distributed with this work
for additional information regarding copyright ownership.
Jasig licenses this file to you under the Apache License,
Version 2.0 (the "License"); you may not use this file
except in compliance with the License. You may obtain a
copy of the License at the following location:
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
-->
<flow xmlns="http://www.springframework.org/schema/webflow"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/webflow
http://www.springframework.org/schema/webflow/spring-webflow-2.0.xsd">
<var name="credentials" class="org.jasig.cas.authentication.principal.UsernamePasswordCredentials" />
<on-start>
<evaluate expression="initialFlowSetupAction" />
</on-start>
<decision-state id="ticketGrantingTicketExistsCheck">
<if test="flowScope.ticketGrantingTicketId != null" then="hasServiceCheck" else="gatewayRequestCheck" />
</decision-state>
<decision-state id="gatewayRequestCheck">
<if test="requestParameters.gateway != '' and requestParameters.gateway != null and flowScope.service != null" then="gatewayServicesManagementCheck" else="serviceAuthorizationCheck" />
</decision-state>
<decision-state id="hasServiceCheck">
<if test="flowScope.service != null" then="renewRequestCheck" else="viewGenericLoginSuccess" />
</decision-state>
<decision-state id="renewRequestCheck">
<if test="requestParameters.renew != '' and requestParameters.renew != null" then="serviceAuthorizationCheck" else="generateServiceTicket" />
</decision-state>
<!-- Do a service authorization check early without the need to login first -->
<action-state id="serviceAuthorizationCheck">
<evaluate expression="serviceAuthorizationCheck"/>
<transition to="generateLoginTicket"/>
</action-state>
<!--
The "warn" action makes the determination of whether to redirect directly to the requested
service or display the "confirmation" page to go back to the server.
-->
<decision-state id="warn">
<if test="flowScope.warnCookieValue" then="showWarningView" else="redirect" />
</decision-state>
<!--
<action-state id="startAuthenticate">
<action bean="x509Check" />
<transition on="success" to="sendTicketGrantingTicket" />
<transition on="warn" to="warn" />
<transition on="error" to="generateLoginTicket" />
</action-state>
-->
<!--
LPPE transitions begin here: You will also need to
move over the 'lppe-configuration.xml' file from the
'unused-spring-configuration' folder to the 'spring-configuration' folder
so CAS can pick up the definition for the bean 'passwordPolicyAction'.
-->
<action-state id="passwordPolicyCheck">
<evaluate expression="passwordPolicyAction" />
<transition on="showWarning" to="passwordServiceCheck" />
<transition on="success" to="sendTicketGrantingTicket" />
<transition on="error" to="viewLoginForm" />
</action-state>
<action-state id="passwordServiceCheck">
<evaluate expression="sendTicketGrantingTicketAction" />
<transition to="passwordPostCheck" />
</action-state>
<decision-state id="passwordPostCheck">
<if test="flowScope.service != null" then="warnPassRedirect" else="pwdWarningPostView" />
</decision-state>
<action-state id="warnPassRedirect">
<evaluate expression="generateServiceTicketAction" />
<transition on="success" to="pwdWarningPostView" />
<transition on="error" to="generateLoginTicket" />
<transition on="gateway" to="gatewayServicesManagementCheck" />
</action-state>
<end-state id="pwdWarningAbstractView">
<on-entry>
<set name="flowScope.passwordPolicyUrl" value="passwordPolicyAction.getPasswordPolicyUrl()" />
</on-entry>
</end-state>
<end-state id="pwdWarningPostView" view="casWarnPassView" parent="#pwdWarningAbstractView" />
<end-state id="casExpiredPassView" view="casExpiredPassView" parent="#pwdWarningAbstractView" />
<end-state id="casMustChangePassView" view="casMustChangePassView" parent="#pwdWarningAbstractView" />
<end-state id="casAccountDisabledView" view="casAccountDisabledView" />
<end-state id="casAccountLockedView" view="casAccountLockedView" />
<end-state id="casBadHoursView" view="casBadHoursView" />
<end-state id="casBadWorkstationView" view="casBadWorkstationView" />
<!-- LPPE transitions end here... -->
<action-state id="generateLoginTicket">
<evaluate expression="generateLoginTicketAction.generate(flowRequestContext)" />
<transition on="generated" to="viewLoginForm" />
</action-state>
<view-state id="viewLoginForm" view="casLoginView" model="credentials">
<binder>
<binding property="username" />
<binding property="password" />
</binder>
<on-entry>
<set name="viewScope.commandName" value="'credentials'" />
</on-entry>
<transition on="submit" bind="true" validate="true" to="realSubmit">
<evaluate expression="authenticationViaFormAction.doBind(flowRequestContext, flowScope.credentials)" />
</transition>
</view-state>
<action-state id="realSubmit">
<evaluate expression="authenticationViaFormAction.submit(flowRequestContext, flowScope.credentials, messageContext)" />
<!--
To enable LPPE on the 'warn' replace the below transition with:
<transition on="warn" to="passwordPolicyCheck" />
CAS will attempt to transition to the 'warn' when there's a 'renew' parameter
and there exists a ticketGrantingId and a service for the incoming request.
-->
<transition on="warn" to="warn" />
<!--
To enable LPPE on the 'success' replace the below transition with:
<transition on="success" to="passwordPolicyCheck" />
-->
<transition on="success" to="sendTicketGrantingTicket" />
<transition on="error" to="generateLoginTicket" />
<transition on="accountDisabled" to="casAccountDisabledView" />
<transition on="mustChangePassword" to="casMustChangePassView" />
<transition on="accountLocked" to="casAccountLockedView" />
<transition on="badHours" to="casBadHoursView" />
<transition on="badWorkstation" to="casBadWorkstationView" />
<transition on="passwordExpired" to="casExpiredPassView" />
</action-state>
<action-state id="sendTicketGrantingTicket">
<evaluate expression="sendTicketGrantingTicketAction" />
<transition to="serviceCheck" />
</action-state>
<decision-state id="serviceCheck">
<if test="flowScope.service != null" then="generateServiceTicket" else="viewGenericLoginSuccess" />
</decision-state>
<action-state id="generateServiceTicket">
<evaluate expression="generateServiceTicketAction" />
<transition on="success" to ="warn" />
<transition on="error" to="generateLoginTicket" />
<transition on="gateway" to="gatewayServicesManagementCheck" />
</action-state>
<action-state id="gatewayServicesManagementCheck">
<evaluate expression="gatewayServicesManagementCheck" />
<transition on="success" to="redirect" />
</action-state>
<action-state id="redirect">
<evaluate expression="flowScope.service.getResponse(requestScope.serviceTicketId)" result-type="org.jasig.cas.authentication.principal.Response" result="requestScope.response" />
<transition to="postRedirectDecision" />
</action-state>
<decision-state id="postRedirectDecision">
<if test="requestScope.response.responseType.name() == 'POST'" then="postView" else="redirectView" />
</decision-state>
<!--
the "viewGenericLogin" is the end state for when a user attempts to login without coming directly from a service.
They have only initialized their single-sign on session.
-->
<end-state id="viewGenericLoginSuccess" view="casLoginGenericSuccessView" />
<!--
The "showWarningView" end state is the end state for when the user has requested privacy settings (to be "warned") to be turned on. It delegates to a
view defines in default_views.properties that display the "Please click here to go to the service." message.
-->
<end-state id="showWarningView" view="casLoginConfirmView" />
<end-state id="postView" view="postResponseView">
<on-entry>
<set name="requestScope.parameters" value="requestScope.response.attributes" />
<set name="requestScope.originalUrl" value="flowScope.service.id" />
</on-entry>
</end-state>
<!--
The "redirect" end state allows CAS to properly end the workflow while still redirecting
the user back to the service required.
-->
<end-state id="redirectView" view="externalRedirect:${requestScope.response.url}" />
<end-state id="viewServiceErrorView" view="viewServiceErrorView" />
<end-state id="viewServiceSsoErrorView" view="viewServiceSsoErrorView" />
<global-transitions>
<!-- CAS-1023 This one is simple - redirects to a login page (same as renew) when 'ssoEnabled' flag is unchecked
instead of showing an intermediate unauthorized view with a link to login page -->
<transition to="viewLoginForm" on-exception="org.jasig.cas.services.UnauthorizedSsoServiceException"/>
<transition to="viewServiceErrorView" on-exception="org.springframework.webflow.execution.repository.NoSuchFlowExecutionException" />
<transition to="viewServiceErrorView" on-exception="org.jasig.cas.services.UnauthorizedServiceException" />
</global-transitions>
</flow>
My Solution
create
resetPasswordView.(class)=org.springframework.web.servlet.view.JstlView
resetPasswordView.url=/WEB-INF/view/jsp/default/ui/ResetPassword.jsp
in default_views.properties
create
public class testflowAction extends AbstractAction{
private String origin;
#Override
protected Event doExecute(RequestContext rc) throws Exception {
origin = rc.getRequestParameters().get("service");
if(true)
return result("setNew");
else
return result("setNew");
}
}
in login-wenflow.xml, replace
<transition on="success" to="sendTicketGrantingTicket" /> with
<transition on="success" to="customFlowCheck" />
also add
<action-state id="customFlowCheck">
<evaluate expression="customCheckAction" />
<transition on="ok" to="sendTicketGrantingTicket" />
<transition on="setNew" to="resetPasswordView" />
</action-state>
and
<end-state id="resetPasswordView" view="resetPasswordView" />
We had similar problem in our company. The user had to be redirected to another page after successful login.
We decided to add another outcome from action state id "realSubmit", that would indicate continuation of flow.
I would suggest that you first let user to preform login, so he confirms that he's the right user. To do so you need to change submit method in your AuthenticationViaFormAction class. Then you need to destroy TGT, and redirect user to your custom Flow Action that reset password.
It would look something like this:
public final String submit(final RequestContext context, final Credentials credentials, final MessageContext messageContext) throws Exception {
(...)
//Login user, so we know that provided password is correct.
WebUtils.putTicketGrantingTicketInRequestScope(context, this.centralAuthenticationService.createTicketGrantingTicket(credentials));
// do custom logic, that check if it is first login attept:
if( firstLoginAttempt(credentials) {
//destroy TGT, so user won't stay logged-in after interrupting next step
centralAuthenticationService.destroyTicketGrantingTicket(ticketGrantingTicketId);
//redirect user to another action that will handle changing password
return "changePassRequired"
}
I don't know how you check if the password IS initial password, so I leave it to you. Next add transition in login-webflow.xml outcome:
<action-state id="realSubmit">
<evaluate expression="authenticationViaFormAction.submit(flowRequestContext,flowScope.credentials, messageContext)" />
<transition on="warn" to="warn" />
<transition on="success" to="sendTicketGrantingTicket" />
<transition on="error" to="generateLoginTicket" />
<transition on="accountDisabled" to="casAccountDisabledView" />
<transition on="mustChangePassword" to="casMustChangePassView" />
<transition on="accountLocked" to="casAccountLockedView" />
<transition on="badHours" to="casBadHoursView" />
<transition on="badWorkstation" to="casBadWorkstationView" />
<transition on="passwordExpired" to="casExpiredPassView" />
<transition on="changePassRequired" to="changePasswordPrepare" />
</action-state>
And add custom action, you might as well use the same form as in login action so break it into two states, for example:
<view-state id="changePasswordPrepare" view="resetPasswordView">
<on-entry>
<evaluate expression="resetPasswordAction.setupForm(flowRequestContext)" />
</on-entry>
<transition on="submit" bind="true" validate="true" to="resetPasswordRealAction">
</transition>
</view-state>
<action-state id="resetPasswordRealAction">
<evaluate expression="resetPasswordAction.submit(flowRequestContext)" />
<transition on="success" to="sendTicketGrantingTicket" />
<transition on="again" to="changePasswordPrepare" />
<transition on="error" to="generateLoginTicket" />
</action-state>
resetPasswordAction.setupForm will prepare custom view with reset password form if it's needed
resetPasswordAction.submit will get variables from your form, and preform changing password.
snippet of class might look somewhat like this:
public class resetPasswordAction extends FormAction {
public final String submit(final RequestContext context) throws Exception {
final Credentials previousCredentials = context.getFlowScope().get("loginCredentials");
final String oldPass = context.getConversationScope().get("pass");
final String newPassword = context.getConversationScope().get("password");
final String newPasswordagain = context.getConversationScope().get("passwordagain");
if (!newPassword.equals(newPasswordagain) {
return "again";
}
if ( everythingIsOk(previousCredentials.getUsername(),oldPass,newPassword)) {
Credentials credentials = new UsernamePasswordCredentials();
credentials.setUsername(previousCredentials.getUsername());
credentials.setPassword(newPassword);
WebUtils.putTicketGrantingTicketInRequestScope(context, this.casService.createTicketGrantingTicket(credentials));
return "success";
}
return "error";
}
public Event setupForm(RequestContext context) throws Exception {
final Locale locale = LocaleContextHolder.getLocale();
context.getFlashScope().put("language",locale);
context.getFlashScope().put("service",context.getRequestScope().get("service");
}
}
You might as well be interested in CAM - CAS account management module, although it seems to be in early, theoretical phase.
You might as well be interested in cas 4, now in beta release as it seems to contain more elastic authentication logic. One, that you could use to do after login password reset.
I have running a CAS Server, seems that you should customize through Spring WebFlow. Follow my glue:
<action-state id="validateForgotPassword">
<on-entry>
<set name="flashScope.pmTask" value="'forceChangePassword'"/>
</on-entry>
<evaluate expression="forgotPasswordTokenValidateAction" />
<transition on="success" to="passwordManager"/>
<transition on="error" to="badForgotPasswordTokenView" />
</action-state>
You can add a JS script in succes login witch redirect a from your specific URL
document.location.href ="http://www...."
You can personnalized your processing JS.

Jetty is not receiving http request from outside on ec2

I've configured jetty hightide 8.1 server on ec2 instance. My jetty.xml file is as follows
<Configure id="Server" class="org.eclipse.jetty.server.Server">
<!-- =========================================================== -->
<!-- Server Thread Pool -->
<!-- =========================================================== -->
<Set name="ThreadPool">
<!-- Default queued blocking threadpool -->
<New class="org.eclipse.jetty.util.thread.QueuedThreadPool">
<Set name="minThreads">10</Set>
<Set name="maxThreads">200</Set>
<Set name="detailedDump">false</Set>
</New>
</Set>
<!-- =========================================================== -->
<!-- Set connectors -->
<!-- =========================================================== -->
<Call name="addConnector">
<Arg>
<New class="org.eclipse.jetty.server.nio.SelectChannelConnector">
<Set name="host"><Property name="jetty.host" default="0.0.0.0"/></Set>
<Set name="port"><Property name="jetty.port" default="80"/></Set>
<Set name="maxIdleTime">300000</Set>
<Set name="Acceptors">2</Set>
<Set name="statsOn">false</Set>
<Set name="confidentialPort">8443</Set>
<Set name="lowResourcesConnections">20000</Set>
<Set name="lowResourcesMaxIdleTime">5000</Set>
</New>
</Arg>
</Call>
<!-- =========================================================== -->
<!-- Set handler Collection Structure -->
<!-- =========================================================== -->
<Set name="handler">
<New id="Handlers" class="org.eclipse.jetty.server.handler.HandlerCollection">
<Set name="handlers">
<Array type="org.eclipse.jetty.server.Handler">
<Item>
<New id="Contexts" class="org.eclipse.jetty.server.handler.ContextHandlerCollection"/>
</Item>
<Item>
<New id="DefaultHandler" class="org.eclipse.jetty.server.handler.DefaultHandler"/>
</Item>
<Item>
<New id="RequestLog" class="org.eclipse.jetty.server.handler.RequestLogHandler"/>
</Item>
</Array>
</Set>
</New>
</Set>
<Call name="addBean">
<Arg>
<New id="DeploymentManager" class="org.eclipse.jetty.deploy.DeploymentManager">
<Set name="contexts">
<Ref id="Contexts" />
</Set>
<Call name="setContextAttribute">
<Arg>org.eclipse.jetty.server.webapp.ContainerIncludeJarPattern</Arg>
<Arg>.*/servlet-api-[^/]*\.jar$</Arg>
</Call>
<!-- Add a customize step to the deployment lifecycle -->
<!-- uncomment and replace DebugBinding with your extended AppLifeCycle.Binding class
<Call name="insertLifeCycleNode">
<Arg>deployed</Arg>
<Arg>starting</Arg>
<Arg>customise</Arg>
</Call>
<Call name="addLifeCycleBinding">
<Arg>
<New class="org.eclipse.jetty.deploy.bindings.DebugBinding">
<Arg>customise</Arg>
</New>
</Arg>
</Call>
-->
</New>
</Arg>
</Call>
<Ref id="DeploymentManager">
<Call name="addAppProvider">
<Arg>
<New class="org.eclipse.jetty.deploy.providers.ContextProvider">
<Set name="monitoredDirName"><Property name="jetty.home" default="." />/contexts</Set>
<Set name="scanInterval">1</Set>
</New>
</Arg>
</Call>
</Ref>
<Ref id="RequestLog">
<Set name="requestLog">
<New id="RequestLogImpl" class="org.eclipse.jetty.server.NCSARequestLog">
<Arg><SystemProperty name="jetty.logs" default="./logs"/>/yyyy_mm_dd.tutorial.log</Arg>
<Set name="retainDays">90</Set>
<Set name="append">true</Set>
<Set name="extended">false</Set>
<Set name="LogTimeZone">GMT</Set>
</New>
</Set>
</Ref>
<!-- =========================================================== -->
<!-- extra options -->
<!-- =========================================================== -->
<Set name="stopAtShutdown">true</Set>
<Set name="sendServerVersion">true</Set>
<Set name="sendDateHeader">true</Set>
<Set name="gracefulShutdown">1000</Set>
<Set name="dumpAfterStart">false</Set>
<Set name="dumpBeforeStop">false</Set>
</Configure>
And in /contexts folder I've made a file mydomain.xml as follows
<Configure class="org.eclipse.jetty.webapp.WebAppContext">
<!-- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -->
<!-- Required minimal context configuration : -->
<!-- + contextPath -->
<!-- + war OR resourceBase -->
<!-- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -->
<Set name="contextPath">/</Set>
<Set name="resourceBase"><SystemProperty name="jetty.home" default="."/>/webapps/sampleapp/</Set>
<!-- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -->
<!-- Optional context configuration -->
<!-- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -->
<Set name="extractWAR">true</Set>
<Set name="copyWebDir">false</Set>
<!-- virtual hosts -->
<Set name="virtualHosts">
<Array type="String">
<Item>www.mydomain.com</Item>
<Item>localhost</Item>
<Item>127.0.0.1</Item>
</Array>
</Set>
<!-- Virtual Hosts-->
<!-- disable cookies
<Get name="sessionHandler">
<Get name="sessionManager">
<Set name="usingCookies" type="boolean">false</Set>
</Get>
</Get>
-->
<!-- Non standard error page mapping -->
<!--
<Get name="errorHandler">
<Call name="addErrorPage">
<Arg type="int">500</Arg>
<Arg type="int">599</Arg>
<Arg type="String">/dump/errorCodeRangeMapping</Arg>
</Call>
</Get>
-->
<!-- Add context specific logger
<Set name="handler">
<New id="RequestLog" class="org.eclipse.jetty.server.handler.RequestLogHandler">
<Set name="requestLog">
<New id="RequestLogImpl" class="org.eclipse.jetty.server.NCSARequestLog">
<Set name="filename"><Property name="jetty.logs" default="./logs"/>/test-yyyy_mm_dd.request.log</Set>
<Set name="filenameDateFormat">yyyy_MM_dd</Set>
<Set name="append">true</Set>
<Set name="LogTimeZone">GMT</Set>
</New>
</Set>
</New>
</Set>
-->
</Configure>
When I'm doing wget from the ec2 instance I'm getting proper index.html page. But if I do it from outside or hit www.mydomain.com from the browser I'm getting request timed out. I've set jetty to listen to http port 80 but no request from outside is coming to jetty. I've created the CNAME record in my domain registrar with the public dns provided in the aws console. IP and dns is resolved correctly but jetty doesn't receive any request. I'm not able to understand the problem in my configuration
Sorry, All the configurations are correct. Actually tcp port 80 was not open from aws console. I just wasted 2 hours to realize that.

Resources