Categories
discuss

How do i use AudioContext in WebAudio

I’m trying to create a way to generate sounds in sms. This gives me a “Cannot call method ‘createScriptProcessor’ of null” ?

Is the JAudioContext supposed to be created ?

...

AudioContext  : JAudioContext;
node          : JScriptProcessorNode;

...

procedure TForm1.W3Button1Click(Sender: TObject);
var bufferSize : integer;
    lastOut : float;
    input,output : JFloat32Array;
begin
  bufferSize := 4096;
  lastOut := 0;
  node := AudioContext.createScriptProcessor(bufferSize, 1, 1);
  node.onaudioprocess := procedure (e: JAudioProcessingEvent)
  var i : integer;
  begin
    input := e.inputBuffer.getChannelData(0);
    output := e.outputBuffer.getChannelData(0);
    for i := 0 to bufferSize-1 do
    begin
      output[i] := (input[i] + lastOut) / 2.0;
      lastOut := output[i];
    end;
  end;
end;

Answer

At the moment you still need some JavaScript workaround to get the audio context created.

Something like

var AudioContext: JAudioContext;

procedure InitializeAudioContext;
begin 
  asm
    // Fix up for prefixing
    window.AudioContext = window.AudioContext||window.webkitAudioContext;

    if('webkitAudioContext' in window) {
      @AudioContext = new webkitAudioContext();
     }
  end;
end;

Note: The unit w3c.WebAudio is basically just a wrapper for the W3C API and does not contain code to get the audio context initialized. So far this has to be done (as shown above) in your code.

For the future we plan to have some higher level abstraction.

The upcoming version 2.1 will contain another featured example about the Web Audio API and an improved ‘Sine Generator’ example. It is planned to be released in April/May.

Update 1:

Alternatively you can instantiate your context using this code:

AudioContext := new JAudioContext;

However, it does not work for older webkit based browsers. These need an additional webkit prefix.

In this case something like:

type
       JWebkitAudioContext = class external 'webkitAudioContext' (JAudioContext);

AudioContext := new JWebkitAudioContext;

would work.

For compatibility reasons, you may need to check whether the prefix is necessary or not. Or just use the “asm” snippet posted above.

Update 2:

Eric just wrote me an email about how to do the check in Pascal code. While it is still a bit ugly, it avoids the asm section.

First declare the webkitAudioContext and then check if it’s assigned:

var webkitAudioContext external 'webkitAudioContext' : JwebkitAudioContext;
var hasWebkitAudio := Boolean(Variant(webkitAudioContext));
Categories
discuss

Recursive blocks in Ace editor

We’ve got our own scripting language that we use. The language is quite simple, but it has one ‘exclusive’ thing: strings are defined using ‘[‘ and ‘]’ (so “test” would be [test]), and these braces can be inside each other:

lateinit([concat([test], [blah])])

Also, there’s no escaping character. How does one parse this block as one string (thus highlighting the [concat([test], [blah])] block)? I currently got the following rule:

     { token: 'punctuation.definition.string.begin.vcl',
       regex: '\[',
       push: 
        [ 
          { token: 'punctuation.definition.string.end.vcl',
            regex: '\]',
            next: 'pop' },
          { defaultToken: 'string.quoted.other.vcl' } ],
        },

But, as you might’ve guessed, this will stop at brace at the end of test: ‘[ concat([test ], [blah])]’…

Other examples are:

setexpratt(1, [if(comparetext([yes], [no]), msg([test expression]))]);
terminator([confirm([Are you sure you want to exit?])]);
registerfunction([testfunction], 1, 3, [], [msg(concat([Argument 1: ], p(1), [, Argument 2: ], p(2), [, Argument 3: ], p(3)))]);

Answer

