AOP Performance issue - aspectj

Below code is taking more time decreasing overall application performance.
#Aspect
#Component
public class LoggingHandler {
/**
* Logger initialization.
*
*/
private final Logger logger = LoggerFactory.getLogger(LoggingHandler.class);
/**
* Around advise for SlingAdapterImpl.
* #param pjp joinPoint
* #return response
* #throws Throwable exception
*/
#Around("execution(* com.abcd.oicp.storage.client.impl.SlingAdapterImpl.*(..))")
public Object logAroundAllMethods(ProceedingJoinPoint pjp) throws Throwable {
long startTime = Calendar.getInstance().getTimeInMillis();
Object obj = null;
try {
obj = pjp.proceed();
} finally {
logger.info("Method={} Time taken={} micro secs", pjp.getSignature().getName(),
(TimeUnit.MILLISECONDS.toMicros(Calendar.getInstance().getTimeInMillis() - startTime)));
}
return obj;
}
}
In JMeter, It is consuming ~1.5sec. WHY?
Is Time converting from milli seconds to micro seconds a
performance issue.
thanks in advance.

use System.nanoTime() or System.currentTimeMillis() instead of Calendar.getInstance().getTimeInMillis()

Related

Symfony 3.0.4 Circular reference detected during serialization with FOSRestBundle

I'm using FOSRestBundle in a Symfony project. When it I try to handle a view, it fails during the serialization of my data with the Symfony serializer as well as with the JMSSerializer.
This is the method rendering the response:
DefaultController.php
$em = $this->getDoctrine()->getManager('magellan');
$qb = $em->createQueryBuilder();
$query = $qb->select('h')
->from('DataBundle:Holding', 'h')
->where($qb->expr()->eq('h.id', ':holding_id'))
->setParameter('holding_id', $holding_id)
->getQuery();
$results = $query->getResult();
$view = $this->view($results, 200);
// Everything's ok up to this point
return $this->handleview($view);
And these are my entities:
Holding.php
class Holding
{
...
/**
* #ORM\OneToMany(targetEntity="Subsidiary", mappedBy="holding")
*/
private $subsidiaries;
}
Subsidiary.php
class Subsidiary
{
...
/**
* #ORM\ManyToOne(targetEntity="Holding", inversedBy="subsidiaries")
* #ORM\JoinColumn(name="id_holding", referencedColumnName="id_holding")
*/
private $holding;
/**
* #ORM\OneToMany(targetEntity="Brand", mappedBy="subsidiary")
*/
private $brands;
}
Brand.php
class Brand
{
...
/**
* #ORM\ManyToOne(targetEntity="Subsidiary", inversedBy="brands")
* #ORM\JoinColumn(name="id_subsidiary", referencedColumnName="id_subsidiary")
*/
private $subsidiary;
/**
* #ORM\OneToMany(targetEntity="Product", mappedBy="brand")
*/
private $products;
}
Product.php
class Product
{
...
/**
* #ORM\ManyToOne(targetEntity="Brand", inversedBy="products")
* #ORM\JoinColumn(name="id_brand", referencedColumnName="id_brand")
*/
private $brand;
/**
* #ORM\ManyToOne(targetEntity="Sector", inversedBy="products")
* #ORM\JoinColumn(name="id_sector", referencedColumnName="id_sector")
*/
private $sector;
/**
* #ORM\OneToMany(targetEntity="Commercial", mappedBy="product")
*/
private $commercials;
}
Commercial.php
class Commercial
{
...
/**
* #ORM\ManyToOne(targetEntity="Product", inversedBy="commercials")
* #ORM\JoinColumn(name="id_product", referencedColumnName="id_product")
*/
private $product;
/**
* #ORM\OneToMany(targetEntity="CommercialReport", mappedBy="commercial")
*/
private $reports;
CommercialReport.php
class CommercialReport
{
...
/**
* #ORM\ManyToOne(targetEntity="Commercial", inversedBy="reports")
* #ORM\JoinColumn(name="id_commercial", referencedColumnName="id_commercial")
*/
private $commercial;
}
Sector.php
class Sector
{
...
/**
* #ORM\OneToMany(targetEntity="Product", mappedBy="sector")
*/
private $products;
}
When using the default symfony serializer, I get the following error:
"message":"A circular reference has been detected (configured limit:
1).","class":"Symfony\Component\Serializer\Exception\CircularReferenceException"
And when using the JMSSerializer, when I go to the corresponding page of the controller, the page just never finishes loading. At the same time in the dev.log file new Doctrine.debug entries with requests to my DB are added every second.
$normalizers->setCircularReferenceHandler(function ($object) {
return $object->getId();
});
Just add it after you make the instance if your objectNormalizer()
it worl perfectly for me
If you use FosRestBundle, you can use the GROUPS for the serializer. There is an annotation given by FosRestBundle : #FOS\RestBundle\Controller\Annotations\View(serializerGroups={"user"})
Your group can exclude the circular property.
Another idea you can do this. In your app/config/services.yml
circular_reference_handler:
public: false
class: callback
factory: [AppBundle\Serializer\CircularHandlerFactory, getId]
serializer.normalizer.object:
class: Symfony\Component\Serializer\Normalizer\ObjectNormalizer
arguments: ["#serializer.mapping.class_metadata_factory", null, "#serializer.property_accessor"]
public: false
tags: [serializer.normalizer]
calls:
- method: setCircularReferenceLimit
arguments: [1]
- method: setCircularReferenceHandler
arguments: ["#circular_reference_handler"]
The factory can be like this:
namespace AppBundle\Serializer;
class CircularHandlerFactory
{
/**
* #return \Closure
*/
public static function getId()
{
return function ($object) {
return $object->getId();
};
}
}

