Infinite Loop when parse XML File to Flat Flie. Bug SpringBatch or Not - xml-parsing

I tried to parse an xml file to flatefile. All worked fine except at the end. In debug Mode the cause of the infinite loop is due to the method moveCursorToNextFragment( reader) in org.springframework.batch.item.xml.StaxEventItemRe ader.class.
More precisily in this part of method
while (reader.peek() != null && !reader.peek().isStartElement()) {
reader.nextEvent();
}
it seems that these conditions are not sufficient to recognize the end of the document.
I replace this part of code by this code to be sure the end of the document test
while (reader.peek() != null && !reader.peek().isStartElement() && !reader.peek().isEndDocument()) {
reader.nextEvent();
}
if (reader.peek() == null || reader.peek().isEndDocument()) {
return false;
}
below my context file and the link for an INSEE xmlfile : http://lei-france.insee.fr/Telechargement.do
I always taked the full file.
Here is my context file
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:batch="http://www.springframework.org/schema/batch"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:jee="http://www.springframework.org/schema/jee"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/batch
http://www.springframework.org/schema/batch/spring-batch-2.2.xsd
http://www.springframework.org/schema/jee
http://www.springframework.org/schema/jee/spring-jee-2.5.xsd">
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"
p:dataSource-ref="dataSource"/>
<bean id="jobLauncher" class="org.springframework.batch.core.launch.support.SimpleJobLauncher"
p:jobRepository-ref="jobRepository"
p:taskExecutor-ref="taskExecutor" />
<bean id="jobRepository" class="org.springframework.batch.core.repository.support.JobRepositoryFactoryBean"
p:dataSource-ref="dataSource"
p:transactionManager-ref="transactionManager" />
<bean id="taskExecutor" class="org.springframework.core.task.SimpleAsyncTaskExecutor"/>
<!-- DATASOURCE -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource" >
<property name="driverClassName"
value="oracle.jdbc.driver.OracleDriver" />
<property name="url"
value="jdbc:oracle:thin:#gulli:1521:OPE" />
<property name="username" value="xxxxxx" />
<property name="password" value="xxx" />
</bean>
<!-- ITEM READER -->
<bean id="itemReader" scope="step" class="org.springframework.batch.item.xml.StaxEventItemReader"
p:resource="insee/lei.xml"
p:fragmentRootElementName="LEIRecord"
p:unmarshaller-ref="inseeMarshaller" />
<bean id="inseeMarshaller" class="org.springframework.oxm.xstream.XStreamMarshaller"
p:autodetectAnnotations="true" p:encoding="UTF-8">
<property name="aliases">
<props>
<prop key="LEIDirectory">fr.cdn.dtc.etudes.emir.insee.LEIDirectory</prop>
<prop key="LEIRecord">fr.cdn.dtc.etudes.emir.insee.LEIRecord</prop>
<prop key="LegalEntity">fr.cdn.dtc.etudes.emir.insee.LegalEntity</prop>
<prop key="OtherIdentifiers">fr.cdn.dtc.etudes.emir.insee.OtherIdentifiers</prop>
<prop key="OtherNames">fr.cdn.dtc.etudes.emir.insee.OtherNames</prop>
<prop key="RelatedLEI">fr.cdn.dtc.etudes.emir.insee.RelatedLEI</prop>
<prop key="Event">fr.cdn.dtc.etudes.emir.insee.Event</prop>
<prop key="OtherAddresses">fr.cdn.dtc.etudes.emir.insee.OtherAddresses</prop>
</props>
</property>
</bean>
<!-- ITEM WRITER DELIMETED LENGTH-->
<bean id="itemWriterFile" class="org.springframework.batch.item.file.FlatFileItemWriter"
p:resource-ref="outputDelimitedResource"
p:lineAggregator-ref="lineAggregator"
p:shouldDeleteIfExists="true"
/>
<bean id="outputDelimitedResource" class="org.springframework.core.io.FileSystemResource">
<constructor-arg value="target/outputs/inseeOutput.txt" />
</bean>
<bean id="lineAggregator" class="org.springframework.batch.item.file.transform.DelimitedLineAggregator"
p:delimiter=";"
p:fieldExtractor-ref="fieldExtractor" />
<bean id="fieldExtractor" class="org.springframework.batch.item.file.transform.BeanWrapperFieldExtractor"
p:names="le" />
<batch:job id="inseeJob" job-repository="jobRepository" >
<batch:step id="inseeStep">
<batch:tasklet>
<batch:chunk reader="itemReader" writer="itemWriterFile" commit-interval="10" />
<batch:transaction-attributes isolation="DEFAULT" propagation="REQUIRED" timeout="30"/>
</batch:tasklet>
</batch:step>
</batch:job>
</beans>
Best Regards
Clément

Related

The function import is missing in the metadata of odata (odata created via CDS)

