error occured when adding anotation to the java class - spring-mvc

Multiple markers at this line
- Repository cannot be resolved to a type
- The attribute value is undefined for the annotation type
Error gets when trying to add #Repository("loginDAO") to the loginDAOImpl.java. I don't use maven.
#Repository("loginDAO")
public class LoginDAOImpl implements LoginDAO {
#Resource(name="sessionFactory")
protected SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
protected Session getSession(){
return sessionFactory.openSession();
}
public boolean checkLogin(String userName, String userPassword) {
System.out.println("In Check login");
Session session = sessionFactory.openSession();
boolean userFound = false;
//Query using Hibernate Query Language
String SQL_QUERY =" from Users as o where o.userName=? and o.userPassword=?";
Query query = session.createQuery(SQL_QUERY);
query.setParameter(0,userName);
query.setParameter(1,userPassword);
List list = query.list();
if ((list != null) && (list.size() > 0)) {
userFound= true;
}
session.close();
return userFound;
}

Related

System.InvalidOperationException: ExecuteNonQuery requires an open and available Connection. The connection's current state is open

I`m trying use this factory:
public class SqlConnectionFactory : ISqlConnectionFactory, IDisposable
{
private readonly string _connectionString;
private IDbConnection _connection;
public SqlConnectionFactory(string connectionString)
{
this._connectionString = connectionString;
}
public IDbConnection GetOpenConnection()
{
if (this._connection == null || this._connection.State != ConnectionState.Open)
{
//this._connection = new SqlConnection(_connectionString);
this._connection = new NpgsqlConnection(_connectionString);
this._connection.Open();
}
return this._connection;
}
public IDbConnection CreateNewConnection()
{
var connection = new NpgsqlConnection(_connectionString);
connection.Open();
return connection;
}
public string GetConnectionString()
{
return _connectionString;
}
public void Dispose()
{
if (this._connection != null && this._connection.State == ConnectionState.Open)
{
this._connection.Dispose();
}
}
}
But, after some time after successful work, I get an error
System.InvalidOperationException: ExecuteNonQuery requires an open and available Connection. The connection's current state is open.
What does this mean ? My connection state is open.
UPD. Usage example :
internal class GetMemberQueryHandler : IQueryHandler<GetMemberQuery, MemberDto>
{
private readonly ISqlConnectionFactory _sqlConnectionFactory;
public GetMemberQueryHandler(ISqlConnectionFactory sqlConnectionFactory)
{
_sqlConnectionFactory = sqlConnectionFactory;
}
public async Task<MemberDto> Handle(GetMemberQuery query, CancellationToken cancellationToken)
{
var connection = _sqlConnectionFactory.GetOpenConnection();
var sql = "some sql";
return await connection.QuerySingleAsync<MemberDto>(sql, new { query.MemberId });
}
}

Query with DynamoDB Secondary Index AWS SDK 2 Java exception creating DynamoDbIndex object

I'm having trouble running a query against a secondary index, getting an exception:
Ex getting dynamodb scan: java.lang.IllegalArgumentException: Attempt to execute an operation that requires a secondary index without defining the index attributes in the table metadata. Index name: category-timestamp-index
Can someone guide me on how I'm doing this wrong?
My table is idIT_RSS_Sources and I've created an index category-timestamp-index.
screenshot attached of index
My code is:
DynamoDbEnhancedClient enhancedClient = getEnhancedDBClient(region);
// Create a DynamoDbTable object
logger.debug("getting RSS Source category-timestamp-index");
//this throws the exception
DynamoDbIndex<RSS_Source> catIndex =
enhancedClient.table("idIT_RSS_Sources",
TableSchema.fromBean(RSS_Source.class))
.index("category-timestamp-index");
logger.debug("building query attributes");
AttributeValue att = AttributeValue.builder()
.s(theCategory)
.build();
Map<String, AttributeValue> expressionValues = new HashMap<>();
expressionValues.put(":value", att);
Expression expression = Expression.builder()
.expression("category = :value")
.expressionValues(expressionValues)
.build();
// Create a QueryConditional object that's used in the query operation
QueryConditional queryConditional = QueryConditional
.keyEqualTo(Key.builder().partitionValue(theCategory)
.build());
logger.debug("calling catIndex.query in getRSS...ForCategory");
Iterator<Page<RSS_Source>> dbFeedResults = (Iterator<Page<RSS_Source>>) catIndex.query(
QueryEnhancedRequest.builder()
.queryConditional(queryConditional)
.build());
solved, I was not using the proper annotation in my model class:
#DynamoDbSecondaryPartitionKey(indexNames = { "category-index" })
public String getCategory() { return category; }
public void setCategory(String category) { this.category = category; }
Assume you have a model named Issues.
package com.example.dynamodb;
import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbBean;
import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbPartitionKey;
import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbSecondaryPartitionKey;
import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbSortKey;
#DynamoDbBean
public class Issues {
private String issueId;
private String title;
private String createDate;
private String description;
private String dueDate;
private String status;
private String priority;
private String lastUpdateDate;
#DynamoDbPartitionKey
public String getId() {
return this.issueId;
}
public void setId(String id) {
this.issueId = id;
}
#DynamoDbSortKey
public String getTitle() {
return this.title;
}
public void setTitle(String title) {
this.title = title;
}
public void setLastUpdateDate(String lastUpdateDate) {
this.lastUpdateDate = lastUpdateDate;
}
public String getLastUpdateDate() {
return this.lastUpdateDate;
}
public void setPriority(String priority) {
this.priority = priority;
}
public String getPriority() {
return this.priority;
}
public void setStatus(String status) {
this.status = status;
}
public String getStatus() {
return this.status;
}
public void setDueDate(String dueDate) {
this.dueDate = dueDate;
}
#DynamoDbSecondaryPartitionKey(indexNames = { "dueDateIndex" })
public String getDueDate() {
return this.dueDate;
}
public String getDate() {
return this.createDate;
}
public void setDate(String date) {
this.createDate = date;
}
public String getDescription() {
return this.description;
}
public void setDescription(String description) {
this.description = description;
}
}
Notice the annotation on getDueDate.
#DynamoDbSecondaryPartitionKey(indexNames = { "dueDateIndex" })
public String getDueDate() {
return this.dueDate;
}
This is because the Issues table has a secondary index named dueDateIndex.
To query on this secondary index, you can use this code that uses the Amazon DynamoDB Java API V2:
public static void queryIndex(DynamoDbClient ddb, String tableName, String indexName) {
try {
// Create a DynamoDbEnhancedClient and use the DynamoDbClient object
DynamoDbEnhancedClient enhancedClient = DynamoDbEnhancedClient.builder()
.dynamoDbClient(ddb)
.build();
//Create a DynamoDbTable object based on Issues
DynamoDbTable<Issues> table = enhancedClient.table("Issues", TableSchema.fromBean(Issues.class));
String dateVal = "2013-11-19";
DynamoDbIndex<Issues> secIndex =
enhancedClient.table("Issues",
TableSchema.fromBean(Issues.class))
.index("dueDateIndex");
AttributeValue attVal = AttributeValue.builder()
.s(dateVal)
.build();
// Create a QueryConditional object that's used in the query operation
QueryConditional queryConditional = QueryConditional
.keyEqualTo(Key.builder().partitionValue(attVal)
.build());
// Get items in the Issues table
SdkIterable<Page<Issues>> results = secIndex.query(
QueryEnhancedRequest.builder()
.queryConditional(queryConditional)
.build());
AtomicInteger atomicInteger = new AtomicInteger();
atomicInteger.set(0);
results.forEach(page -> {
Issues issue = (Issues) page.items().get(atomicInteger.get());
System.out.println("The issue title is "+issue.getTitle());
atomicInteger.incrementAndGet();
});
} catch (DynamoDbException e) {
System.err.println(e.getMessage());
System.exit(1);
}
}
For what it's worth, if your Global Secondary Index has a sort key, you must annotate that field in the DynamoDB bean with:
#DynamoDbSecondarySortKey(indexNames = { "<indexName>" })
public String getFieldName() {
return fieldName;
}
My working code is as below:
sortKey-index = GSI in dynamo db
List<Flow> flows = new ArrayList<>();
DynamoDbIndex<Flow> flowBySortKey = table().index("sortKey-index");
// Create a QueryConditional object that's used in the query operation
QueryConditional queryConditional = QueryConditional
.keyEqualTo(Key.builder()
.partitionValue(sortKey)
.build());
SdkIterable<Page<Flow>> dbFeedResults = flowBySortKey.query(
QueryEnhancedRequest.builder()
.queryConditional(queryConditional)
.build());
dbFeedResults.forEach(flowPage -> {
flows.addAll(flowPage.items());
});

How to read custom annotation value using reflection?

I am trying to read custom annotation value using reflection.
I see the custom annotation in debug but when i try to typecast annotation to my custom annotation, I am getting ClassCastException.
What am I doing wrong?
//custom annotation
#Retention(Retention.RUNTIME)
#Target({ElementType.METHOD})
public #interface SendEmail{
public String id;
}
//method annotated with custom annotation
#SendEmail(id="test#test.com")
public void testEmail(){
}
// extracting custom annotation using reflection
Set<Method> annotatedMethods = reflections.getMethodsAnnotatedWith(SendEmail.class);
for(Methods method : annotatedMethods){
Annotations[] annotations = method.getDeclaredAnnotations();
SendEmail sendEmail = method.getAnnotation(SendEmail.class); // returns null;
for(Annotation annotation : annotations){
annotation.annotationType.getName(); // com.test.email.annotation.SendEmail
annotation.toString(); // #com.test.email.annotation.SendEmail(id=test#test.com)
SendEmail sendEmail = (SendEmail) annotation; // ClassCastException com.sun.proxy.$Proxy24 cannot be cast to com.test.email.annotation.SendEmail
if(annotation.annotationType.getName() == SendEmail.class.getName()){
SendEmail sendEmail = (SendEmail) annotation; // ClassCastException com.sun.proxy.$Proxy24 cannot be cast to com.test.email.annotation.SendEmail
}
}
Can read custom annotation value using java reflection as described in below code.
public class ValidatorClassName implements ConstraintValidator<RemarkValid, Object> {
private String remark;
private String enable;
#Override
public void initialize(RemarkValid constraintAnnotation) {
enable = constraintAnnotation.enable();
remark = constraintAnnotation.remark();
}
#Override
public boolean isValid(Object objectToValidate, ConstraintValidatorContext context) {
String remarkFieldValue;
Boolean enableFieldValue;
try {
context.disableDefaultConstraintViolation();
remarkFieldValue = (String) getFieldValue(objectToValidate, remark);
enableFieldValue = (Boolean) getFieldValue(objectToValidate, enable);
/*logic*/
} catch (Exception e) {
log.error(e.getLocalizedMessage());
}
return true;
}
private Object getFieldValue(Object object, String remark) throws Exception {
Field field = object.getClass().getDeclaredField(remark);
field.setAccessible(true);
return field.get(object);
}
}
As well as can create a BeanWrapperImpl for the given object to read bean property value as below,
BeanWrapper objectToValidateBean = new BeanWrapperImpl(objectToValidate);
Object actualValue = objectToValidateBean.getPropertyValue(remark);

ASP.NET Core 2.1 How to pass variables to TypeFilter

I have created this typefilter that is supposed to take 2 variables in order for it to send to a method that is linked to the filter. However, I am unable to attach my 2 variables for it to run.
public class RolesFilterAttribute : TypeFilterAttribute
{
public RolesFilterAttribute() : base(typeof(RolesFilterAttributeImpl))
{
}
private class RolesFilterAttributeImpl : IActionFilter
{
private readonly ValidateRoleClient validateRoleClient;
private string Role;
private string SecretKey;
public RolesFilterAttributeImpl(string Role, string SecretKey, ValidateRoleClient validateRoleClient)
{
this.validateRoleClient = validateRoleClient;
this.Role = Role;
this.SecretKey = SecretKey;
}
public void OnActionExecuted(ActionExecutedContext context)
{
if (context.HttpContext.Request.Cookies["Token"] != null || context.HttpContext.Request.Cookies["RefreshToken"] != null)
{
TokenViewModel tvm = new TokenViewModel
{
Token = context.HttpContext.Request.Cookies["Token"],
RefreshToken = context.HttpContext.Request.Cookies["RefreshToken"]
};
ValidateRoleViewModel vrvm = new ValidateRoleViewModel
{
Role = Role,
SecretKey = SecretKey,
Token = tvm
};
validateRoleClient.ValidateRole(vrvm);
}
}
public void OnActionExecuting(ActionExecutingContext context)
{
throw new NotImplementedException();
}
}
}
This is how I declare the filter and it compiles fine. However, I am not able to pass the required variables which are SecretKey and Role through it. Is my typefilter declared correctly?
[TypeFilter(typeof(RolesFilterAttribute))]
public IActionResult About()
{
return View();
}
Taken from the official documentation
[TypeFilter(typeof(AddHeaderAttribute),
Arguments = new object[] { "Author", "Steve Smith (#ardalis)" })]
public IActionResult Hi(string name)
{
return Content($"Hi {name}");
}

Create a session scoped bean in spring security

I need to create a POJO class that will store information pertaining to a user. In spring security, my authorities table has an extra column of instituionIds, it is a CSV string that will be needed in various DAO calls. I need to set the values of this class, which will be needed when querying the database.
#Component
#Scope("session")
public class InstitutionList {
private String institutionList = "";
public String getInstitutionList() {
return institutionList;
}
public void setInstitutionList(String institutionList) {
this.institutionList = institutionList;
}
}
I need to use this in my custom UserDetailsService implementation
#Transactional
#Service
public class UserDetailsServiceImpl implements UserDetailsService {
private static final Logger logger = LoggerFactory.getLogger(UserDetailsServiceImpl.class);
private #Autowired ACSAdminUsersService acsAdminUsersService;
private #Autowired ACSAdminAuthoritiesService acsAdminAuthoritiesService;
private String[] authority;
public ACSAdminUsers getUserByAdminUsername(String username) {
logger.info("Getting user by username");
ACSAdminUsers user = acsAdminUsersService.getUserByAdminUsername(username);
if(user!=null) acsAdminUsersService.addLogInInfo(username);
return user;
}
#Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
ACSAdminUsers user = getUserByAdminUsername(username);
logger.info("Username is : " + username);
logger.info("user is : " + user);
authority = acsAdminAuthoritiesService.getAuthoritiesForRole(user.getRole());
logger.info("User role is : " + authority);
if(authority == null) {
throw new UsernameNotFoundException("User : "+username+" has no authorities." );
}else {
boolean accountNonExpired = true;
boolean credentialsNonExpired = true;
boolean accountNonLocked = true;
return new org.springframework.security.core.userdetails.User(username,user.getAdmin_pass(),
true,accountNonExpired,credentialsNonExpired,
accountNonLocked,
getAuthorities(username));
}
}
public Collection<? extends GrantedAuthority> getAuthorities(String username) {
List<GrantedAuthority> authList = null;
authList=new ArrayList<GrantedAuthority>();
for(int i = 0; i < authority.length; i++) {
SimpleGrantedAuthority s = new SimpleGrantedAuthority(this.authority[i]);
authList.add(s);
}
return authList;
}
}
In the above java class I need to query the database and fetch, along with authorities, institutionIds which need to be used in queries throughout the application.
You could create your own InstitutionContextHolder and use a threadlocal to store the object. In this way you can acces this object in every class you want. You can take a look at the SecurityContextHolder for examples.

Resources