Source

webcandy / src / webmstn_admin_resource.erl

The default branch has multiple heads

Full commit
%% @author sunneach http://bitbuckets.com/sunneach
%% @copyright 2009 sunneach
%% @doc Example webmachine_resource.

-module(webmstn_admin_resource).
-export([
		init/1,
		allowed_methods/2,
		delete_resource/2,
		resource_exists/2,
		content_types_accepted/2,
		from_json/2,
		to_html/2
		]).

-define(TRACE_ENV,"WEBCANDY_TRACE").

-include_lib("webmachine/include/webmachine.hrl").

init([]) -> {ok, undefined}.

allowed_methods(RD, Ctx) ->
     {['GET','PUT','HEAD','DELETE'], RD, Ctx}.

	 
%% PUT support
content_types_accepted(RD, Ctx) ->
    {[{"application/json", from_json}], RD, Ctx}.

%% PUT support
%% SET TRACE ON 
from_json(RD, Ctx) ->
    Trace  = application:get_env(webmachine,dispatch_list_trace),
	case Trace of 
	    undefined       ->	            
    {ok,Dispatch} = application:get_env(webmachine,dispatch_list),
                [{_,_,[{trace_dir,TraceDir}]}] = 
  				    [{P,R,M} || {P,R,M} <- Dispatch, R =:= wmtrace_resource],
                TraceDisp = lists:map(fun({P,R,M}) ->
						{P,R,
						     case R of 
							 Adm when Adm =:= wmtrace_resource;Adm =:= webmstn_admin_resource ->
									  M;
							 _ -> [{trace_dir,TraceDir}|M]
							 end} end, Dispatch),
	            application:set_env(webmachine,dispatch_list_trace,TraceDisp),
	            application:set_env(webmachine,dispatch_list_notrace,Dispatch);
        {ok,TraceDisp}  ->
			    ok
	end,
	
	application:set_env(webmachine,dispatch_list,TraceDisp),
 
	% ignore input, just create non-empty trace value
    os:putenv(?TRACE_ENV, "Trace On"),
              io:format("Trace On~n"),
    {true, RD, Ctx}.


%% DELETE support
%% trace OFF operation 
delete_resource(RD, Ctx) ->
	NoTrace  = application:get_env(webmachine,dispatch_list_notrace),
	case NoTrace of 
	undefined ->
	            ok;
    {ok,Disp} ->
	            application:set_env(webmachine,dispatch_list,Disp)
	end,
				 
    % empty value is considered non-existent
    os:putenv(?TRACE_ENV, []),
              io:format("Trace OFF~n"),
    {true, RD, Ctx}.

%% 
to_html(RD, Ctx) ->
   % no need to send anything but code 200 for the HEAD
    {[], RD, Ctx}.

%% HEAD support
resource_exists(RD, Ctx) ->
    case os:getenv(?TRACE_ENV) of
    false  -> 
              {false, RD, Ctx};
    Result -> 
		      case Result of
		       "" ->
			        {false, RD, Ctx};
	           _  ->	
                    {true, RD, Result}
        end
    end.