I want to create a function import in odata for use in sapui5 application. I create CDS view, add BOPF, create action SEND_MAIL, add annotation to odata. But function import tag is still missing in the metadata, i dont know why. And Exporting type in action inactive. Determination working, action not. What i do wrong?
СDS View:
#AbapCatalog.sqlViewName: 'ZGUT_FIORY_VW'
#AbapCatalog.compiler.compareFilter: true
#VDM.viewType: #COMPOSITE
#AbapCatalog.preserveKey: true
#AccessControl.authorizationCheck: #CHECK
#EndUserText.label: 'Test cds fiori list report'
// BOPF CRUD
#Metadata.allowExtensions: true
#ObjectModel:{
modelCategory: #BUSINESS_OBJECT,
compositionRoot: true,
transactionalProcessingEnabled: true,
createEnabled: true,
updateEnabled: true,
deleteEnabled: true,
writeActivePersistence: 'ZGUT_TEST_UI5',
semanticKey: ['id'],
representativeKey: 'id'
}
#OData:{
publish:true
}
#UI.headerInfo: {
typeName : 'Тестовое приложение fiori', // Заголовок списка
typeNamePlural: 'Тестовое приложение fiori' ,
title.value: 'Title', // Заголовок детальной страницы
description.value: 'bukrs_txt'
}
#Search.searchable: true
define view ZGUT_CDS_FIORY as select from zgut_test_ui5
association [1..1] to t001 as _bukrs on zgut_test_ui5.bukrs = _bukrs.bukrs
association [0..*] to ZGUT_CHART_AMOUNT as _chartamount on zgut_test_ui5.curr = _chartamount.Curr
association [1..1] to ZGUT_CHART_AMOUNT as _chartamount2 on zgut_test_ui5.id = _chartamount2.Ids
{
#UI.lineItem:[
{position: 30},
{ type: #FOR_ACTION, dataAction: 'BOPF:SEND_MAIL', position: 1, label: 'Send mail' }
]
#ObjectModel.mandatory: true
key id as Id,
// Another fields
}
BOPF:
Action:
Action class:
Metadata (i dont see here any function import, i dont know why) /sap/opu/odata/sap/ZGUT_CDS_FIORY_CDS/$metadata:
<edmx:Edmx xmlns:edmx="http://schemas.microsoft.com/ado/2007/06/edmx" xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata" xmlns:sap="http://www.sap.com/Protocols/SAPData" Version="1.0">
<edmx:Reference xmlns:edmx="http://docs.oasis-open.org/odata/ns/edmx" Uri="http://host:50000/sap/opu/odata/IWFND/CATALOGSERVICE;v=2/Vocabularies(TechnicalName='%2FIWBEP%2FVOC_COMMON',Version='0001',SAP__Origin='LOCAL')/$value">
<edmx:Include Namespace="com.sap.vocabularies.Common.v1" Alias="Common"/>
</edmx:Reference>
<edmx:DataServices m:DataServiceVersion="2.0">
<Schema xmlns="http://schemas.microsoft.com/ado/2008/09/edm" Namespace="ZGUT_CDS_FIORY_CDS" xml:lang="ru" sap:schema-version="1">
<EntityType Name="ZGUT_CDS_FIORYType" sap:label="Test cds fiori list report" sap:content-version="1">
<Key>
<PropertyRef Name="Id"/>
</Key>
<Property Name="Send_mail_ac" Type="Edm.Boolean" sap:label="Dyn. Action Control" sap:creatable="false" sap:updatable="false" sap:sortable="false" sap:filterable="false"/>
<Property Name="Id" Type="Edm.String" Nullable="false" MaxLength="6" sap:display-format="NonNegative" sap:label="Номер"/>
<Property Name="Descr" Type="Edm.String" sap:label="Описание"/>
<Property Name="target_amount" Type="Edm.String" MaxLength="6" sap:display-format="NonNegative" sap:label="Количество"/>
<Property Name="Title" Type="Edm.String" MaxLength="255" sap:label="Заголовок"/>
<Property Name="Bukrs" Type="Edm.String" MaxLength="4" sap:display-format="UpperCase" sap:label="БЕ"/>
<Property Name="bukrs_txt" Type="Edm.String" MaxLength="25" sap:label="Название фирмы" sap:creatable="false" sap:updatable="false"/>
<Property Name="Ab" Type="Edm.DateTime" Precision="0" sap:display-format="Date" sap:label="Дата начала"/>
<Property Name="Bis" Type="Edm.DateTime" Precision="0" sap:display-format="Date" sap:label="Дата конца"/>
<Property Name="Price" Type="Edm.Decimal" Precision="11" Scale="3" sap:label="Цена"/>
<Property Name="Curr" Type="Edm.String" MaxLength="3" sap:display-format="UpperCase" sap:label="Валюта"/>
<Property Name="Amount" Type="Edm.String" MaxLength="6" sap:display-format="NonNegative" sap:label="Количество"/>
<NavigationProperty Name="to_chartamount" Relationship="ZGUT_CDS_FIORY_CDS.assoc_17D58845CCECEF801599D15F5569B65F" FromRole="FromRole_assoc_17D58845CCECEF801599D15F5569B65F" ToRole="ToRole_assoc_17D58845CCECEF801599D15F5569B65F"/>
<NavigationProperty Name="to_chartamount2" Relationship="ZGUT_CDS_FIORY_CDS.assoc_84AF2B5FF9693A0A2F011CFC2072B09A" FromRole="FromRole_assoc_84AF2B5FF9693A0A2F011CFC2072B09A" ToRole="ToRole_assoc_84AF2B5FF9693A0A2F011CFC2072B09A"/>
</EntityType>
<EntityType Name="ZGUT_CHART_AMOUNTType" sap:semantics="aggregate" sap:label="ZGUT_CHART_AMOUNT" sap:content-version="1">
<Key>
<PropertyRef Name="ID"/>
</Key>
<Property Name="ID" Type="Edm.String" Nullable="false"/>
<Property Name="Ids" Type="Edm.String" MaxLength="6" sap:aggregation-role="dimension" sap:display-format="NonNegative" sap:label="Номер"/>
<Property Name="Amounts" Type="Edm.String" MaxLength="6" sap:aggregation-role="measure" sap:display-format="NonNegative" sap:label="Количество" sap:filterable="false"/>
<Property Name="target_amount" Type="Edm.String" MaxLength="6" sap:aggregation-role="dimension" sap:display-format="NonNegative" sap:label="Количество"/>
<Property Name="Price" Type="Edm.Decimal" Precision="11" Scale="3" sap:aggregation-role="dimension" sap:label="Цена"/>
<Property Name="Curr" Type="Edm.String" MaxLength="3" sap:aggregation-role="dimension" sap:display-format="UpperCase" sap:label="Валюта"/>
</EntityType>
<Association Name="assoc_84AF2B5FF9693A0A2F011CFC2072B09A" sap:content-version="1">
<End Type="ZGUT_CDS_FIORY_CDS.ZGUT_CDS_FIORYType" Multiplicity="1" Role="FromRole_assoc_84AF2B5FF9693A0A2F011CFC2072B09A"/>
<End Type="ZGUT_CDS_FIORY_CDS.ZGUT_CHART_AMOUNTType" Multiplicity="1" Role="ToRole_assoc_84AF2B5FF9693A0A2F011CFC2072B09A"/>
</Association>
<Association Name="assoc_17D58845CCECEF801599D15F5569B65F" sap:content-version="1">
<End Type="ZGUT_CDS_FIORY_CDS.ZGUT_CDS_FIORYType" Multiplicity="1" Role="FromRole_assoc_17D58845CCECEF801599D15F5569B65F"/>
<End Type="ZGUT_CDS_FIORY_CDS.ZGUT_CHART_AMOUNTType" Multiplicity="*" Role="ToRole_assoc_17D58845CCECEF801599D15F5569B65F"/>
</Association>
<EntityContainer Name="ZGUT_CDS_FIORY_CDS_Entities" m:IsDefaultEntityContainer="true" sap:supported-formats="atom json xlsx">
<EntitySet Name="ZGUT_CDS_FIORY" EntityType="ZGUT_CDS_FIORY_CDS.ZGUT_CDS_FIORYType" sap:searchable="true" sap:content-version="1"/>
<EntitySet Name="ZGUT_CHART_AMOUNT" EntityType="ZGUT_CDS_FIORY_CDS.ZGUT_CHART_AMOUNTType" sap:creatable="false" sap:updatable="false" sap:deletable="false" sap:content-version="1"/>
<AssociationSet Name="assoc_17D58845CCECEF801599D15F5569B65F" Association="ZGUT_CDS_FIORY_CDS.assoc_17D58845CCECEF801599D15F5569B65F" sap:creatable="false" sap:updatable="false" sap:deletable="false" sap:content-version="1">
<End EntitySet="ZGUT_CDS_FIORY" Role="FromRole_assoc_17D58845CCECEF801599D15F5569B65F"/>
<End EntitySet="ZGUT_CHART_AMOUNT" Role="ToRole_assoc_17D58845CCECEF801599D15F5569B65F"/>
</AssociationSet>
<AssociationSet Name="assoc_84AF2B5FF9693A0A2F011CFC2072B09A" Association="ZGUT_CDS_FIORY_CDS.assoc_84AF2B5FF9693A0A2F011CFC2072B09A" sap:creatable="false" sap:updatable="false" sap:deletable="false" sap:content-version="1">
<End EntitySet="ZGUT_CDS_FIORY" Role="FromRole_assoc_84AF2B5FF9693A0A2F011CFC2072B09A"/>
<End EntitySet="ZGUT_CHART_AMOUNT" Role="ToRole_assoc_84AF2B5FF9693A0A2F011CFC2072B09A"/>
</AssociationSet>
</EntityContainer>
<atom:link xmlns:atom="http://www.w3.org/2005/Atom" rel="self" href="http://host:50000/sap/opu/odata/sap/ZGUT_CDS_FIORY_CDS/$metadata"/>
<atom:link xmlns:atom="http://www.w3.org/2005/Atom" rel="latest-version" href="http://host:50000/sap/opu/odata/sap/ZGUT_CDS_FIORY_CDS/$metadata"/>
</Schema>
</edmx:DataServices>
</edmx:Edmx>
I solved the issue by choosing the exporting type in the actions list and reactivate the bopf