Error with to string method my code is below

Trying to code this and its driving me crazy i know its something simple
my question is on the toString method i am getting compile error Cannot find symbol varible getNext also if you can check the rest of the methods for accuracy that would be greatly appreciated
public class Turner_A06Q2
{
/**
* Program entry point for queue testing.
* #param args Argument list.
*/
public static void main(String[] args)
{
LinkedQueue<Integer> queue = new LinkedQueue<Integer>();
System.out.println("QUEUE TESTING");
queue.enqueue(3);
queue.enqueue(7);
queue.enqueue(4);
System.out.println(queue.first());
queue.dequeue();
queue.enqueue(9);
queue.enqueue(8);
System.out.println(queue.first());
System.out.println(queue.dequeue());
System.out.println(queue.first());
System.out.println("The size of the queue is: " + queue.size());
System.out.println("The queue contains:\n" +queue.toString());
}
/**
* LinkedQueue represents a linked implementation of a queue.
*
* #author Java Foundations
* #version 4.0
*/
public static class LinkedQueue<T> implements QueueADT<T>
{
private int count;
private LinearNode<T> head, tail; //front, back
/**
* Creates an empty queue.
*/
public LinkedQueue()
{
count = 0;
head = tail = null;
}
/**
* Adds the specified element to the tail of this queue.
* #param element the element to be added to the tail of the queue
*/
public void enqueue(T element)
{
LinearNode<T> node = new LinearNode<T>(element);
if (isEmpty())
head = node;
else
tail.setNext(node);
tail = node;
count++;
}
/**
* Removes the element at the head of this queue and returns a
* reference to it.
* #return the element at the head of this queue
* #throws EmptyCollectionException if the queue is empty
*/
public T dequeue() throws EmptyCollectionException
{
if (isEmpty())
throw new EmptyCollectionException("queue");
T result = head.getElement();
head = head.getNext();
count--;
if (isEmpty())
tail = null;
return result;
}
/**
* Returns a reference to the element at the head of this queue.
* The element is not removed from the queue.
* #return a reference to the first element in this queue
* #throws EmptyCollectionsException if the queue is empty
*/
public T first() throws EmptyCollectionException
{
return head.getElement();
return null;
}
/**
* Returns true if this queue is empty and false otherwise.
* #return true if this queue is empty
*/
public boolean isEmpty()
{
return count==0;
}
/**
* Returns the number of elements currently in this queue.
* #return the number of elements in the queue
*/
public int size()
{
return count;
return 0;
}
/**
* Returns a string representation of this queue. The front element
* occurs first, and each element is separated by a space. If the
* queue is empty, returns "empty".
* #return the string representation of the queue
*/
public String toString()
{
if (isEmpty()) {
return " ";
}
StringBuilder sb = new StringBuilder();
LinearNode<T> next = head.getNext;
while(next != null){
sb.append(" ").append(next.getElement());
next = next.getNext();
}
return sb.toString();
}
}
}
it is a queue and you are trying to print the contents of a queue without actually iterating over it hence, the error.
Try something like this:
for (E element : queue)
{
System.out.println(queue.get(i).toString());
}

