Spring AuditingHandler in Scheduled jobs - spring-security

Is it possible to use AuditingHandler in #Scheduled job? My system already uses AuditingHandler to rest endpoints to work, but now we have our very first scheduled job and using this technique is not handling auditing.
Here's my task class:
#Service
#RequiredArgsConstructor
public class AgendamentoTituloTask {
private final AgendamentoTituloService agendamentoTituloService;
#Scheduled(fixedRate = 60000)
public void salvarTitulosDosAgendamentos() {
this.agendamentoTituloService.salvarTitulosDosAgendamentos();
}
}
Here's my auditable entity:
#Getter(AccessLevel.PROTECTED)
#Setter(AccessLevel.PROTECTED)
#MappedSuperclass
#EntityListeners(AuditingEntityListener.class)
public class Auditable<U> {
#CreatedBy
#Column(name = "created_by", insertable = true, updatable = false)
protected U createdBy;
#CreatedDate
#Temporal(TIMESTAMP)
#Column(name = "created_date", insertable = true, updatable = false)
protected Date createdDate;
#LastModifiedBy
#Column(name = "updated_by", insertable = true, updatable = true)
protected U updatedBy;
#LastModifiedDate
#Temporal(TIMESTAMP)
#Column(name = "updated_date", insertable = false, updatable = true)
protected Date updatedDate;
}

Related

Thymeleaf - th:checked works, th:field fails