RESTier OData Function that support $expand and $filter

With the help of the RESTier team, I manage to create an RESTier function that return a list of my entity.
Here's the code
protected EdmModel OnModelExtending(EdmModel model)
{
var ns = model.DeclaredNamespaces.First(); // PointLoc.Data
var entityContainer = (EdmEntityContainer) model.EntityContainer;
var locationEntityType = (IEdmEntityType) model.FindDeclaredType(ns + "." + "Location");
var locationEntitySet = entityContainer.FindEntitySet("Locations");
var locationEntityTypeReference = new EdmEntityTypeReference(locationEntityType, false);
var locationEntityCollection = EdmCoreModel.GetCollection(locationEntityTypeReference);
var ambilLocationsByMarketId = new EdmFunction(ns, "AmbilLocationsByMarketId", locationEntityCollection, false, null, true);
model.AddElement(ambilLocationsByMarketId);
entityContainer.AddFunctionImport("AmbilLocationsByMarketId", ambilLocationsByMarketId,
new EdmEntitySetReferenceExpression(locationEntitySet));
return model;
}
And here's my implementation on the Controller
[HttpGet]
[EnableQuery]
[ODataRoute("AmbilLocationsByMarketId")]
public IQueryable<Location> AmbilLocationsByMarketId()
{
var locations = DbContext.Locations.Where(l => l.Name.Contains("Hotel")).Select(l => l);
return locations;
}
It works fine returning the list of data with i send a HTTP GET to
http://localhost:21922/odata/AmbilLocationsByMarketId
but when I try to add $expand or $filter, It's not working.
http://localhost:21922/odata/AmbilLocationsByMarketId?$expand=Category
I'm Error that reads like
{
"error": {
"code": "",
"message": "An error has occurred.",
"innererror": {
"message": "The 'ObjectContent`1' type failed to serialize the response body for content type 'application/json; odata.metadata=minimal'.",
"type": "System.InvalidOperationException",
"stacktrace": "",
"internalexception": {
"message": "'DbQuery`1' cannot be serialized using the ODataMediaTypeFormatter.",
"type": "System.Runtime.Serialization.SerializationException",
"stacktrace": " at System.Web.OData.Formatter.ODataMediaTypeFormatter.GetSerializer(Type type, Object value, IEdmModel model, ODataSerializerProvider serializerProvider)\\\r\\\n at System.Web.OData.Formatter.ODataMediaTypeFormatter.WriteToStream(Type type, Object value, Stream writeStream, HttpContent content, HttpContentHeaders contentHeaders)\\\r\\\n at System.Web.OData.Formatter.ODataMediaTypeFormatter.WriteToStreamAsync(Type type, Object value, Stream writeStream, HttpContent content, TransportContext transportContext, CancellationToken cancellationToken)\\\r\\\n--- End of stack trace from previous location where exception was thrown ---\\\r\\\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\\\r\\\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\\\r\\\n at System.Runtime.CompilerServices.TaskAwaiter.GetResult()\\\r\\\n at System.Web.Http.WebHost.HttpControllerHandler.<WriteBufferedResponseContentAsync>d__1b.MoveNext()"
}
}
}
}
Here's my metadata
<EntityType Name="Location">
<Key>
<PropertyRef Name="Id" />
</Key>
<Property Name="Id" Type="Edm.Int32" Nullable="false">
<Annotation Term="Org.OData.Core.V1.Computed" Bool="true" />
</Property>
<Property Name="Name" Type="Edm.String" Nullable="false" MaxLength="500" />
<Property Name="Address" Type="Edm.String" Nullable="false" MaxLength="2000" />
<Property Name="City" Type="Edm.String" MaxLength="500" />
<Property Name="Postcode" Type="Edm.String" MaxLength="100" />
<Property Name="Phone" Type="Edm.String" MaxLength="50" />
<Property Name="Email" Type="Edm.String" MaxLength="200" />
<Property Name="Latitude" Type="Edm.Decimal" Nullable="false" Precision="9" Scale="6" />
<Property Name="Longitude" Type="Edm.Decimal" Nullable="false" Precision="9" Scale="6" />
<Property Name="Street" Type="Edm.String" MaxLength="1000" />
<Property Name="UpVotes" Type="Edm.Int32" Nullable="false" />
<Property Name="DownVotes" Type="Edm.Int32" Nullable="false" />
<Property Name="CategoryId" Type="Edm.Int32" Nullable="false" />
<Property Name="StatusId" Type="Edm.Int32" Nullable="false" />
<Property Name="StateId" Type="Edm.Int32" Nullable="false" />
<Property Name="TitleSlug" Type="Edm.String" MaxLength="200" />
<NavigationProperty Name="Category" Type="PointLoc.Data.Category" Nullable="false" Partner="Locations">
<ReferentialConstraint Property="CategoryId" ReferencedProperty="Id" />
</NavigationProperty>
</EntityType>
and here's the EntityContainer
<EntityContainer Name="DatabaseContext">
<EntitySet Name="Categories" EntityType="PointLoc.Data.Category">
<NavigationPropertyBinding Path="Locations" Target="Locations" />
</EntitySet>
<EntitySet Name="Locations" EntityType="PointLoc.Data.Location">
<NavigationPropertyBinding Path="Accesses" Target="Accesses" />
<NavigationPropertyBinding Path="Category" Target="Categories" />
<NavigationPropertyBinding Path="Contents" Target="Contents" />
<NavigationPropertyBinding Path="State" Target="States" />
<NavigationPropertyBinding Path="Status" Target="Status" />
<NavigationPropertyBinding Path="LocationMarketMaps" Target="LocationMarketMaps" />
<NavigationPropertyBinding Path="LocationTagMaps" Target="LocationTagMaps" />
</EntitySet>
<FunctionImport Name="AmbilLocationsByMarketId" Function="PointLoc.Data.AmbilLocationsByMarketId" EntitySet="Locations" />
</EntityContainer>

