No serializer found for class com.atlassian.jira.issue.security.IssueSecurityLevelImpl error - jira

I am creating a Jira software server plugin for v7.13.0. I am creating an API to get all the issue security levels of a user.
My code for the same is as follows:
UserManager userManager = ComponentAccessor.getComponentOfType(UserManager.class);
#GET
#Produces({MediaType.APPLICATION_JSON})
#Path("user-security-levels")
public Response getUserSecurityLevels(#QueryParam("user") String user) {
log.error("entering getSecurityLevels function");
log.error("name of the user: " + user);
ApplicationUser targetUser = userManager.getUserByName(user);
log.error("value of targetUser: " + targetUser);
IssueSecurityLevelManager issueSecurityLevelManager = ComponentAccessor.getComponentOfType(IssueSecurityLevelManager.class);
Collection<IssueSecurityLevel> securityLevelsOfUser = issueSecurityLevelManager.getAllSecurityLevelsForUser(targetUser);
log.error("user security levels: " + securityLevelsOfUser);
return securityLevelsOfUser == null ? Response.status(Response.Status.NOT_FOUND)
.build() : Response.ok(securityLevelsOfUser).build();
}
But, this code is not working and is giving the following error:
2022-10-27 16:00:35,623 http-nio-8080-exec-13 ERROR [o.a.c.c.C.[.[localhost].[/].[default]] Servlet.service() for servlet [default] in context with path [] threw exception
org.codehaus.jackson.map.JsonMappingException: No serializer found for class com.atlassian.jira.issue.security.IssueSecurityLevelImpl and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS) ) (through reference chain: java.util.HashSet[0])

Related

Google Spreadsheets api: Error o.s.b.w.servlet.support.ErrorPageFilter : Forwarding to error page from request due to exception Address already in us

I have write the code get google could credential by below code for read google spreadsheet data:
public static Credential getCredentials(final NetHttpTransport HTTP_TRANSPORT, String spreadsheetCredentialURL)
throws IOException {
// Load client secrets.
InputStream in = new URL( awsBucketUrl+spreadsheetCredentialURL).openStream();
if (in == null) {
throw new FileNotFoundException("Resource not found: " + awsBucketUrl+spreadsheetCredentialURL);
}
GoogleClientSecrets clientSecrets =
GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));
in.close();
// Build flow and trigger user authorization request.
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
.setDataStoreFactory(new FileDataStoreFactory(new java.io.File(TOKENS_DIRECTORY_PATH)))
.setAccessType("offline")
.build();
LocalServerReceiver receiver = new LocalServerReceiver.Builder().setPort(8099).build();
return new AuthorizationCodeInstalledApp(flow, receiver).authorize("user");
}
Now, when i am deploying this code to my develop environment on docker serve it is givin me below error:
2022-09-07 12:52:40.461 ERROR 1 --- [nio-8080-exec-6] o.s.b.w.servlet.support.ErrorPageFilter : Forwarding to error page from request [/google/spreadsheets-tabs/1Klc6IICWEiq-Oi9YEEbRxbqtEylJ4Ti0UtKNkieYo8Q] due to exception [Address already in us].
The same code is working on my local laptop environment.
anyone has any idea?

asp net core - file download results is FileNotFoundException

