2017-04-06 4 views
1

にResponseオブジェクトへのデータの追加、私は周りの助言を使用してjavax.ws.rs.core.Responseにタイムスタンプを追加するためにAspectを使用しようとしています。はジャージー

私は、Javaとジャージーに新たなんだと私はこれを行うのに苦労しています。生成された応答の種類は常にapplication/JSONある

Object output = proceed(); 
Method method = ((MethodSignature) thisJoinPoint.getSignature()).getMethod(); 
Type type = method.getGenericReturnType(); 

if (type == Response.class) 
{ 
    System.out.println("We have a response!"); 
    Response original = (Response) output; 
    output = (Object)Response.ok(original.getEntity(String.class).toString()+ " " + Double.toString(duration)).build(); 
} 

return output; 

:私が持っている最も近いがこれです。基本的には、time:<val of duration>というJSONに別のフィールドを追加したいと思います。

答えて

0

最も簡単な解決策は、すべてのエンティティクラスをメソッドgetTime()setTime()を持つインターフェイスに拡張することです。次に、以下のようにインターセプタで時間値を設定できます。

public interface TimedEntity { 
    long getTime(); 

    void setTime(long time); 
} 

あなたの実際のエンティティ

public class Entity implements TimedEntity { 
    private long time; 

    // Other fields, getters and setters here.. 

    @Override 
    public long getTime() { 
     return time; 
    } 

    @Override 
    public void setTime(long time) { 
     this.time = time; 
    } 
} 

そして、あなたの迎撃

Object output = proceed(); 
Method method = ((MethodSignature)thisJoinPoint.getSignature()).getMethod(); 
Type type = method.getGenericReturnType(); 

if (type == Response.class) 
{ 
    System.out.println("We have a response!"); 
    Response original = (Response) output; 
    if (original != null && original.getEntity() instanceof TimedEntity) { 
    TimedEntity timedEntity = (TimedEntity) original.getEntity(); 
    timedEntity.setTime(duration); 
    } 

}else if (output instanceof TimedEntity) { 
    TimedEntity timedEntity = (TimedEntity) output; 
    timedEntity.setTime(duration); 
} 

return output; 
関連する問題