Custom UserDetailsService in spring-security

I cant proceed further into my project because of an strange error. I am trying to implement spring-security and spring data JPA for my application, which exposes only REST api.
Now, when I am trying to implement my custom UserDetailsService class, as mentioned below, the parameter username in method loadUserByUsername is not the username I am passing as a POST request parameter, rather its the client_id parameter.
Can someone please suggest as what am I doing wrong?
public class CustomUserDetailsService implements UserDetailsService {
private ClientDetailsService clientDetailsService;
private String emptyPassword = "";
public CustomUserDetailsService() {
}
public CustomUserDetailsService(ClientDetailsService clientDetailsService) {
this.clientDetailsService = clientDetailsService;
}
private List<GrantedAuthority> getAuthorities(String role) {
List<GrantedAuthority> authList = new ArrayList<GrantedAuthority>();
authList.add(new SimpleGrantedAuthority("ROLE_USER"));
// you can also add different roles here
// for example, the user is also an admin of the site, then you can add
// ROLE_ADMIN
// so that he can view pages that are ROLE_ADMIN specific
if (role != null && role.trim().length() > 0) {
if (role.equals("admin")) {
authList.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
}
}
return authList;
}
#Override
public UserDetails loadUserByUsername(String username)
throws UsernameNotFoundException {
ClientDetails clientDetails = clientDetailsService
.loadClientByClientId(username);
String clientSecret = clientDetails.getClientSecret();
if (clientSecret == null || clientSecret.trim().length() == 0) {
clientSecret = emptyPassword;
}
return new User(username, clientSecret, clientDetails.getAuthorities());
}
}
My spring-security configuration is as following:
<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:oauth="http://www.springframework.org/schema/security/oauth2"
xmlns:sec="http://www.springframework.org/schema/security" xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/security/oauth2 http://www.springframework.org/schema/security/spring-security-oauth2-2.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.2.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd ">
<http pattern="/oauth/token" create-session="stateless"
authentication-manager-ref="authenticationManager"
xmlns="http://www.springframework.org/schema/security">
<intercept-url pattern="/oauth/token" access="IS_AUTHENTICATED_FULLY" />
<anonymous enabled="false" />
<http-basic entry-point-ref="clientAuthenticationEntryPoint" />
<custom-filter ref="clientCredentialsTokenEndpointFilter"
before="BASIC_AUTH_FILTER" />
<access-denied-handler ref="oauthAccessDeniedHandler" />
</http>
<http pattern="/api/**" create-session="never"
entry-point-ref="oauthAuthenticationEntryPoint" xmlns="http://www.springframework.org/schema/security">
<anonymous enabled="false" />
<intercept-url pattern="/api/**" access="IS_AUTHENTICATED_FULLY" />
<custom-filter ref="resourceServerFilter" before="PRE_AUTH_FILTER" />
<access-denied-handler ref="oauthAccessDeniedHandler" />
</http>
<http pattern="/logout" create-session="never"
entry-point-ref="oauthAuthenticationEntryPoint" xmlns="http://www.springframework.org/schema/security">
<anonymous enabled="false" />
<intercept-url pattern="/logout" method="GET" />
<sec:logout invalidate-session="true" logout-url="/logout"
success-handler-ref="logoutSuccessHandler" />
<custom-filter ref="resourceServerFilter" before="PRE_AUTH_FILTER" />
<access-denied-handler ref="oauthAccessDeniedHandler" />
</http>
<bean id="logoutSuccessHandler" class="com.monsor.feasthub.security.LogoutImpl">
<property name="tokenstore" ref="tokenStore" />
</bean>
<bean id="oauthAuthenticationEntryPoint"
class="org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint" />
<bean id="applicationContextProvder" class="com.monsor.feasthub.util.ApplicationContextProvider" />
<bean id="clientAuthenticationEntryPoint"
class="org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint">
<property name="realmName" value="springsec/client" />
<property name="typeName" value="Basic" />
</bean>
<bean id="oauthAccessDeniedHandler"
class="org.springframework.security.oauth2.provider.error.OAuth2AccessDeniedHandler" />
<bean id="clientCredentialsTokenEndpointFilter"
class="org.springframework.security.oauth2.provider.client.ClientCredentialsTokenEndpointFilter">
<property name="authenticationManager" ref="authenticationManager" />
</bean>
<authentication-manager alias="authenticationManager"
xmlns="http://www.springframework.org/schema/security">
<authentication-provider user-service-ref="clientDetailsUserService" />
</authentication-manager>
<bean id="clientDetailsUserService" class="com.monsor.feasthub.security.CustomUserDetailsService">
<constructor-arg ref="clientDetails" />
</bean>
<bean id="clientDetails" class="com.monsor.feasthub.security.ClientDetailsServiceImpl" />
<oauth:authorization-server
client-details-service-ref="clientDetails" token-services-ref="tokenServices">
<oauth:authorization-code />
<oauth:implicit />
<oauth:refresh-token />
<oauth:client-credentials />
<oauth:password authentication-manager-ref="userAuthenticationManager" />
</oauth:authorization-server>
<authentication-manager id="userAuthenticationManager"
xmlns="http://www.springframework.org/schema/security">
<authentication-provider ref="customUserAuthenticationProvider" />
</authentication-manager>
<bean id="customUserAuthenticationProvider"
class="com.monsor.feasthub.security.CustomUserAuthenticationProvider" />
<oauth:resource-server id="resourceServerFilter"
resource-id="springsec" token-services-ref="tokenServices" />
<bean id="tokenStore"
class="org.springframework.security.oauth2.provider.token.store.InMemoryTokenStore" />
<bean id="tokenServices"
class="org.springframework.security.oauth2.provider.token.DefaultTokenServices">
<property name="tokenStore" ref="tokenStore" />
<property name="supportRefreshToken" value="true" />
<property name="accessTokenValiditySeconds" value="300000" />
<property name="clientDetailsService" ref="clientDetails" />
</bean>
<mvc:annotation-driven /> <!-- Declares explicit support for annotation-driven MVC controllers #RequestMapping,
#Controller -->
<mvc:default-servlet-handler />
<bean id="MyResource" class="com.monsor.feasthub.resources.MyResource" />
</beans>