I'm trying to do a simple file download, but it results with FileNotFoundException.
The code in the controller:
public FileResult DownloadFile()
{
var fileName = "1.pdf";
var filePath = env.WebRootPath + "\\" + fileName;
var fileExists = System.IO.File.Exists(filePath);
return File(filePath, "application/pdf", fileName);
}
(Debugging the variable fileExists shows that it's set to true.)
The code in the view:
#Html.ActionLink("Download", "DownloadFile")
Messages from the log:
2017-03-12 09:28:45 [INF] Executing action method "Team.Controllers.ModulesExController.DownloadFile (Team)" with arguments (null) - ModelState is Valid
2017-03-12 09:28:45 [DBG] Executed action method "Team.Controllers.ModulesExController.DownloadFile (Team)", returned result "Microsoft.AspNetCore.Mvc.VirtualFileResult".
2017-03-12 09:28:45 [INF] Executing FileResult, sending file as "1.pdf"
2017-03-12 09:28:45 [INF] Executed action "Team.Controllers.ModulesExController.DownloadFile (Team)" in 0.8238ms
2017-03-12 09:28:45 [DBG] System.IO.FileNotFoundException occurred, checking if Entity Framework recorded this exception as resulting from a failed database operation.
2017-03-12 09:28:45 [DBG] Entity Framework did not record any exceptions due to failed database operations. This means the current exception is not a failed Entity Framework database operation, or the current exception occurred from a DbContext that was not obtained from request services.
2017-03-12 09:28:45 [ERR] An unhandled exception has occurred while executing the request
System.IO.FileNotFoundException: Could not find file: D:\Projekti\Team\src\Team\wwwroot\1.pdf
If I paste the link in the error message in the browser, I can open the file.
In ASP.NET Core 2.0 you can use a PhysicalFile as the return type if you have a file path.
public FileResult DownloadFile() {
var fileName = "1.pdf";
var filePath = env.WebRootPath + "\\" + fileName;
var fileExists = System.IO.File.Exists(filePath);
return PhysicalFile(filePath, "application/pdf", fileName);
}
Controller.File() is expecting a virtual path, not an absolute path.
See https://learn.microsoft.com/en-us/aspnet/core/api/microsoft.aspnetcore.mvc.controllerbase#Microsoft_AspNetCore_Mvc_ControllerBase_File_System_String_System_String_System_String_
If you want to use an absolute path, pass in a stream:
public FileResult DownloadFile()
{
var fileName = "1.pdf";
var filePath = env.WebRootPath + "\\" + fileName;
var fileExists = System.IO.File.Exists(filePath);
var fs = System.IO.File.OpenRead(filePath);
return File(fs, "application/pdf", fileName);
}
This code downloads a pdf file named 'abc123.pdf' that you've put in your MVC 5 Resources folder. It took me several hours of stitching together other stack overflow articles to make it work. Most of the solutions I've seen don't tell you how to download the physical file. Most solutions don't mention how to deal with the resource file, which I find very useful.
public IActionResult DownloadBlankACH()
{
return DownloadDocumentLikeThis("abc123");
}
private IActionResult DownloadDocumentLikeThis(string likeThis)
{
ResourceManager MyResourceClass = new ResourceManager(typeof(Resources));
ResourceSet resourceSet = MyResourceClass.GetResourceSet(CultureInfo.CurrentUICulture, true, true);
foreach (DictionaryEntry entry in resourceSet)
{
string resourceKey = entry.Key.ToString();
object resource = entry.Value;
if (resourceKey.Contains(likeThis))
{
string RunningPath = AppDomain.CurrentDomain.BaseDirectory;
string FileName = string.Format("{0}Properties\\" + resourceKey + ".pdf", Path.GetFullPath(Path.Combine(RunningPath, #"..\..\..\")));
return PhysicalFile(System.IO.Path.GetFullPath(FileName), "application/pdf", System.IO.Path.GetFileName(FileName));
}
}
return View();
}

exception inside of OnException

I created a custom attribute, inheriting from HandleErrorAttribute:
public class CustomHandleErrorAttribute : HandleErrorAttribute
{
public override void OnException(ExceptionContext filterContext)
{
try
{
Utility.LogAndNotifyOfError(filterContext.Exception, null, true);
}
catch(Exception ex)
{
filterContext.Exception = ex;
}
}
}
, and then registered with:
filters.Add(new CustomHandleErrorAttribute());
This has always worked as intended. However a common problem with my log method is that it uses a custom event log source when writing to the event log, which the app pool account typically doesn't have the permissions to create. Creating the event log source is a simple powershell script, however I wanted to actually include that tidbit in the error:
try
{
log.WriteEntry(error, EventLogEntryType.Error);
}
catch(SecurityException ex1)
{
throw new ErrorHandlerException($"The event log could not be written to due to a SecurityExcption. The likely issue is that the '{eventLogSource}' does not already exist. Please run the following powershell command:\r\n"
+ $"New - EventLog - LogName Application - Source {eventLogSource}", ex1);
}
The problem is that the catch in the OnException is never hit. When debugging, the custom error I throw from LogAndNotifyOfError instead triggers a second call to OnException, and the detail of my ErrorHandlerException is never seen. I want the asp.net error page that comes up to be with my custom error detail rather than the SecurityException that was originally raised.
You can even see the surrounding try in the displayed error:
Edit: Entire log method listed:
public static void LogAndNotifyOfError(Exception ex, String extraInfo, Boolean sendEmail)
{
//if the error handler itself faulted...
if (ex is ErrorHandlerException)
return;
string eventLogName = "Application";
string eventLogSource = "MySourceName";
String error = ex.ToString();
if (error.Length > 28000)
error.Substring(0, 28000);//event log is limited to 32k
error += "\r\n\r\nAdditional Information: \r\n"
+ "Machine Name: " + Environment.MachineName + "\r\n"
+ "Logged in user:" + App.CurrentSecurityContext.CurrentUser?.UserId + "\r\n"
+ extraInfo + "\r\n";
EventLog log = new EventLog(eventLogName);
log.Source = eventLogSource;
try
{
log.WriteEntry(error, EventLogEntryType.Error);
}
catch(SecurityException ex1)
{//this doesn't work - for some reason, OnError still reports the original error.
throw new ErrorHandlerException($"The event log could not be written to due to a SecurityExcption. The likely issue is that the '{eventLogSource}' does not already exist. Please run the following powershell command:\r\n"
+ $"New - EventLog - LogName Application - Source {eventLogSource}", ex1);
}
//if the email-to field has been set...
if (!String.IsNullOrEmpty(App.Config.General.ErrorHandlerSendToAddresses) && sendEmail)
{
//...then send the email
MailMessage email = new MailMessage();
email.To.Add(App.Config.General.ErrorHandlerSendToAddresses);
email.IsBodyHtml = false;
email.Subject = String.Format("Error in {0}", eventLogSource);
email.Body = email.Subject + "\r\n\r\n"
//+ "Note: This error may be occuring continuously, but this email is only sent once per hour, per url, in order to avoid filling your mailbox. Please check the event log for reoccurances and variations of this error.\r\n\r\n"
+ "The error description is as follows: \r\n\r\n"
+ error + "\r\n\r\n";
SmtpClient smtp = new SmtpClient();
smtp.Send(email);
}
}
I figured it out (sort of). It would appear that when the newly throw exception has an inner exception, it is only displaying that inner exception. It does not matter what the type is on the outer or inner exception.

Result.to(NodeEntity.class): stack overflow error

while trying to retrieve my nodes back to my domain objects I'm getting this strange error:
Exception in thread "main" java.lang.StackOverflowError
at sun.nio.ch.NativeThreadSet.remove(NativeThreadSet.java:76)
at sun.nio.ch.FileChannelImpl.read(FileChannelImpl.java:678)
at org.neo4j.kernel.impl.nioneo.store.PersistenceRow.readFullWindow(PersistenceRow.java:158)
at org.neo4j.kernel.impl.nioneo.store.PersistenceRow$State$1.transition(PersistenceRow.java:115)
at org.neo4j.kernel.impl.nioneo.store.PersistenceRow.lock(PersistenceRow.java:59)
at org.neo4j.kernel.impl.nioneo.store.PersistenceWindowPool.acquire(PersistenceWindowPool.java:193)
at org.neo4j.kernel.impl.nioneo.store.CommonAbstractStore.acquireWindow(CommonAbstractStore.java:520)
at org.neo4j.kernel.impl.nioneo.store.NodeStore.getRecord(NodeStore.java:76)
at org.neo4j.kernel.impl.nioneo.xa.ReadTransaction.nodeLoadProperties(ReadTransaction.java:239)
at org.neo4j.kernel.impl.persistence.PersistenceManager.loadNodeProperties(PersistenceManager.java:113)
at org.neo4j.kernel.impl.core.NodeManager.loadProperties(NodeManager.java:682)
at org.neo4j.kernel.impl.core.NodeImpl.loadProperties(NodeImpl.java:132)
at org.neo4j.kernel.impl.core.Primitive.ensureFullProperties(Primitive.java:584)
at org.neo4j.kernel.impl.core.Primitive.ensureFullProperties(Primitive.java:567)
at org.neo4j.kernel.impl.core.Primitive.getProperty(Primitive.java:153)
at org.neo4j.kernel.impl.core.NodeImpl.getProperty(NodeImpl.java:51)
at org.neo4j.kernel.impl.core.NodeProxy.getProperty(NodeProxy.java:155)
at org.springframework.data.neo4j.support.typerepresentation.AbstractIndexingTypeRepresentationStrategy.readAliasFrom(AbstractIndexingTypeRepresentationStrategy.java:106)
at org.springframework.data.neo4j.support.mapping.TRSTypeAliasAccessor.readAliasFrom(TRSTypeAliasAccessor.java:36)
at org.springframework.data.neo4j.support.mapping.TRSTypeAliasAccessor.readAliasFrom(TRSTypeAliasAccessor.java:26)
at org.springframework.data.convert.DefaultTypeMapper.readType(DefaultTypeMapper.java:96)
at org.springframework.data.convert.DefaultTypeMapper.getDefaultedTypeToBeUsed(DefaultTypeMapper.java:144)
at org.springframework.data.convert.DefaultTypeMapper.readType(DefaultTypeMapper.java:121)
at org.springframework.data.neo4j.support.mapping.Neo4jEntityConverterImpl.read(Neo4jEntityConverterImpl.java:76)
at org.springframework.data.neo4j.support.mapping.Neo4jEntityPersister$CachedConverter.read(Neo4jEntityPersister.java:170)
at org.springframework.data.neo4j.support.mapping.Neo4jEntityPersister.createEntityFromState(Neo4jEntityPersister.java:189)
at org.springframework.data.neo4j.support.Neo4jTemplate.createEntityFromState(Neo4jTemplate.java:180)
at org.springframework.data.neo4j.fieldaccess.RelationshipNodeFieldAccessorFactory$RelationshipNodeFieldAccessor.getValue(RelationshipNodeFieldAccessorFactory.java:102)
at org.springframework.data.neo4j.fieldaccess.DefaultEntityState.getValue(DefaultEntityState.java:97)
at org.springframework.data.neo4j.support.mapping.SourceStateTransmitter.copyEntityStatePropertyValue(SourceStateTransmitter.java:90)
at org.springframework.data.neo4j.support.mapping.SourceStateTransmitter.access$000(SourceStateTransmitter.java:40)
at org.springframework.data.neo4j.support.mapping.SourceStateTransmitter$2.doWithAssociation(SourceStateTransmitter.java:61)
at org.springframework.data.mapping.model.BasicPersistentEntity.doWithAssociations(BasicPersistentEntity.java:207)
at org.springframework.data.neo4j.support.mapping.SourceStateTransmitter.copyPropertiesFrom(SourceStateTransmitter.java:57)
at org.springframework.data.neo4j.support.mapping.Neo4jEntityConverterImpl.loadEntity(Neo4jEntityConverterImpl.java:100)
at org.springframework.data.neo4j.support.mapping.Neo4jEntityConverterImpl.read(Neo4jEntityConverterImpl.java:92)
at org.springframework.data.neo4j.support.mapping.Neo4jEntityPersister$CachedConverter.read(Neo4jEntityPersister.java:170)
at org.springframework.data.neo4j.support.mapping.Neo4jEntityPersister.createEntityFromState(Neo4jEntityPersister.java:192)
at org.springframework.data.neo4j.support.Neo4jTemplate.createEntityFromState(Neo4jTemplate.java:180)
at org.springframework.data.neo4j.fieldaccess.GraphBackedEntityIterableWrapper.underlyingObjectToObject(GraphBackedEntityIterableWrapper.java:41)
at org.springframework.data.neo4j.fieldaccess.GraphBackedEntityIterableWrapper.underlyingObjectToObject(GraphBackedEntityIterableWrapper.java:27)
at org.neo4j.helpers.collection.IterableWrapper$MyIteratorWrapper.underlyingObjectToObject(IterableWrapper.java:57)
at org.neo4j.helpers.collection.IteratorWrapper.next(IteratorWrapper.java:47)
at org.neo4j.helpers.collection.IteratorUtil.addToCollection(IteratorUtil.java:324)
at org.neo4j.helpers.collection.IteratorUtil.addToCollection(IteratorUtil.java:341)
at org.springframework.data.neo4j.fieldaccess.RelatedToViaCollectionFieldAccessorFactory$RelatedToViaCollectionFieldAccessor.getValue(RelatedToViaCollectionFieldAccessorFactory.java:122)
at org.springframework.data.neo4j.fieldaccess.DefaultEntityState.getValue(DefaultEntityState.java:97)
For example, this is my cypher query which tries to get a user node entity:
public MyUser getUserByUserId(String userId){
Long t1 = System.currentTimeMillis();
if(existsUserByUserId(userId)){
HashedMap params = new HashedMap();
params.put("userId", userId);
String query = "START x=node:searchByUserId(userId = {userId})" +
" RETURN x";
Result<Map<String,Object>> result = neo4jTemplate.query(query, params);
MyUser user = result.to(MyUser.class).single();
Long t2 = System.currentTimeMillis();
logger.info("get user by user id exec time: " + (t2-t1) + " ms");
return user;
}
Long t2 = System.currentTimeMillis();
logger.info("get user by id exec time: " + (t2-t1) + " ms");
return null;
}
where searchByUserId is a node index and existsUserByUserId is a helper method which checks whether the the specified user exists or not. The problem is that when I try to call the result.to() method I get this error randomly. With randomly I mean that I'm not getting this error always. To be more concrete, I inserted all my node/relationships using the native Neo4j Java API and now I'm trying to retrieve these objects with Spring Data Neo4j (repository approach). This is how I'm inserting my node entities:
public Node createAndIndexMyUserNode(MyUser user){
Map<String,Object> properties = new HashMap<String, Object>();
properties.put("userId", user.getUserId());
properties.put("baseID" , user.getBaseID());
properties.put("__type__", MyUser.class.getName());
properties.put("canUpdate", false);
Node node = neo4jTemplate.getOrCreateNode("searchByUserId", "userId", user.getTwitterId(), properties);
return node;
}
This is probably the problem but I don't know how I could solve it. I suspect that bad database shutdowns or relationships creation (afterwards) could be also one reason, but I'm not sure though.
This is the reason why I'm inserting "manually" all nodes instead of using the repository save method. Any suggestions or ideas?
Thank you all in advance!

Setting Calendar property on Domain Object

I came accross an interesting problem in my code today.
I am using Grails 2.2.0.
Here is the code
def user = lookupUserClass().get(params.id)
log.info "[update]user.subscriptionExpiryDate1: " + user.subscriptionExpiryDate
user.subscriptionExpiryDate = Calendar.getInstance();
log.info "[update]user.subscriptionExpiryDate2: " + user.subscriptionExpiryDate
if (user.subscriptionExpiryDate instanceof Calendar ) {
log.error "***** Is A Calendar Instance ***"
} else if (user.subscriptionExpiryDate instanceof String ) {
log.error "***** Is A String Instance ***"
} else {
log.error "***** Is Something else ***"
}
if (!user.save()) {
log.error "[update]Error occured saving user. Errors are: "
user.errors.each { err -> log.error err; }
render view: 'edit', model: buildUserModel(user)
return
} else {
log.info "[update]Successfully saved user"
}
subscriptionExpiryDate is a calendar property in my User object.
When I perform the save I get the following error
Failed to convert property value of type 'java.lang.String' to required type 'java.util.Calendar' for property 'subscriptionExpiryDate'; nested exception is java.lang.IllegalArgumentException: Could not parse date: Unparseable date: 05/03/2013
Could anyone please explain why I would be seeing this error for the above code as nothing is standing out
This question has been resolved as per Andrew's suggestion:
Are you doing any data binding on the user object before the code you pasted? If you are binding to the subscriptionExpiryDate property, you will need a PropertyEditor to do the String -> Calendar conversion

Resources