CMethodAction.java

  1. /*
  2.  * @cond LICENSE
  3.  * ######################################################################################
  4.  * # LGPL License                                                                       #
  5.  * #                                                                                    #
  6.  * # This file is part of the LightJason AgentSpeak(L++)                                #
  7.  * # Copyright (c) 2015-19, LightJason (info@lightjason.org)                            #
  8.  * # This program is free software: you can redistribute it and/or modify               #
  9.  * # it under the terms of the GNU Lesser General Public License as                     #
  10.  * # published by the Free Software Foundation, either version 3 of the                 #
  11.  * # License, or (at your option) any later version.                                    #
  12.  * #                                                                                    #
  13.  * # This program is distributed in the hope that it will be useful,                    #
  14.  * # but WITHOUT ANY WARRANTY; without even the implied warranty of                     #
  15.  * # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the                      #
  16.  * # GNU Lesser General Public License for more details.                                #
  17.  * #                                                                                    #
  18.  * # You should have received a copy of the GNU Lesser General Public License           #
  19.  * # along with this program. If not, see http://www.gnu.org/licenses/                  #
  20.  * ######################################################################################
  21.  * @endcond
  22.  */

  23. package org.lightjason.agentspeak.action.binding;

  24. import org.lightjason.agentspeak.action.IBaseAction;
  25. import org.lightjason.agentspeak.common.CPath;
  26. import org.lightjason.agentspeak.common.IPath;
  27. import org.lightjason.agentspeak.language.CRawTerm;
  28. import org.lightjason.agentspeak.language.ITerm;
  29. import org.lightjason.agentspeak.language.execution.IContext;
  30. import org.lightjason.agentspeak.language.fuzzy.CFuzzyValue;
  31. import org.lightjason.agentspeak.language.fuzzy.IFuzzyValue;

  32. import javax.annotation.Nonnegative;
  33. import javax.annotation.Nonnull;
  34. import javax.annotation.Nullable;
  35. import java.io.IOException;
  36. import java.io.ObjectInputStream;
  37. import java.io.ObjectOutputStream;
  38. import java.lang.invoke.MethodHandle;
  39. import java.lang.invoke.MethodHandles;
  40. import java.lang.reflect.Method;
  41. import java.text.MessageFormat;
  42. import java.util.List;
  43. import java.util.Locale;
  44. import java.util.Objects;
  45. import java.util.stream.Collectors;
  46. import java.util.stream.Stream;


  47. /**
  48.  * action for binding a method.
  49.  * action uses agent for object binding
  50.  */
  51. public final class CMethodAction extends IBaseAction
  52. {
  53.     /**
  54.      * serial id
  55.      */
  56.     private static final long serialVersionUID = -507236338411690842L;
  57.     /**
  58.      * name of the action
  59.      */
  60.     private final IPath m_name;
  61.     /**
  62.      * number of arguments
  63.      */
  64.     private final int m_arguments;
  65.     /**
  66.      * method reference
  67.      */
  68.     private transient Method m_method;
  69.     /**
  70.      * method handle
  71.      */
  72.     private transient MethodHandle m_methodhandle;


  73.     /**
  74.      * ctor
  75.      *
  76.      * @param p_method method reference
  77.      * @throws IllegalAccessException on method access error
  78.      */
  79.     public CMethodAction( @Nonnull final Method p_method ) throws IllegalAccessException
  80.     {
  81.         m_method = p_method;
  82.         m_arguments = m_method.getParameterCount();
  83.         m_name = CPath.from(
  84.             m_method.isAnnotationPresent( IAgentActionName.class ) && !m_method.getAnnotation( IAgentActionName.class ).name().isEmpty()
  85.             ? m_method.getAnnotation( IAgentActionName.class ).name().toLowerCase( Locale.ROOT )
  86.             : m_method.getName().toLowerCase( Locale.ROOT )
  87.         );
  88.         m_methodhandle = MethodHandles.lookup().unreflect( m_method );
  89.     }

  90.     /**
  91.      * serialize call
  92.      *
  93.      * @param p_stream object stream
  94.      * @throws IOException error on writing object data
  95.      */
  96.     private void writeObject( final ObjectOutputStream p_stream ) throws IOException
  97.     {
  98.         p_stream.defaultWriteObject();

  99.         // serialize method handle
  100.         p_stream.writeObject( m_method.getDeclaringClass() );
  101.         p_stream.writeUTF( m_method.getName() );
  102.         p_stream.writeObject( m_method.getParameterTypes() );
  103.     }

  104.     /**
  105.      * deserializable call
  106.      *
  107.      * @param p_stream object stream
  108.      * @throws IOException is thrown on io error
  109.      * @throws ClassNotFoundException is thrown on deserialization error
  110.      * @throws NoSuchMethodException is thrown on method deserialization
  111.      * @throws IllegalAccessException is thrown on creating method handle
  112.      */
  113.     @SuppressWarnings( "unchecked" )
  114.     private void readObject( final ObjectInputStream p_stream ) throws IOException, ClassNotFoundException, NoSuchMethodException, IllegalAccessException
  115.     {
  116.         p_stream.defaultReadObject();

  117.         // deserialize method handle
  118.         m_method = ( (Class<?>) p_stream.readObject() ).getMethod( p_stream.readUTF(), (Class<?>[])p_stream.readObject() );
  119.         m_methodhandle = MethodHandles.lookup().unreflect( m_method );
  120.     }

  121.     @Nonnull
  122.     @Override
  123.     public final IPath name()
  124.     {
  125.         return m_name;
  126.     }

  127.     @Nonnegative
  128.     @Override
  129.     public final int minimalArgumentNumber()
  130.     {
  131.         return m_arguments;
  132.     }

  133.     @Nonnull
  134.     @Override
  135.     public IFuzzyValue<Boolean> execute( final boolean p_parallel, @Nonnull final IContext p_context,
  136.                                          @Nonnull final List<ITerm> p_argument, @Nonnull final List<ITerm> p_return
  137.     )
  138.     {
  139.         try
  140.         {
  141.             return m_arguments == 0

  142.                 ? CMethodAction.returnvalues(
  143.                 m_methodhandle.invoke( p_context.agent() ),
  144.                 p_return
  145.                 )

  146.                 : CMethodAction.returnvalues(
  147.                     m_methodhandle.invokeWithArguments(
  148.                         Stream.concat(
  149.                             Stream.of( p_context.agent() ),
  150.                             p_argument.stream().map( ITerm::raw )
  151.                         ).collect( Collectors.toList() )
  152.                     ),
  153.                     p_return
  154.                 );
  155.         }
  156.         catch ( final Throwable l_throwable )
  157.         {
  158.             LOGGER.warning( MessageFormat.format( "binding method [{0}] throws error [{1}] in agent: ", m_name, l_throwable, p_context.agent() ) );
  159.             return CFuzzyValue.from( false );
  160.         }
  161.     }

  162.     /**
  163.      * creates the returns values of the execution
  164.      *
  165.      * @param p_result return object of the invoke call
  166.      * @param p_return return argument list
  167.      * @return execution return
  168.      */
  169.     @Nonnull
  170.     private static IFuzzyValue<Boolean> returnvalues( @Nullable final Object p_result, @Nonnull final List<ITerm> p_return )
  171.     {
  172.         // void result of the execution
  173.         if ( ( Objects.isNull( p_result ) ) || ( void.class.equals( p_result.getClass() ) ) )
  174.             return CFuzzyValue.from( true );

  175.         // otherwise object is returned
  176.         p_return.add( CRawTerm.from( p_result ) );
  177.         return CFuzzyValue.from( true );
  178.     }
  179. }