Login form issue with spring security 2.0.7 and spring 2.5

Hi i am trying to put a login page on my application.
My login.jsp is
<form name='f' action="<c:url value='j_spring_security_check' />"
method='POST'>
<table>
<tr>
<td>User:</td>
<td><input type='text' name='j_username' value=''>
</td>
</tr>
<tr>
<td>Password:</td>
<td><input type='password' name='j_password' />
</td>
</tr>
<tr>
<td colspan='2'><input name="submit" type="submit"
value="submit" />
</td>
</tr>
<tr>
<td colspan='2'><input name="reset" type="reset" />
</td>
</tr>
</table>
</form>
</body>
</html>
Login controller
#Controller
public class LoginController {
#RequestMapping("/user/login.do")
public ModelAndView handleLoginForm(HttpServletRequest request) {
String errParam = request.getParameter("error");
ModelAndView mv = new ModelAndView("login");
if(errParam != null) {
mv.addObject("error", "Benutzer oder Kennwort unzulässig");
}
return mv;
}
}
spring secuirty xml
<http auto-config="true">
<intercept-url pattern="/login"
access="ROLE_USER" />
<intercept-url pattern="/j_spring_security_check"
access="ROLE_USER" />
<form-login login-page="/login"
login-processing-url="/j_spring_security_check" default-target-url="/userPage.do"
authentication-failure-url="/login?error=1" />
<logout logout-success-url="/login"
logout-url="/logout" />
<!-- <intercept-url pattern="/user/userPage.do" access="ROLE_USER" />
<form-login login-page="/user/login.do" default-target-url="/user/userPage.do"
authentication-failure-url="/loginfailed" />
<logout logout-success-url="/logout" /> -->
</http>
<authentication-provider>
<user-service id="userDetailsService">
<user name="admin" password="admin" authorities="ROLE_USER, ROLE_ADMIN" />
<user name="username" password="password" authorities="ROLE_USER" />
<user name="test" password="test" authorities="ROLE_USER" />
</user-service>
</authentication-provider>
</beans:beans>
spring xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<bean id="userFormValidator" class="com.validator.UserFormValidator"/>
<bean id="userProxy"
class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="target" ref="userManager" />
<property name="interceptorNames">
<list>
<value>transactionInterceptor</value>
</list>
</property>
</bean>
<bean id="genderManager" class="com.service.impl.GenderManagerImpl">
</bean>
<bean id="userProxyBean" class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="proxyInterfaces">
<value>com.service.UserManager</value>
</property>
<property name="target">
<ref bean="userManager" />
</property>
<property name="interceptorNames">
<list>
<value>loggerAdviser</value>
</list>
</property>
</bean>
<bean id="genderProxyBean" class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="proxyInterfaces">
<value>com.service.GenderManager</value>
</property>
<property name="target">
<ref bean="genderManager" />
</property>
<property name="interceptorNames">
<list>
<value>loggerAdviser</value>
</list>
</property>
</bean>
<bean id="loggerAdviser" class="org.springframework.aop.support.RegexpMethodPointcutAdvisor">
<property name="advice">
<ref bean="loggingInterceptor"/>
</property>
<property name="patterns">
<value>.*</value>
</property>
</bean>
<bean id="loggingInterceptor" class="com.log.LoggingInterceptor"/>
<bean id="userDetailController" class="com.web.UserDetailController">
<property name="userManager"><ref bean="userProxyBean"/></property>
</bean>
<bean id="loginController" class="com.web.LoginController">
</bean>
<bean id="userController" class="com.web.UserController">
<property name="sessionForm"><value>true</value></property>
<property name="commandName"><value>userBean</value></property>
<property name="commandClass"><value>com.beans.UserBean</value></property>
<property name="validator"><ref bean="userFormValidator"/></property>
<property name="formView"><value>userForm</value></property>
<property name="successView"><value>userDetail.do</value></property>
<property name="userManager"><ref bean="userProxyBean"/></property>
<property name="genderManager"><ref bean="genderProxyBean"/></property>
</bean>
<bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="urlMap">
<map>
<entry key="/user/userPage.do"><ref bean="userController"/></entry>
<entry key="/user/userDetail.do"><ref bean="userDetailController"/></entry>
<entry key="/user/login.do"><ref bean="loginController"/></entry>
</map>
</property>
</bean>
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"><value>org.springframework.web.servlet.view.JstlView</value></property>
<property name="prefix"><value>/WEB-INF/jsp/</value></property>
<property name="suffix"><value>.jsp</value></property>
</bean>
</beans>
web.xml
<servlet>
<servlet-name>context</servlet-name>
<servlet-class>
org.springframework.web.context.ContextLoaderServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<!-- Spring context loading ends-->
<servlet>
<servlet-name>user</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>user</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>dwr-invoker</servlet-name>
<servlet-class>uk.ltd.getahead.dwr.DWRServlet</servlet-class>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dwr-invoker</servlet-name>
<url-pattern>/dwr/*</url-pattern>
</servlet-mapping>
<taglib>
<taglib-uri>/spring</taglib-uri>
<taglib-location>/WEB-INF/spring.tld</taglib-location>
</taglib>
<!-- Spring Security -->
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
Now when ever i hit http://localhost:8080/springhibernate/user/login.do
it shows me login page but when click login it always gives me error
The requested resource (/springhibernate/user/j_spring_security_check) is not available.
The page is redirected to http://localhost:8080/springhibernate/user/j_spring_security_check
Please help me to solve this issue and suggest me how this login feature can be implimented in my app i am stuck with it
I have pretty much the same setup with a separate login form, but on login action the following method get's called:
(see edit)
Not too sure how it works but appearently it's neccessairy:
http://ocpsoft.com/java/jsf-java/spring-security-what-happens-after-you-log-in/
EDIT:
my form:
<h:form id="loginForm" prependId="false">
<label for="j_username"><h:outputText value="Username:" /><br />
</label>
<h:inputText id="j_username" required="true">
</h:inputText>
<br />
<br />
<label for="j_password"><h:outputText value="Password:" /><br />
</label>
<h:inputSecret id="j_password" required="true">
</h:inputSecret>
<br />
<br />
<label for="_spring_security_remember_me"> <h:outputText
value="Remember me" /> </label>
<h:selectBooleanCheckbox id="_spring_security_remember_me" />
<br />
<h:commandButton type="submit" id="login"
action="#{loginBean.doLogin}" value="Login" />
</h:form>
Login bean:
#SessionScope
public class LoginBean implements Serializable
{
private String j_username;
private String j_password;
private String _spring_security_remember_me;
public String getJ_username() {
return j_username;
}
public void setJ_username(String j_username) {
this.j_username = j_username;
}
public String getJ_password() {
return j_password;
}
public void setJ_password(String j_password) {
this.j_password = j_password;
}
public String get_spring_security_remember_me() {
return _spring_security_remember_me;
}
public void set_spring_security_remember_me(String _spring_security_remember_me) {
this._spring_security_remember_me = _spring_security_remember_me;
}
// This is the action method called when the user clicks the "login" button
public String doLogin() throws IOException, ServletException
{
ExternalContext context = FacesContext.getCurrentInstance().getExternalContext();
RequestDispatcher dispatcher = ((ServletRequest) context.getRequest())
.getRequestDispatcher("/j_spring_security_check");
dispatcher.forward((ServletRequest) context.getRequest(),
(ServletResponse) context.getResponse());
FacesContext.getCurrentInstance().responseComplete();
// It's OK to return null here because Faces is just going to exit.
return null;
}
}
Here are my working configs for your reference . They seem to be quite the same . These are for Spring 3.0 . Haven't tried with 2.x but thought this may help you .
<!-- Spring-security -->
<http auto-config="false" access-denied-page="/login.jsp?error=Access%20Denied">
<intercept-url pattern="/login.jsp*" filters="none" />
<intercept-url pattern="/manager/**" access="${manager.roles}" />
<form-login login-page="/login.jsp"
default-target-url="/welcome.jsp"
always-use-default-target="true"
authentication-failure-url="/login.jsp?error=true" />
<logout logout-success-url="/login.jsp"/>
<anonymous/>
</http>
<authentication-manager>
<authentication-provider>
<user-service>
<user name="a" password="a" authorities="ROLE_MANAGER" />
</user-service>
</authentication-provider>
</authentication-manager>
<!--Jsp -->
<form name="login" action="<c:url value="j_spring_security_check"/>" method="POST">
<table width="40%" border="4" align="center" cellpadding="0" cellspacing="0" bordercolor="#E3DBB8">
<tr><td bgcolor="#FFF4C3"><br>
<table width="100%" border="0" align="center" cellpadding="10" cellspacing="0" frame="box">
<tr>
<td align="right" nowrap><font face="Tahoma" size="+1">User Name:</font></td>
<td align="left" width="300"><input id="username" tabindex="1"
type="text" name="j_username" maxlength="20" border="1" style="width: 150px"/ ></td>
</tr>
<tr>
<td align="right" nowrap><font face="Tahoma" size="+1">Password:</font></td>
<td align="left"><input id="password" tabindex="2" type="password" name="j_password" maxlength="20" style="width: 150px"/></td>
</tr>
<tr>
<td align="right"><input type="submit" tabindex="3" name="login" value=" Login " class="Button" /></td>
<td align="left">
<input type="reset" tabindex="3" name="reset" value=" Reset " class="Button" />
</td>
</tr>
</table><br>
</td></tr>
</table>
</form >
<!--Web.xml -->
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

"An item with the same key has already been added" error when calling Context AddObject

Can somebody please help me with this error. I have an ASP.NET WebApp, within the Entity Model I have an entity called tb_AdminUser, with a UserID property as GUID. This is also the Entity Key. The entity is not in any relationship with any other entity. I get the error when calling the AddObject() function.
In my code I call the following...
SQL2008R2_824852_leapdbEntities temp = new SQL2008R2_824852_leapdbEntities();
tb_AdminUser au = new tb_AdminUser();
au.UserID = Guid.NewGuid();
au.Username = "TEST";
au.Password = "pete#webinspired.net";
au.LockedOut = false;
au.Surname = "Feehan";
au.Forename = "Pete";
temp.tb_AdminUser.AddObject(au); //error occurs here
temp.SaveChanges();
The EDMX XML Code is as follows
<EntityType Name="tb_AdminUser">
<Key>
<PropertyRef Name="UserID" />
</Key>
<Property Name="UserID" Type="uniqueidentifier" Nullable="false" />
<Property Name="Forename" Type="nvarchar" Nullable="false" MaxLength="50" />
<Property Name="Surname" Type="nvarchar" Nullable="false" MaxLength="50" />
<Property Name="Username" Type="nvarchar" Nullable="false" MaxLength="50" />
<Property Name="Password" Type="nvarchar" Nullable="false" MaxLength="50" />
<Property Name="LockedOut" Type="bit" Nullable="false" />
</EntityType>

Resources