You need to add rule for [ into the inner string state, try

this.$rules = { 
    start: [
        { token: 'string.begin.vcl', regex: '\[', push: "string" }
    ],
    string : [ 
        { token: 'string.begin.vcl', regex: '\[', push: "string" },
        { token: 'string.end.vcl', regex: '\]', next: 'pop' },
        { defaultToken: 'string.quoted.other.vcl' },
    ]
};
this.normalizeRules();
Categories
discuss

Spring security OAuth2 authorization process

Can anybody tell me what http GET or POST methods should I sequentially call in order to authorize to my apache cxf web services and get access to resources? I tried to call:

http://localhost:8080/oauth/token?client_id=client1&client_secret=client1&grant_type=password&username=client1&password=client1

and all I can get is token response:

{"access_token":"7186f8b2-9bae-48b6-90c2-033a4476c0fc","token_type":"bearer","refresh_token":"d7fe8cda-812b-4b3e-9ce7-b15067e001e4","expires_in":298653}

but what is the next step after I get this token? How can I authenticate the user and get access to resource in url /resources/MyResource/getMyInfo which requires user with role ROLE_USER ? Thanks.

I have the following servlet config:

<http pattern="/oauth/token" create-session="stateless"
      authentication-manager-ref="authenticationManager"
      xmlns="http://www.springframework.org/schema/security">
    <intercept-url pattern="/oauth/token" access="IS_AUTHENTICATED_FULLY"/>
    <anonymous enabled="false"/>
    <http-basic entry-point-ref="clientAuthenticationEntryPoint"/>
    <custom-filter ref="clientCredentialsTokenEndpointFilter" before="BASIC_AUTH_FILTER"/>
</http>

<http pattern="/resources/**" create-session="never"
      entry-point-ref="oauthAuthenticationEntryPoint"
      xmlns="http://www.springframework.org/schema/security">
    <anonymous enabled="false"/>
    <intercept-url pattern="/resources/MyResource/getMyInfo" access="ROLE_USER" method="GET"/>
    <custom-filter ref="resourceServerFilter" before="PRE_AUTH_FILTER"/>
    <access-denied-handler ref="oauthAccessDeniedHandler"/>
</http>

<http pattern="/logout" create-session="never"
      entry-point-ref="oauthAuthenticationEntryPoint"
      xmlns="http://www.springframework.org/schema/security">
    <anonymous enabled="false"/>
    <intercept-url pattern="/logout" method="GET"/>
    <sec:logout invalidate-session="true" logout-url="/logout" success-handler-ref="logoutSuccessHandler"/>
    <custom-filter ref="resourceServerFilter" before="PRE_AUTH_FILTER"/>
    <access-denied-handler ref="oauthAccessDeniedHandler"/>
</http>

<bean id="logoutSuccessHandler" class="demo.oauth2.authentication.security.LogoutImpl">
    <property name="tokenstore" ref="tokenStore"/>
</bean>

<bean id="oauthAuthenticationEntryPoint"
      class="org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint">
</bean>

<bean id="clientAuthenticationEntryPoint"
      class="org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint">
    <property name="realmName" value="springsec/client"/>
    <property name="typeName" value="Basic"/>
</bean>

<bean id="oauthAccessDeniedHandler"
      class="org.springframework.security.oauth2.provider.error.OAuth2AccessDeniedHandler">
</bean>

<bean id="clientCredentialsTokenEndpointFilter"
      class="org.springframework.security.oauth2.provider.client.ClientCredentialsTokenEndpointFilter">
    <property name="authenticationManager" ref="authenticationManager"/>
</bean>

<authentication-manager alias="authenticationManager"
                        xmlns="http://www.springframework.org/schema/security">
    <authentication-provider user-service-ref="clientDetailsUserService"/>
</authentication-manager>

<bean id="clientDetailsUserService"
      class="org.springframework.security.oauth2.provider.client.ClientDetailsUserDetailsService">
    <constructor-arg ref="clientDetails"/>
</bean>

<bean id="clientDetails" class="demo.oauth2.authentication.security.ClientDetailsServiceImpl"/>

<authentication-manager id="userAuthenticationManager"
                        xmlns="http://www.springframework.org/schema/security">
    <authentication-provider ref="customUserAuthenticationProvider">
    </authentication-provider>
</authentication-manager>

<bean id="customUserAuthenticationProvider"
      class="demo.oauth2.authentication.security.CustomUserAuthenticationProvider">
</bean>

<oauth:authorization-server user-approval-handler-ref="userApprovalHandler"
        client-details-service-ref="clientDetails" token-services-ref="tokenServices">
    <oauth:authorization-code/>
    <oauth:implicit/>
    <oauth:refresh-token/>
    <oauth:client-credentials />
    <oauth:password authentication-manager-ref="authenticationManager"/>
</oauth:authorization-server>

<oauth:resource-server id="resourceServerFilter"
                       resource-id="springsec" token-services-ref="tokenServices"/>

<bean id="tokenStore" class="org.springframework.security.oauth2.provider.token.InMemoryTokenStore"/>

<bean id="tokenServices"
      class="org.springframework.security.oauth2.provider.token.DefaultTokenServices">
    <property name="tokenStore" ref="tokenStore"/>
    <property name="supportRefreshToken" value="true"/>
    <property name="accessTokenValiditySeconds" value="300000"/>
    <property name="clientDetailsService" ref="clientDetails"/>
</bean>

<bean id="userApprovalHandler"
      class="org.springframework.security.oauth2.provider.approval.TokenServicesUserApprovalHandler">
    <property name="tokenServices" ref="tokenServices" />
</bean>

<bean id="MyResource" class="demo.oauth2.authentication.resources.MyResource"/>

and web.xml:

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID"
         version="2.5">
    <display-name>Spring Secure REST</display-name>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/spring-servlet.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <listener>
        <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
    </listener>
    <filter>
        <filter-name>springSecurityFilterChain</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
        <init-param>
            <param-name>contextAttribute</param-name>
            <param-value>org.springframework.web.servlet.FrameworkServlet.CONTEXT.spring</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>springSecurityFilterChain</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <servlet>
        <servlet-name>REST Service</servlet-name>
        <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
        <init-param>
            <param-name>com.sun.jersey.config.property.packages</param-name>
            <param-value>demo.oauth2.authentication.resources</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>REST Service</servlet-name>
        <url-pattern>/resources/*</url-pattern>
    </servlet-mapping>

    <servlet>
        <servlet-name>spring</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>spring</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

UPDATED: Found working sample here http://software.aurorasolutions.org/how-to-oauth-2-0-with-spring-security-2/ maybe will be useful for those who have similiar problem

Answer

You first need to create an OAuth2AccessToken which you can then use to build an OAuth2RestTemplate which can then be used perform authenticated GET, POST calls.

Here is an example of how you might setup an OAuth2RestTemplate:

ResourceOwnerPasswordAccessTokenProvider provider = new ResourceOwnerPasswordAccessTokenProvider();
ResourceOwnerPasswordResourceDetails resource = new ResourceOwnerPasswordResourceDetails();
resource.setClientAuthenticationScheme(AuthenticationScheme.form);
resource.setAccessTokenUri("accessTokenURI");
resource.setClientId("clientId");
resource.setGrantType("password");
resource.setClientSecret("clientSecret");
resource.setUsername("userName");
resource.setPassword("password");
OAuth2AccessToken accessToken = provider.obtainAccessToken(getResource(), new DefaultAccessTokenRequest());
OAuth2RestTemplate restTemplate = new OAuth2RestTemplate(getResource(), new DefaultOAuth2ClientContext(accessToken));
Categories
discuss

Cartesian product in RxJava

Is it possible to get Cartesian product of two Observables in rxjava?

Something like this:

A -> 1,2,3
B -> a,b
A x B -> (1, a), (1, b), (2, a), (2, b), (3, a), (3, b)

Answer

What you want is to produce, for one number, as pair as you have letters. So you can easily achive this using map and flatMap operator.

    Observable<Integer> number = Observable.from(Arrays.asList(1, 2, 3));
    Observable<String> letters = Observable.from(Arrays.asList("a", "b"));

    Observable<Pair> cartesian = number.flatMap((n) -> letters.map((l) -> new Pair(n, l)));
Categories
discuss

Comparisions using ternary operator vs if else vs switch case (Performance)

I was searching for if-else vs ternary operator vs switch case but could not find any post with all the three comparisons. However, I came across some good posts and found that switch-case is faster than if-else. You may check the below one:

Why switch is faster than if

Then I came across some posts which said that there is no performance difference between if-else and the ternary operator.
One of the most relevant posts is the following:

ternary operator vs. if statement: question of prettiness?

However, I did not find any relevant posts for switch-case vs ternary operator.

So, I just want to know if I can conclude that switch case is faster than both ternary operator and if-else?

I know this is a silly question but I want to know the answer.

Answer

If switch < if-then-else and if-then-else == ternary, then switch < ternary.

Source: stackoverflow
Text is available under the Creative Commons Attribution-ShareAlike License; additional terms may apply. By using this site, you agree to the Privacy Policy, and Copyright Policy. Content is available under CC BY-SA 3.0 unless otherwise noted. The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 © No Copyrights, All Questions are retrived from public domain..