Thymeleaf
Im trying to bind a variable called 'permitirAcesso' to thymeleaf. When I use th:checked, it shows the value correctly. When I use th:field, it doesnt bind. What should I do?
I investigated and th:text shows the correct value. Ive also tried changing the variable name, but it still doesnt work. Ive also tried to use a common html checkbox, it still doesnt bind.
Ive simplified the page and removed everything except the form and the malfunction persists. It works with th:checked but fails to bind with th:field.
Here's my code:
<head>
<meta charset="UTF-8"/>
</head>
<body>
<form id="formulario" th:action="#{/painel-do-administrador/usuarios/salvar}" th:object="${usuario}" method="POST" class="action-buttons-fixed">
<input type="checkbox" name="permitirAcesso" id="permitirAcesso" th:field="*{permitirAcesso}" />
<input type="checkbox" name="permitirAcesso" id="permitirAcesso" th:checked="*{permitirAcesso}" />
</form>
</body>
My Java Code:
#Entity
#Table(name = "users")
public class User implements UserDetails, Comparable<User> {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#NotBlank(message = "O nome não pode ser nulo")
#NotNull(message = "O nome não pode ser nulo")
#Column(name = "username", nullable = false, length = 512, unique = true)
private String username;
#Column(name = "nome_completo", updatable = true, nullable = false)
private String nomeCompleto;
#Column(name = "password", updatable = true, nullable = false)
private String password;
#Column(name = "ultimo_acesso")
private ZonedDateTime ultimoAcesso;
#Email(message = "Insira uma e-mail válido")
#Column(name = "email", updatable = true, nullable = false)
private String email;
#Column(name = "permitir_acesso")
private boolean permitirAcesso;
#Lob
#Column(name = "avatar", columnDefinition = "BLOB")
private byte[] avatar;
#ManyToMany(fetch = FetchType.EAGER)
#JoinTable(
name = "users_roles",
joinColumns = #JoinColumn(name = "user_id"),
inverseJoinColumns = #JoinColumn(name = "role_id"))
private Set<Role> roles = new HashSet<>();
public User() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
#Override
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getNomeCompleto() {
return nomeCompleto;
}
public void setNomeCompleto(String nomeCompleto) {
this.nomeCompleto = nomeCompleto;
}
#Override
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public ZonedDateTime getUltimoAcesso() {
return ultimoAcesso;
}
public void setUltimoAcesso(ZonedDateTime ultimoAcesso) {
this.ultimoAcesso = ultimoAcesso;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public boolean isPermitirAcesso() {
return permitirAcesso;
}
public String getPermitirAcessoString() {
if (permitirAcesso) {
return "Sim";
} else {
return "Não";
}
}
public void setPermitirAcesso(boolean permitirAcesso) {
this.permitirAcesso = permitirAcesso;
}
public Set<Role> getRoles() {
return roles;
}
public void setRoles(Set<Role> roles) {
this.roles = roles;
}
public void addRole(Role role) {
this.roles.add(role);
}
public boolean hasRole(Role role) {
Iterator<Role> iterator = this.roles.iterator();
while (iterator.hasNext()) {
if (role.equals(iterator.next())) {
return true;
}
}
return false;
}
public boolean hasRole(String roleName) {
for (Role role : this.roles) {
if (role.getName().equals(roleName)) {
return true;
}
}
return false;
}
#Override
#JsonIgnore
public Collection<? extends GrantedAuthority> getAuthorities() {
return Collections.emptyList();
}
#Override
public int compareTo(User o) {
return getEmail().compareToIgnoreCase(o.getEmail());
}
#Override
#JsonIgnore
public boolean isAccountNonExpired() {
return true;
}
#Override
#JsonIgnore
public boolean isAccountNonLocked() {
return true;
}
#Override
#JsonIgnore
public boolean isCredentialsNonExpired() {
return true;
}
#Override
#JsonIgnore
public boolean isEnabled() {
return isPermitirAcesso();
}
}
Ok. This was a stupid mistake of mine. So what happened is that I had a Boolean Converter that converted Boolean to String. Removing the converter, fixed the issue.

how receive data from apple server notification in spring boot project

how to define the endpoint on spring boot server to receive server notification after read the app doc, this is what I am doing now:
#Api
#RequestMapping("/post/notification")
#FeignClient(name = "dolphin-post-service")
#Validated
public interface IAppleServerNotificationController {
/**
* Receive Apple Server Notification
* #param
* #return
*/
#PostMapping("/v1/appleSeverNotification")
Response<Integer> handleNotification(#RequestBody #Valid ServerNotificationRequest request);
}
and this is the entity I am define:
#Data
#NoArgsConstructor
#JsonIgnoreProperties(ignoreUnknown = true)
public class ServerNotificationRequest implements Serializable {
#ApiModelProperty(value = "responseBody")
#NonNull
private String responseBody;
}
but It seems not work. where I am going wrong? Any suggestion?
#Override
#NoCheck
public Response<Integer> handleNotification(ServerNotificationRequest request) {
JSONObject jsonResult = JSONObject.parseObject(request.getResponseBody());
AppleServerNotificationRecord record = new AppleServerNotificationRecord();
record.setResponseBody(request.getResponseBody());
record.setNotificationType(jsonResult.getString("notification_type"));
int result = notificationRecordService.saveNotificationRecord(record);
return new Response<>(result);
}
the responseBody is null!!!
define the request entity like this:
#Data
#NoArgsConstructor
#JsonIgnoreProperties(ignoreUnknown = true)
public class ServerNotificationRequest implements Serializable {
#ApiModelProperty(value = "auto_renew_adam_id")
#JsonProperty("auto_renew_adam_id")
private String autoRenewAdamId;
#ApiModelProperty(value = "auto_renew_product_id")
#JsonProperty("auto_renew_product_id")
private String autoRenewProductId;
#ApiModelProperty(value = "auto_renew_status")
#JsonProperty("auto_renew_status")
private String autoRenewStatus;
#ApiModelProperty(value = "auto_renew_status_change_date")
#JsonProperty("auto_renew_status_change_date")
private String autoRenewStatusChangeDate;
#ApiModelProperty(value = "auto_renew_status_change_date_ms")
#JsonProperty("auto_renew_status_change_date_ms")
private String autoRenewStatusChangeDateMs;
#ApiModelProperty(value = "auto_renew_status_change_date_pst")
#JsonProperty("auto_renew_status_change_date_pst")
private String autoRenewStatusChangeDatePst;
#ApiModelProperty(value = "environment")
private String environment;
#ApiModelProperty(value = "expiration_intent")
#JsonProperty("expiration_intent")
private Integer expirationIntent;
#ApiModelProperty(value = "notification_type")
#JsonProperty("notification_type")
private String notificationType;
#ApiModelProperty(value = "password")
#JsonProperty("password")
private String sharedSecret;
//#ApiModelProperty(value = "unified_receipt")
//#JsonProperty("unified_receipt")
//private String unifiedReceipt;
#ApiModelProperty(value = "bid")
private String bid;
#ApiModelProperty(value = "bvrs")
private String bvrs;
}

IOptionsSnapshot in .net core Console application not working

Below is the example of .NET Core console application, uses constructor dependency injection with IOptionsSnapshot<T>.
class Program
{
static void Main(string[] args)
{
IConfigurationRoot configuration = new ConfigurationBuilder()
.AddJsonFile("appsettings.json",
optional: false, reloadOnChange: true)
.Build();
IServiceProvider provider = new ServiceCollection()
.Configure<AppSettings>(
configuration.GetSection("AppSettings"))
.AddTransient<CheckOption>()
.BuildServiceProvider();
while (true)
{
if (Console.ReadLine() != "stop")
{
CheckOption checkOption =
provider.GetRequiredService<CheckOption>();
checkOption.Run();
}
else
{
return;
}
}
}
}
public class CheckOption
{
public AppSettings _AppSettings;
public CheckOption(IOptionsSnapshot<AppSettings> appSettings)
{
_AppSettings = appSettings.Value;
}
public void Run()
{
string option1 = _AppSettings.Option1;
string option2 = _AppSettings.Option2;
}
}
public class AppSettings
{
public string Option1 {get; set;}
public string Option2 {get; set;}
}
Values of Option1 and Option2 remains same, on change of "appsettings.json" in while loop.

GORM is not saving my hasMany entity

So I am asking a lot about GORM lately because it's the first time I am using it, and each time I have some issues with relations between objects and saving them.
So this is one class:
class TesterUser {
#Id
private String id
private String userId
static belongsTo = Dashboard
static constraints = {
userId nullable: true
}
static mapping = {
id column: 'id', generator: 'assigned'
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
And this is the other class:
class TestingClass {
#Id
private String id
private Date created
private Date modified
private String title
private ClassName className
static hasMany = [testUsers : TesterUser, sheets : Sheet]
static belongsTo = ClassName
static constraints = {
modified nullable: true
title nullable: true
className nullable: true
}
static mapping = {
sheets column:'testingClassId',joinTable: false
testUsers column:'testingClassId',joinTable: false
id column: 'id', generator: 'assigned'
title column: "title", length: 90000
}
public Date getCreated() {
return created;
}
public void setCreated(Date created) {
this.created = created;
}
public Date getModified() {
return modified;
}
public void setModified(Date modified) {
this.modified = modified;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public DavUser getClassName() {
return className;
}
public void setClassName(ClassName className) {
this.className = className;
}
public Date getDeleted() {
return deleted;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
I already saved the objects in the DB, but now I want to set the relations between them and when I call and save them it's not working:
TesterUser testU = TesterUser.findById(uId)
TestingClass testC = TestingClass.findById(cId)
if(testU != null && testC != null){
amountOfRelations++
testC.addToDashboardUsers(testU)
if(!dtestC.save(flush:true, failOnError: true)){
amountOfUnsaved++
}
else{
amountOfsaved++
}
For some reason, I get no error. Not only that, I can see the queries are going to my db, but nothing happens. There is no update and no error.
I have no idea why it's not working.
Any idea?
Eventually I was not able to save my entities.
My 'solution' was to save the entity in the first place using addTo method.
I still don't know why it didn't work or what I needed to do in order to make my entity to be saved, but still I got a workaround.

Related nodes are not fetched in Spring Data Neo4j 4.0.0

I have a weird problem with the node auto fetching in Spring Data Neo4j 4.0.0.
I have a class like below :
#NodeEntity
public class FilterVersionChange extends UnitVersion {
#GraphId
private Long id;
public FilterVersionChange() {
super();
}
public FilterVersionChange(String description, Long creationDate)
{
super(description, creationDate);
}
#Relationship(type="CONTAINS", direction = Relationship.OUTGOING)
private Set<FilterState> filterStates;
#Relationship(type="REFERENCES", direction = Relationship.OUTGOING)
private FilterVersionChange referencedFilterVersionChange;
#Relationship(type="ADDED", direction = Relationship.OUTGOING)
private Set<FilterState> newFilterStates;
#Relationship(type="DELETED", direction = Relationship.OUTGOING)
private Set<FilterState> deletedFilterStates;
#Relationship(type="MODIFIED", direction = Relationship.OUTGOING)
private Set<ModifiedUnitState> modifiedFilterStates;
#Relationship(type="TRACKS", direction = Relationship.INCOMING)
private FilterVersion filterVersion;
#Relationship(type = "CREATED_ON", direction = Relationship.OUTGOING)
private TimeTreeSecond timeTreeSecond;
public void createdOn(TimeTreeSecond timeTreeSecond) {
this.timeTreeSecond = timeTreeSecond;
}
public void contains(Set<FilterState> filterStates) {
this.filterStates = filterStates;
}
public void references(FilterVersionChange referencedFilterVersionChange) {
this.referencedFilterVersionChange = referencedFilterVersionChange;
}
public void added(Set<FilterState> newFilterStates) {
this.newFilterStates = newFilterStates;
}
public void deleted(Set<FilterState> deletedFilterStates) {
this.deletedFilterStates = deletedFilterStates;
}
public void modified(Set<ModifiedUnitState> modifiedFilterStates) {
this.modifiedFilterStates = modifiedFilterStates;
}
public void trackedIn(FilterVersion filterVersion) {
this.filterVersion = filterVersion;
}
public FilterVersion getFilterVersion() {
return filterVersion;
}
public Set<FilterState> getFilterStates() {
return filterStates;
}
}
In the database, I have one FilterVersionChange node with several FilterStates nodes attached to it via 'CONTAINS' and 'ADDED' relationships. Assume that I have the id of that FilterVersionChange node and I want to get the node by calling findOne(id). But, what I get from it is null value for the filterStates variable.
As I understand from the documentation, findOne should retrieve the depth of 1 by default. But I really have no idea why I get the value of null with the filterStates variable.
Thank you in advance and your suggestion would be really appreciated!
EDIT
This is the function where the insertion code is.
public FilterVersionChange createNewFilterVersionChange(String projectName,
String filterVersionName,
String filterVersionChangeDescription,
Set<FilterState> filterStates)
{
Long filterVersionNodeId = filterVersionRepository.findFilterVersionByName(projectName, filterVersionName);
if(filterVersionNodeId != null)
{
FilterVersion newFilterVersion = filterVersionRepository.findOne(filterVersionNodeId, 2);
HashMap<String, Filter> filterHashMap = new HashMap<String, Filter>();
Iterable<Filter> filters = filterRepository.findAll();
if(filters.iterator().hasNext())
{
for(Filter filter : filters)
{
filterHashMap.put(filter.getMatchingString(), filter);
}
}
for(FilterState filterState : filterStates)
{
Filter filter;
if(filterHashMap.isEmpty() == false)
{
filter = filterHashMap.get(filterState.getMatchingString());
}
else
{
filter = new Filter(filterState.getMatchingString(), filterState.getMatchingType());
filter.belongsTo(newFilterVersion.getProject());
}
filterState.stateOf(filter);
}
Date now = new Date();
FilterVersionChange filterVersionChange = new FilterVersionChange();
filterVersionChange.setDescription(filterVersionChangeDescription);
filterVersionChange.setCreationDate(now.getTime());
filterVersionChange.contains(filterStates);
filterVersionChange.added(filterStates);
filterVersionChange.trackedIn(newFilterVersion);
TimeTreeSecond timeInstantNode = timeTreeService.getFilterTimeInstantNode(projectName, now.getTime());
filterVersionChange.createdOn(timeInstantNode);
FilterVersionChange addedFilterVersionChange = filterVersionChangeRepository.save(filterVersionChange);
return addedFilterVersionChange;
}
else
{
return null;
}
}
Here is the FilterState class
#NodeEntity
public class FilterState {
#GraphId
private Long id;
private String matchingString;
private String matchingType;
public FilterState() {
}
public FilterState(String matchingString, String matchingType) {
this.matchingString = matchingString;
setMatchingType(matchingType);
}
#Relationship(type="STATE_OF", direction = Relationship.OUTGOING)
private Filter filter;
#Relationship(type="PART_OF", direction = Relationship.OUTGOING)
private CodeUnit codeUnit;
#Relationship(type="CONTAINS", direction = Relationship.INCOMING)
private FilterVersionChange containedInFilterVersionChange;
#Relationship(type="ADDED", direction = Relationship.INCOMING)
private FilterVersionChange addedInFilterVersionChange;
public void setMatchingString(String matchingString) {
this.matchingString = matchingString;
}
public void setMatchingType(String matchingType) {
String type = null;
if(matchingType.equalsIgnoreCase("RegexFilter"))
{
type = "RegexFilter";
}
else if(matchingType.equalsIgnoreCase("ClassFilter"))
{
type = "ClassFilter";
}
this.matchingType = type;
}
public void stateOf(Filter filter) {
this.filter = filter;
}
public void partOf(CodeUnit codeUnit) {
this.codeUnit = codeUnit;
}
public String getMatchingString() {
return matchingString;
}
public String getMatchingType() {
return matchingType;
}
public Filter getFilter() {
return filter;
}
public Long getId() {
return id;
}
public void addedIn(FilterVersionChange addedInFilterVersionChange) {
this.addedInFilterVersionChange = addedInFilterVersionChange;
}
public FilterVersionChange getContainedInFilterVersionChange() {
return containedInFilterVersionChange;
}
}
and here is the gradle file
def RMQVersion = "3.3.4"
def GSONVersion = "2.3.1"
def Neo4jVersion = "2.2.1"
def Neo4jTimeTreeVersion = "2.2.1.30.21"
def SpringVersion = "4.1.6.RELEASE"
def SDNVersion = "4.0.0.BUILD-SNAPSHOT"
def JunitVersion = "4.12"
apply plugin: 'java'
apply plugin: 'maven'
sourceCompatibility = 1.5
version = '1.0'
repositories {
mavenCentral()
maven {
url("http://maven.springframework.org/milestone")
}
maven {
url("http://repo.spring.io/libs-snapshot")
}
}
dependencies {
compile "org.springframework.data:spring-data-neo4j:${SDNVersion}"
compile "org.neo4j:neo4j:${Neo4jVersion}"
compile "com.graphaware.neo4j:timetree:${Neo4jTimeTreeVersion}"
compile "com.rabbitmq:amqp-client:${RMQVersion}"
compile "com.google.code.gson:gson:${GSONVersion}"
testCompile group: 'org.springframework.data', name: 'spring-data-neo4j', version: SDNVersion, classifier: 'tests'
testCompile group: 'org.springframework', name: 'spring-test', version: SpringVersion
testCompile group: 'junit', name: 'junit', version: JunitVersion
}
This issue has been fixed post 4.0.0M1, please use the latest build snapshot, thanks.

Resources