NullPointerException when tyring to create table for mapped-superclass

I traced it down to the getDatastoreClass returning a null datastore class to the createPerImplementationColumnsForReferenceField.
I have tried both the 3.1.1 and now using 3.2.0-m4 release hoping that would fix my problem.
RDBMSStoreManager#getDatastoreClass(String className, ClassLoaderResolver clr);
It is returning a null datastore class to the
ReferenceMapping#createPerImplementationColumnsForReferenceField(boolean pk, boolean nullable, boolean serialised, boolean embedded, int fieldRole, ColumnMetaData[] columnMetaData, ClassLoaderResolver clr)
I am using the orm to annotate a mapped-superclass and this mapped-superclass does not have a table definition and both of my mapped-superclass throwing this exception.
499170 [http-bio-8080-exec-8] DEBUG DataNucleus.Datastore.Schema - Field [com.hp.vf.server.domain.AlertDefinition.isPublic] -> Column(s) ["ALERTDEFINITION"."ISPUBLIC"] using mapping of type "org.datanucleus.store.rdbms.mapping.java.BooleanMapping" (org.datanucleus.store.rdbms.mapping.datastore.SmallIntRDBMSMapping)
551964 [http-bio-8080-exec-8] DEBUG DataNucleus.Persistence - Managing Persistence of Class : com.hp.vf.analytics.shared.metric.Metric [Table : (none), InheritanceStrategy : subclass-table]
561964 [http-bio-8080-exec-8] ERROR DataNucleus.Datastore.Schema - An exception was thrown while adding/validating class(es) : null
java.lang.NullPointerException
at org.datanucleus.store.rdbms.mapping.java.ReferenceMapping.createPerImplementationColumnsForReferenceField(ReferenceMapping.java:452)
at org.datanucleus.store.rdbms.mapping.java.ReferenceMapping.prepareDatastoreMapping(ReferenceMapping.java:214)
at org.datanucleus.store.rdbms.mapping.java.ReferenceMapping.initialize(ReferenceMapping.java:110)
at org.datanucleus.store.rdbms.mapping.java.InterfaceMapping.initialize(InterfaceMapping.java:54)
In the Reference mapping, dc is null when trying to execute getIdMapping(), I have verified this in the debugger.
try
{
DatastoreClass dc = storeMgr.getDatastoreClass(implClass.getName(), clr);
m = dc.getIdMapping(); // DC is null
}
catch (NoTableManagedException ex)
{
// TODO Localise this message
throw new NucleusUserException("Cannot define columns for " + mmd.getFullFieldName() +
" due to " + ex.getMessage(), ex);
}
Here is the problematic class file.
public abstract class Metric implements IMetric {
/**
* Serialization ID
*/
private static final long serialVersionUID = 3806479436166940035L;
private Long id;
/**
* The name of the metric, this is not mandatory we have some metrics that
* may come back without names.
*/
protected String name;
/**
* This is an optional metric value that can be set by the script in order
* to add context to the execution of the metric.
*/
protected String context;
/**
* The list of violations associated with this metric.
*/
protected List<Violation> violations = null;
public Metric() {
violations = new ArrayList<Violation>();
}
/**
* Constructor that takes the name of the object and the value that it
* represents.
*
* #param name
* #param value
*/
public Metric(String name) {
this();
this.name = name;
}
/* (non-Javadoc)
* #see com.hp.vf.taskengine.shared.metric.IMetric#getName()
*/
#Override
public String getName() {
return name;
}
/* (non-Javadoc)
* #see com.hp.vf.taskengine.shared.metric.IMetric#setName(java.lang.String)
*/
#Override
public void setName(String name) {
this.name = name;
}
/**
* This is the context that represents the metric. This could have come from
* R and would be a Key:Value; pair of values used to calculate the value.
* For example if a metric was calculated for a product in houston for ISS
* the context may look like "ProdNum:1234;Factory:Houston;BUnit:ISS". This
* context is useful when chaining together tasks.
*
* #return String context used when chaining tasks together.
*/
public String getContext() {
return context;
}
/* (non-Javadoc)
* #see com.hp.vf.taskengine.shared.metric.IMetric#toString()
*/
public String toString() {
String debugString = "";
debugString += "Metric: " + name;
return debugString;
}
/* (non-Javadoc)
* #see com.hp.vf.taskengine.shared.metric.IMetric#hasMetricViolations()
*/
#Override
public boolean hasMetricViolations() {
return (violations != null && violations.size() > 0) ? true : false;
}
/* (non-Javadoc)
* #see com.hp.vf.taskengine.shared.metric.IMetric#getViolations()
*/
#Override
public List<IViolation> getViolations() {
return violations;
}
/* (non-Javadoc)
* #see com.hp.vf.taskengine.shared.metric.IMetric#setViolations(java.util.List)
*/
#Override
public void setViolations(List<IViolation> violations) {
this.violations = violations;
}
#Override
public Long getId() {
return id;
}
}
Here is an excert from my orm.xml file
<access>FIELD</access>
<mapped-superclass class="com.hp.vf.analytics.shared.metric.Metric" access="FIELD">
<attributes>
<basic name="name" />
<basic name="context" />
<one-to-many name="violations">
<cascade>
<cascade-all />
</cascade>
</one-to-many>
</attributes>
</mapped-superclass>
Am I doing something wrong or is this a bug?
I was able to resolve the problem using the tips from Datanucleus. I had multiple problems
Problems
The most obvious and silly on my part
If you have an one-to-many or one-to-one that uses an interface you must specify the target-entity.
/**
* The list of violations associated with this metric.
*/
protected List<IViolation> violations = null;
...
<one-to-many name="violations"
target-entity="com.vf.analytics.shared.metric.Violation">
<cascade>
<cascade-all />
</cascade>
</one-to-many>
Don't use generics, the jpa spec does not suppport them
Not sure if datanucleus supports generics but it but probably not recommended.
public MetricNumber< T extends Number> extends Metric implements IMetric {
T value;
}
If you extend an entity that is not annotated make sure that you add it to your orm.xml
I wasn't testing some of the objects so I assumed that datanucleus would ignore them but this appears not to be the case. I had extended third party classes that were not annotated but had not yet added them to the orm.xml, this was also causing null the null pointer exceptions I was getting.

