I have the following xml
<?xml version="1.0" encoding="UTF-8"?>
<tests>
<testdef name="Gaps (Simple)">
<property GapInterval="null" />
<property ReturnAllOpt="null" />
</testdef>
<testdef name="Gaps (Holiday Aware)">
<property GapInterval="null" />
<property HolidayOrigin="null" />
<property ReturnAllOpt="null" />
</testdef>
I need to get the attributes of property for each of the testdef name.
List<string> values = new List<string>();
XmlNodeList valueslist = propdoc.GetElementsByTagName("testdef");
for (int i = 0; i < valueslist.Count; i++)
{
values.Add(valueslist[i].InnerXml);
Console.WriteLine(valueslist[i].InnerXml);
}
I have written the following code where I get the whole attribute of the testdef. Is there any way I can achieve my goal.
Related
I'm trying to select a node by its attribute name, but my selectors return nothing.
XML
<?xml version="1.0" encoding="utf-8"?>
<products>
<product ID="10036218">
<name>TEST</name>
<price currency="EUR">8.95</price>
<categories>
<category path="Feestartikelen">Feestartikelen</category>
</categories>
<properties>
<property name="fromPrice">
<value>8.95</value>
</property>
<property name="gender">
<value></value>
</property>
<property name="deliveryCosts">
<value>3.95</value>
</property>
<property name="model">
<value>Balloons</value>
</property>
</properties>
<variations/>
</product>
</products>
Dim nodeList As XmlNodeList = root.SelectNodes("/products/product")
nodelist.Count = 530 here, so I'm getting results.
Next I tried both properties/property/#model/value and properties/property/#model as values to select the node. Both return nothing.
For Each node In nodeList
If node.SelectSingleNode("properties/property/#model/value") IsNot Nothing Then
End If
Next node
What's wrong with my expressions?
This should get you the node by attribute name:
For Each node In nodeList
If node.SelectSingleNode("properties/property[#name='model']/value") IsNot Nothing Then
End If
Next node
I'm a newbie in spring batch and spring Mvc, and I want that a batch job (which extracts data from a database and writes it in another database) is executed from a jsp page by clicking on a button (or a link if it's possible) I'm using spring Mvc. This is my job configuration:
<bean id="jobRepository"
class="org.springframework.batch.core.repository.support.JobRepositoryFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="transactionManager" ref="transactionManager" />
<property name="databaseType" value="oracle" />
</bean>
<bean id="itemReader"
class="org.springframework.batch.item.database.JdbcCursorItemReader"
scope="step">
<property name="dataSource" ref="dataSource" />
<property name="sql"
value="select id,name,qual from users" />
<property name="rowMapper">
<bean class="tn.com.spring.UserRowMapper" />
</property>
</bean>
<bean id="oracleitemWriter"
class="org.springframework.batch.item.database.JdbcBatchItemWriter">
<property name="dataSource" ref="dataSource" />
<property name="sql">
<value>
<![CDATA[
insert into users2(id,name,qual)
values (:id,:name,:qual)
]]>
</value>
</property>
<property name="itemSqlParameterSourceProvider">
<bean
class="org.springframework.batch.item.database.BeanPropertyItemSqlParameterSourceProvider" />
</property>
</bean>
<batch:job id="Job" job-repository="jobRepository">
<batch:step id="step1">
<batch:tasklet transaction-manager="transactionManager">
<batch:chunk reader="itemReader" writer="oracleitemWriter"
commit-interval=" 10">
</batch:chunk>
</batch:tasklet>
</batch:step>
</batch:job>
<jdbc:initialize-database data-source="dataSource">
<jdbc:script
location="org/springframework/batch/core/schema-drop-oracle10g.sql" />
<jdbc:script location="org/springframework/batch/core/schema-oracle10g.sql" />
</jdbc:initialize-database>
and this is my job controller (I found it in the net but still not working!)
#Component
#Controller()
public class JobController {
#Autowired
#Qualifier("JobLauncher")
private JobLauncher jobLauncher;
#Autowired
#Qualifier("Job")
private Job job;
#RequestMapping(value = "/job")
public void job() {
try {
JobExecution execution = jobLauncher.run(job, new JobParameters());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
and here is the button
<form action=" <%=application.getContextPath()%>/job" method="get">
<input type="submit" value="execute My job" />
</form>
Could you please help me ? Whats's missing in my configuration?
I'm confused !
Thanks in advance.
As a solution for this problem, I have made this javascript code which will invoke the execution of the job :
$(function() {
$('#JobBtn').click(function() {
$.get('${batchJobUrl}');
});
});
and in the jsp page you need to specify the Id of the button writen in the javascript code:
<input type="button" value="execute job " id='JobBtn' class="btn" />
I Hope it will help someOne..
I am using velocity template for sending e-mail in my Spring MVC application , but the parameters I am sending to the template are not binding in the resulting email. Here what I am doing:
Dependency in my pom.xml for Velocity
<!-- velocity -->
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity</artifactId>
<version>1.7</version>
</dependency>
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-tools</artifactId>
<version>2.0</version>
</dependency>
Configuration in my spring-config.xml
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="host" value="smtp.gmail.com" />
<property name="username" value="abc#gmail.com" />
<property name="password" value="fakepass" />
<property name="javaMailProperties">
<props>
<prop key="mail.smtp.auth">true</prop>
<prop key="mail.smtp.socketFactory.port">465</prop>
<prop key="mail.smtp.socketFactory.class">javax.net.ssl.SSLSocketFactory</prop>
<prop key="mail.smtp.socketFactory.fallback">false</prop>
<prop key="mail.smtp.quitwait">false</prop>
<prop key="mail.debug">true</prop>
</props>
</property>
</bean>
<bean id="velocityEngine" class="org.springframework.ui.velocity.VelocityEngineFactoryBean">
<property name="velocityProperties">
<value>
resource.loader=class
class.resource.loader.class=org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader
</value>
</property>
</bean>
Here is the velocity template (.vm) file I have:
<html>
<body>
<h1 class="note-info"><strong>Forgot your application password?</strong></h1>
<p>
Dear ${model.userName}, <br />
We have received a request to reset your password.
</p>
<p>
To reset your password, Click on the link below or Copy and Paste the URL into your browser.<br />
The link will be valid for next 24 hours.
</p>
<p>
${model.link}
</p>
<p>
Best regards,<br />
The AppTeam
<br />
</p>
</body>
</html>
And here is the Java code sending the email
public void sendEmailNotification(final EmailNotification emailNotofication)throws Exception {
MimeMessagePreparator preparator = new MimeMessagePreparator() {
#SuppressWarnings({ "unchecked" })
public void prepare(MimeMessage mimeMessage) throws Exception {
MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
message.setTo(emailNotofication.getReceiversArr());
if(emailNotofication.getCcArr() != null)
message.setCc(emailNotofication.getCcArr());
if(emailNotofication.getBccArr() != null)
message.setBcc(emailNotofication.getBccArr());
message.setFrom(new InternetAddress(emailNotofication.getSender()) );
message.setSubject(emailNotofication.getSubject());
message.setSentDate(new Date());
Map<String,Object> model = new HashMap<String, Object>();
if(emailNotofication.getParams() != null)
{
Set<Map.Entry<String, Object>> entrySet = emailNotofication.getParams().entrySet();
for(Map.Entry<String, Object> entry : entrySet)
{
model.put(entry.getKey(), entry.getValue());
}
}
String text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine,emailNotofication.getMailTemplate(),"UTF-8",model);
message.setText(text, true);
}
};
mailSender.send(preparator);
}
I am adding the variables in model as key value pair in mergeTemplateIntoString(), but still the in the resulting email I am getting
${model.userName} and ${model.link}, those are not replaced by the value passed in model.
I fond the answer , posting the same as it may help some-one else. The problem is in .vm file. Need to use just ${link} instead of ${model.link}.
I am trying to enhance my spring-enabled web-app's security using Apache Shiro and am thus configuring filterchain definitions into a spring-configured file.
How do i achieve the equivalent of
#Controller
#RequestMapping("/mywebapp")
// #RequiresAuthentication (is this possible ? wish i could do this !)
public class MyWebAppController {
#RequiresRoles(value={"Role1","Role2","Role3"},logical=Logical.OR)
#RequestMapping(value="/home", method = RequestMethod.GET)
public String home() { return .. }
and my spring-config file contains this :
assume that my dispatcherservlet is mapped to /rest/*
<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
<property name="securityManager" ref="securityManager"/>
<property name="loginUrl" value="/rest/secure/windowslogin"/>
<property name="successUrl" value="/mywebapp/rest/menu"/>
<property name="unauthorizedUrl" value="/mywebapp/rest/unauthorized"/>
<property name="filters">
<util:map>
<entry key="anon">
<bean class="org.apache.shiro.web.filter.authc.AnonymousFilter"/>
</entry>
<entry key="authc">
<!-- why is this not invoked ? -->
<bean class="org.apache.shiro.web.filter.authc.PassThruAuthenticationFilter">
</bean>
</entry>
<entry key="roles">
<bean class="org.apache.shiro.web.filter.authz.RolesAuthorizationFilter"/>
</entry>
</util:map>
</property>
<property name="filterChainDefinitions">
<value>
/rest/secure/** = anon
/rest/mywebapp/** = authc, roles[Role1,Role2,Role3]
</value>
</property>
</bean>
In the code above i need a logical.OR kind of mapping to the /rest/mywebapp/** using the roles mentioned. This is possible via shiro annotations and it works but rather than specifying at every method i would rather handle it here (since i dont think shiro supports class level annotations yet ?) .
Is this possible ?
Also on a side note why is the authc filter not invoked ?
( for now we assume that the windows login can serve as authentication, using shiro only for authorization )
home page = meta refresh to /rest/secure/windowslogin/
if within intranet -> login ...
else /rest/secure/login ... login page.
Is it because the loginurl is different ? How do i circumvent this ? Note that my realm's getAuthorizationInfo is invoked though using the roles[ .. ] part specified in the config file.. but i was assuming that there should be a check to see if the request is 'authc' ? (which probably means that the filter is invoked and SubjectUtils.getSubject() is checked for authentication). Am i missing something in the flow or configuration ?
This is how shiro-security.xml looks like.
<bean id="customFilter1" class="com.pkg.RolesAuthorizationFilter">
<property name="roles" value="ROLE1,ROLE3,ROLE5"></property>
</bean>
<bean id="customFilter2" class="com.pkg.RolesAuthorizationFilter">
<property name="roles" value="ROLE1,ROLE2,ROLE5,ROLE6"></property>
</bean>
<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
<property name="securityManager" ref="securityManager" />
<property name="loginUrl" value="/login" />
<property name="successUrl" value="/home" />
<property name="unauthorizedUrl" value="/unauthorized" />
<property name="filters">
<util:map>
<entry key="authc">
<bean class="org.apache.shiro.web.filter.authc.PassThruAuthenticationFilter" />
</entry>
</util:map>
</property>
<property name="filterChainDefinitions">
<value>
/resources/** = anon
/login = anon
/logout = authc
/unauthorized = authc
/someurl/** = customFilter2
/** = customFilter1
</value>
</property>
</bean>
And this is RolesAuthorizationFilter class
package com.pkg;
import java.util.Arrays;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import org.apache.log4j.Logger;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authz.AuthorizationFilter;
public class RolesAuthorizationFilter extends AuthorizationFilter {
protected Logger logger = Logger.getLogger(this.getClass()
.getCanonicalName());
private String[] roles;
#Override
protected boolean isAccessAllowed(ServletRequest request,
ServletResponse response, Object mappedValue) throws Exception {
logger.info("= Roles = " + Arrays.toString(roles));
Subject subject = getSubject(request, response);
boolean allowAccess = false;
for (String role : roles) {
if (subject.hasRole(role)) {
logger.info("Authenticated role " + role);
allowAccess = true;
break;
}
}
return allowAccess;
}
public void setRoles(String[] roles) {
this.roles = roles;
}
}
I;m trying to create RSS feeds for my web site. I follow the tutorial from mkyong (http://www.mkyong.com/spring-mvc/spring-3-mvc-and-rss-feed-example/) which was quite useful. According to this tutorial i create a model class and the following class
public class CustomRssViewer extends AbstractRssFeedView{
#Override
protected void buildFeedMetadata(){
//some code
}
#Override
protected List<Item> buildFeedItems(){
//some code
}
}
And finally the controller class
#Controller
public class RssController {
#RequestMapping(value="/rssfeed", method = RequestMethod.GET)
public ModelAndView getFeedInRss() {
//set the RSS content
ModelAndView mav = new ModelAndView();
mav.setViewName("rssViewer");
mav.addObject("feedContent", items);
return mav;
}
}
According to the tutorial the View rssViewer belongs the class CustomRssViewer , so i need to write it at the dispatcher servlet the following lines of code:
<bean class="org.springframework.web.servlet.view.BeanNameViewResolver" />
<bean id="rssViewer" class="com.mkyong.common.rss.CustomRssViewer" />
My problem is that i'm using apache tiles. So the rssViewer can not be recognised as i didn't enhanced it to the tiles definition. And i really don't know how can i do this. For example i need to write something as the following:
<definition name="rssViewer" template="?">
<put-attribute name="title" value=""/>
<put-attribute name="content" value=""/>
</definition>
At the template i don't know what to declare as well as at the put-attribute.Because until now at the template i use to declare the direction that a specific jsp exists. Something like this:
template="/WEB-INF/pages/mypage.jsp"
And also at the view-properties i don't know what should i declare.
Thanks in advance for any comment or response.
You should use a ContentNegotiatingViewResolver in conjuction with that example's BeanNameViewResolver. Just declare the order property of your already existing BeanNameViewResolver to be 1, and set the order property of the new ContentNegotiatingViewResolver to 0.
You should then configure the ContentNegotiatingViewResolver to use the appropriate View for RSS, and set the media type for RSS.
Here is an example from the Spring Docs:
<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<property name="mediaTypes">
<map>
<entry key="atom" value="application/atom+xml"/>
<entry key="html" value="text/html"/>
<entry key="json" value="application/json"/>
</map>
</property>
<property name="viewResolvers">
<list>
<bean class="org.springframework.web.servlet.view.BeanNameViewResolver"/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
</list>
</property>
<property name="defaultViews">
<list>
<bean class="org.springframework.web.servlet.view.json.MappingJacksonJsonView" />
</list>
</property>
</bean>
Note, they are using atom, not RSS, but the idea is the same. Also they do not set the order (which you should do).