GWTP Handlers are Thread safe?

I am using gwt-platform for my application development.
I opened 2 browsers running the same application, i did 2 same operations with different data, but the now the browsers on the same view accessing the similar handler action
now the issue is the 2 browsers has updated with first received data from handler..
i am not understanding why it is not recognized the browsers which send the request... so this means its not Threadsafe...?
I seen #RequestedScope annotation in the Guice is it useful when i use on execute() of Handler
any suggestions?
Thanks in advance...
Maybe...
You have to made your Actions thread-safe. (attrs has final, e.g., inject in constructor), and perharps your logic has to be thread-safe too.
Btw, can you post a example of your action?
With 2 browsers you should have 2 different instances of your app running. In your onModuleLoad(), just put a System.out.println(this);. You should see different result which means you have different instances.
If you run an action from Browser 1, the action will be executed only in Browser 1. I don't know what your action is doing but if it updates data in the datastore (or DB) and since both instances share the persistence layer, you will see the new data in Browser 2 too.
It's very unlikely that the action triggered in Browser 1 is executed on both Browsers. It would mean that they share the same event bus.
public class InfoAction extends UnsecuredActionImpl<Response<ObjectTO>>
{
private List<OpenTO> request;
private String machineId;
private int actionType;
private UserBean userBean;
/**
* This is been in the case of double dated flight.
*/
private String orignalFpesLegId;
public List<OpenTO> getRequest() {
return request;
}
public void setRequest(List<OpenTO> request) {
this.request = request;
}
public String getMachineId() {
return machineId;
}
public void setMachineId(String machineId) {
this.machineId = machineId;
}
/**
* #return the actionType
*/
public int getActionType() {
return actionType;
}
/**
* #param actionType the actionType to set
*/
public void setActionType(int actionType) {
this.actionType = actionType;
}
/**
* #param userBean the userBean to set
*/
public void setUserBean(UserBean userBean) {
this.userBean = userBean;
}
/**
* #return the userBean
*/
public UserBean getUserBean() {
return userBean;
}
}
Please find my action class code

Vala: D-BUS object implementing interface, error with properties

Is it possible to have a class annotated with [DBus (name = ...)] implement an interface?
Following the example at https://live.gnome.org/Vala/DBusServerSample, I am implementing a D-BUS client/server application.
One thing that I found peculiar about the example was that there was no separate interface definition. I would like to have the interface used by the client side in a separate file, and have the server class implement that interface. That way I can have the compiler tell me when I miss something.
This does not appear to work with properties though. The following definition is compatible with what I have:
/* interface.vala */
namespace org.test {
[DBus (name = "org.test.Items")]
public interface IItems : Object {
/**
* The object paths to the item instances.
*
* These objects are of type org.test.items.Item.
*/
public abstract ObjectPath[] items {
owned get;
}
/**
* The signal that is emitted when a new item is added.
*
* When this signal is emitted, the item will be available.
*
* #param id
* The object path to the item instance.
*/
public signal void item_added(ObjectPath id);
/**
* The signal that is emitted when an item is removed.
*
* When this signal is emitted, the item will be unavailable.
*
* #param id
* The object path to the item instance.
*/
public signal void item_removed(ObjectPath id);
/**
* Adds a new item.
*
* The URL will be parsed, and if it contains a valid item, it will be
* added.
*
* #param url
* The URL to the item. This should typically be the URL of the
* RSS feed.
* #return the ID of the item added, which can be used to query D-BUS
* for it
* #throws IOError if a D-BUS error occurs
*/
public abstract ObjectPath add_item(string url) throws IOError;
/**
* Removes an item.
*
* #param id
* The ID of the item to remove.
* #throws IOError if a D-BUS error occurs
*/
public abstract void remove_item(ObjectPath id) throws IOError;
}
}
/* server.vala */
using Gee;
namespace org.test {
[DBus (name = "org.test.Items")]
public class Items : DBUSObject, IItems {
private ArrayList<Item> _items;
[DBus (visible = false)]
protected override void dbus_register(DBusConnection conn,
ObjectPath path) throws IOError {
conn.register_object(path, this);
}
[DBus (visible = false)]
public Items() {
base("org.test.Items", "/org/test", "Items", true);
_items = new ArrayList<Item>();
}
[DBus (visible = false)]
~Items() {
unregister();
}
/**
* #see interface.vala::org.test.IItems.comics
*/
public ObjectPath[] items {
owned get {
ObjectPath[] result = {};
foreach (var item in _items) {
result += new ObjectPath(item.path);
}
return result;
}
}
/**
* #see interface.vala::org.test.IItems.add_comic
*/
public ObjectPath add_item(string url) throws IOError {
/* . . . */
}
/**
* #see interface.vala::org.test.IItems.remove_item
*/
public void remove_item(ObjectPath id) throws IOError {
/* . . . */
}
}
}
When I compile it, I get no error from valac, but when the generated C code is compiled, the linker complains: undefined reference to 'org_test_items_get_items'.
This function is referenced by _dbus_org_test_items_get_items, but it does not exist
It's obviously a bug. The right place to report bugs is http://bugzilla.gnome.org .