Thursday, September 28, 2017

Cordova IOS video player

Leave a Comment

I am using webRTC streaming via RTCMultiConnection. I created a cordova application and get the blob url from server in video tag. In android and browsers works well. In IOS, video plays but control buttons does not work. Also video's position is static on application. I change page in application but video always stay. When i try to pull page, it looks like here :

enter image description here

enter image description here

My HTML code :

<video webkit-playsinline playsinline class="screen-video" src="" reload="metadata" autoplay controls></video> 

And how i append in js :

var videoURL = event.mediaElement.src; $('.screen-video').attr('src', videoURL); 

My videoURL is like : blob : file:///adfsg-123asd1-12asfd3-4fdssdv

Edit : I can see my iphone's front camera on browser live. But i can not see me, in iphone.

Videoplayer does not work.

Edit 2 : 26.09.2017 There is no problem with mp4 video. I tried with remote mp4 video, and it works well.

Here is screenshots, they are all same. Only src different.

p.s Big video is mp4 always static position, and small video is blob and when i scrolling, it scroll to. :

https://i.imgyukle.com/2017/09/25/kgZev.jpg

https://i.imgyukle.com/2017/09/25/kg4kx.jpg

https://i.imgyukle.com/2017/09/25/kg6a6.jpg

enter image description here

1 Answers

Answers 1

iOS doesn't play nice with embed media sadly.

As this SO answer suggests:

For the controls, as the videos always play in full-screen, the space left will capture all the click and touch events.

A workaround suggested above could be to set the video's tag width & height to 1/1 dimensions - fixed position to -10,-10 and trigger "play" manually with a custom UI instead the video.

Note the following info from Apple's Dev Site:

Optimization for Small Screens

Currently, Safari optimizes video presentation for the smaller screen on iPhone or iPod touch by playing video using the full screen—video controls appear when the screen is touched, and the video is scaled to fit the screen in portrait or landscape mode. Video is not presented within the webpage. The height and width attributes affect only the space allotted on the webpage, and the controls attribute is ignored. This is true only for Safari on devices with small screens. On Mac OS X, Windows, and iPad, Safari plays video inline, embedded in the webpage.

Default Height and Width on iOS

Because the native dimensions of a video are not known until the movie metadata loads, a default height and width of 150 x 300 is allocated on devices running iOS if the height or width is not specified. Currently, the default height and width do not change when the movie loads, so you should specify the preferred height and width for the best user experience on iOS, especially on iPad, where the video plays in the allocated space.

iPhone Video Placeholder

The placeholder provides a way for the user to play the media. If the iOS device cannot play the specified media, there is a diagonal bar through the control, indicating that it cannot play.

In case you are willing to consider alternatives, this cordova plugin could be useful:

This plugin allows you to stream audio and video in a fullscreen, native player on iOS and Android.

Basic usage:

var videoUrl = STREAMING_VIDEO_URL;    // Just play a video   window.plugins.streamingMedia.playVideo(videoUrl); 
Read More

Wednesday, September 27, 2017

Why do I get invalid byte sequence in UTF-8

Leave a Comment

Why do I get this error ?

invalid byte sequence in UTF-8 

for loading an image in:

= image_tag 'features_home/show1.png' 

EDIT

I've notice that this issue occurred only after I did bundle update, the error occurs with any image.. I will try to add details here:

Stacktrace:

  Rendered home/home.html.haml within layouts/application (229.9ms) Completed 500 Internal Server Error in 1047ms invalid byte sequence in UTF-8 excluded from capture: DSN not set  ActionView::Template::Error (invalid byte sequence in UTF-8):     81:           / Carousel items     82:           .carousel-inner     83:             .active.item     84:               = image_tag 'features_home/show1.png'     85:               -#.carousel-caption     86:               -#  %h4     87:               -#  %p   app/views/home/home.html.haml:84:in `block in _app_views_home_home_html_haml__623651309533727079_70331260863620'   app/views/home/home.html.haml:33:in `_app_views_home_home_html_haml__623651309533727079_70331260863620'   lib/rack/seoredirect.rb:20:in `call'     Rendered /Users/Apple/.rvm/gems/ruby-2.2.2@myapp/gems/actionpack-4.2.0/lib/action_dispatch/middleware/templates/rescues/_source.erb (115.6ms)   Rendered /Users/Apple/.rvm/gems/ruby-2.2.2@myapp/gems/actionpack-4.2.0/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb (23.1ms)   Rendered /Users/Apple/.rvm/gems/ruby-2.2.2@myapp/gems/actionpack-4.2.0/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb (1.7ms)   Rendered /Users/Apple/.rvm/gems/ruby-2.2.2@myapp/gems/actionpack-4.2.0/lib/action_dispatch/middleware/templates/rescues/template_error.html.erb within rescues/layout (237.9ms) 

Gemfile.lock before and after bundle update: https://gist.github.com/hopewise/35c2a98b13ac646b65770feb2f3c7ec8

Full trace: https://gist.github.com/hopewise/551169518a5938647dc767d3de393cd4

I don't know which gem caused the issue though..

0 Answers

Read More

How to allow / workaround nested composite Gradle builds

Leave a Comment

I'm running into the same issue as reported here:

I have a Java project A which depends on project B (module), and project B dependes on project C (another module). For project A I would like to setup "includeBuild ../projectB" and for project B I would like too setup "includeBuild ../projectC" so that I could develop everything in Eclipse + Buildship 2.0 without the need to run Gradle for every small change in each of the projecta A, B and C.

But if I setup this I get: "Included build '%s' cannot have included builds.".

Expected Behavior

Recursive "includeBuild" would recursively include dependent projects.

Current Behavior

I get "Included build '%s' cannot have included builds.".

Your Environment

Gradle 3.5, Buildship 2.0, Eclipse 3.6

How can I resolve / work around this issue? In my instance, I have utility project that includes email functionality (using JavaMail). The email functionality is needed in the data project and a UI project. The UI project also depends on the data project.

2 Answers

Answers 1

Have you considered

  1. Ensuring that none of the individual builds are composite builds
  2. Having an "uber" build which is a composite of everything

Note that the settings.gradle is itself a groovy script, so you could create a dynamic composite, eg all sub-folders with a build.gradle under a parent.

uber/settings.gradle

new File("c:/someFolder").listFiles().each { File f ->     if (f.directory && new File(f, 'build.gradle').exists()) {         includeBuild f     } } 

Eg

c:/someFolder/project1/build.gradle c:/someFolder/project1/src/main/java/**/*.java c:/someFolder/project2/build.gradle c:/someFolder/project2/src/main/java/**/*.java c:/uber/settings.gradle (as above) 

Answers 2

Adding another answer for a different approach...

Each settings.gradle could add a check to before includeBuild to see if it's already inside a composite. If it's already inside a composite, it doesn't includeBuild.

See here for extra info on the composite check

Eg

project2/settings.gradle

boolean inComposite = gradle.parent != null if (!inComposite) {     includeBuild '../project1' } 

project3/settings.gradle

boolean inComposite = gradle.parent != null if (!inComposite) {     includeBuild '../project1'     includeBuild '../project2' } 

project4/settings.gradle

boolean inComposite = gradle.parent != null if (!inComposite) {     includeBuild '../project1'     includeBuild '../project2'     includeBuild '../project3' } 

etc etc

Using this approach you could run gradle from wherever you like and it should behave as expected (ie substitute dependencies with local projects)

Read More

Authenticate users from more than two tables in laravel 5

Leave a Comment

As I know Auth::attempt is used to authenticate users from users table, but i want to authenticate another users from managers table and admin from admins table. I know there are laravel-multiauth plugin already exist. But can we create our own AuthServiceProvider for authenticating users from multiple tables..?

6 Answers

Answers 1

Try my idea if you want to. I'm expecting that different table has different users. Because it won't work if you have the same user in other tables.

  1. Choose your priority table (e.g. users)
  2. Add the condition
    • if(Auth::user(attempt(...))
    • elseif(Auth::manager(attempt(...))
    • elseif(Auth::admins(attempt(...)))

Note: Your priority table here is users, then if the user doesn't exists in that table, it will try the managers table, then if still doesn't exists, it will check the admins table, otherwise (use else) return a message error.

Other option:

Other option is to use this package sarav/laravel-multiauth. You can follow this thread. How to use authentication for multiple tables in Laravel 5 for more information.

More Reference:

https://laracasts.com/discuss/channels/general-discussion/using-laravel-auth-for-multiple-tables?page=1

Can anyone explain Laravel 5.2 Multi Auth with example

https://laracasts.com/discuss/channels/laravel/52-auth-multiple-tables?page=1

Answers 2

You could setup multiple authentication guards, with each one having a different provider. The providers define the table or model to be used.

In config/auth.php you setup the providers as follows and you also setup corresponding guards for each of those providers:

'providers' => [     'users'  => [         'driver' => 'eloquent',         'model'  => App\User::class,     ],     'managers'  => [         'driver' => 'eloquent',         'model'  => App\Manager::class,     ],     'admins'  => [         'driver' => 'eloquent',         'model'  => App\Admin::class,     ] ] 

Then you can authenticate like this:

Auth::attempt($credentials) // use default guard for simple users Auth::guard('manager')->attempt($credentials) Auth::guard('admin')->attempt($credentials) 

Check out the docs here.

Answers 3

Implement Multi Auth in Larvel 5.2

I'm considering two tables admin and users

Laravel 5.2 has a new artisan command.

php artisan make:auth 

it will generate basic login/register route, view and controller for user table.

Make a admin table as users table for simplicity.

Controller For Admin

app/Http/Controllers/AdminAuth/AuthController app/Http/Controllers/AdminAuth/PasswordController 

(note: I just copied these files from app/Http/Controllers/Auth/AuthController here)

config/auth.php

//Authenticating guards 'guards' => [     'user' =>[         'driver' => 'session',         'provider' => 'user',     ],     'admin' => [         'driver' => 'session',         'provider' => 'admin',     ], ],    //User Providers 'providers' => [     'user' => [         'driver' => 'eloquent',         'model' => App\User::class,     ],     'admin' => [         'driver' => 'eloquent',         'model' => App\Admin::class,     ] ],    //Resetting Password   'passwords' => [     'clients' => [         'provider' => 'client',         'email' => 'auth.emails.password',         'table' => 'password_resets',         'expire' => 60,     ],     'admins' => [         'provider' => 'admin',         'email' => 'auth.emails.password',         'table' => 'password_resets',         'expire' => 60,     ], ], 

route.php

Route::group(['middleware' => ['web']], function () {     //Login Routes...     Route::get('/admin/login','AdminAuth\AuthController@showLoginForm');     Route::post('/admin/login','AdminAuth\AuthController@login');     Route::get('/admin/logout','AdminAuth\AuthController@logout');      // Registration Routes...     Route::get('admin/register', 'AdminAuth\AuthController@showRegistrationForm');     Route::post('admin/register', 'AdminAuth\AuthController@register');      Route::get('/admin', 'AdminController@index');  });   

AdminAuth/AuthController.php

Add two methods and specify $redirectTo and $guard

protected $redirectTo = '/admin'; protected $guard = 'admin'; public function showLoginForm() {     if (view()->exists('auth.authenticate')) {         return view('auth.authenticate');     }          return view('admin.auth.login');     }      public function showRegistrationForm()     {            return view('admin.auth.register');     }   

it will help you to open another login form for admin

creating a middleware for admin

class RedirectIfNotAdmin {     /**      * Handle an incoming request.      *      * @param  \Illuminate\Http\Request  $request      * @param  \Closure  $next      * @param  string|null  $guard      * @return mixed      */     public function handle($request, Closure $next, $guard = 'admin')     {         if (!Auth::guard($guard)->check()) {             return redirect('/');         }          return $next($request);     } } 

register middleware in kernel.php

 protected $routeMiddleware = [     'admin' => \App\Http\Middleware\RedirectIfNotAdmin::class, ]; 

use this middleware in AdminController e.g.,

namespace App\Http\Controllers;  use Illuminate\Http\Request;  use App\Http\Requests; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\Auth;  class AdminController extends Controller {     public function __construct(){         $this->middleware('admin');    }     public function index(){         return view('admin.dashboard');     } } 

That's all needed to make it working and also to get json of authenticated admin use

Auth::guard('admin')->user() 

We can access authenticated user directly using

Auth::user() but if you have two authentication table then you have to use

Auth::guard('guard_name')->user()   

for logout

Auth::guard('guard_name')->user()->logout() 

for authenticated user json

Auth::guard('guard_name')->user()   

Hope this helps.

Answers 4

I just done this in my project for two tables namely users and admin but you can do the same for more than two table.
Let's have a look

How to create our own AuthServiceProvider for authenticating users from multiple tables

I have two table admin and users

first of create basic login/register route, view and controller for user table by using Laravel 5.2 artisan command.

php artisan make:auth

Lets make a admin table as users table.

Controller For Admin Part
app/Http/Controllers/AdminAuth/AuthController
app/Http/Controllers/AdminAuth/PasswordController
(Just copied these files from app/Http/Controllers/Auth/AuthController here)

config/auth.php

//Authenticating guards 'guards' => [     'user' =>[         'driver' => 'session',         'provider' => 'user',     ],     'admin' => [         'driver' => 'session',         'provider' => 'admin',     ], ],    //User Providers 'providers' => [     'user' => [         'driver' => 'eloquent',         'model' => App\User::class,     ],     'admin' => [         'driver' => 'eloquent',         'model' => App\Admin::class,     ] ],    //Resetting Password   'passwords' => [     'clients' => [         'provider' => 'client',         'email' => 'auth.emails.password',         'table' => 'password_resets',         'expire' => 60,     ],     'admins' => [         'provider' => 'admin',         'email' => 'auth.emails.password',         'table' => 'password_resets',         'expire' => 60,     ], ],   

route.php

Route::group(['middleware' => ['web']], function () {     //Login Routes...     Route::get('/admin/login','AdminAuth\AuthController@loginPage');     Route::post('/admin/login','AdminAuth\AuthController@login');     Route::get('/admin/logout','AdminAuth\AuthController@logout');      // Registration Routes...     Route::get('admin/register', 'AdminAuth\AuthController@registrationPage');     Route::post('admin/register', 'AdminAuth\AuthController@register');      Route::get('/admin', 'AdminController@index');  });   

AdminAuth/AuthController.php

Add two methods and specify $redirectTo and $guard

protected $redirectTo = '/admin'; protected $guard = 'admin'; public function loginPage() {     if (view()->exists('auth.authenticate')) {         return view('auth.authenticate');     }      return view('admin.auth.login'); } public function registrationPage() {     return view('admin.auth.register'); }   

it will help you to open another login form for admin

creating a middleware for admin

class RedirectIfNotAdmin { /**  * Handle an incoming request.  *  * @param  \Illuminate\Http\Request  $request  * @param  \Closure  $next  * @param  string|null  $guard  * @return mixed  */ public function handle($request, Closure $next, $guard = 'admin') {     if (!Auth::guard($guard)->check()) {         return redirect('/');     }      return $next($request); } 

}

register middleware in kernel.php

 protected $routeMiddleware = [     'admin' => \App\Http\Middleware\RedirectIfNotAdmin::class, ]; 

use this middleware in AdminController e.g.,

namespace App\Http\Controllers;  use Illuminate\Http\Request;  use App\Http\Requests; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\Auth;  class AdminController extends Controller {     public function __construct(){         $this->middleware('admin');    } public function index(){         return view('admin.dashboard');     } } 

Authentication
We can access authenticated user directly using
Auth::user() but if you have two authentication table then you have to use

Auth::guard('guard_name')->user()   

Like
Auth::guard('admin')->user()

And also for reference check this https://laracasts.com/discuss/channels/laravel/52-auth-multiple-tables?page=1

Answers 5

First create Admin Authenticatable in Illuminate\Foundation\Auth like

    <?php  namespace Illuminate\Foundation\Auth; use Illuminate\Auth\Authenticatable; use Illuminate\Database\Eloquent\Model; use Illuminate\Auth\Passwords\CanResetPassword; use Illuminate\Foundation\Auth\Access\Authorizable; use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract; use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract; use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;      class Admin extends Model implements         AuthenticatableContract,         AuthorizableContract,         CanResetPasswordContract     {         use Authenticatable, Authorizable, CanResetPassword;     } 

Then create Admin Model by extending Authenticatable Admin Model :-

  <?php namespace App; use Illuminate\Foundation\Auth\Admin as Authenticatable;  class Admin extends Authenticatable {     /**      * The attributes that are mass assignable.      *      * @var array      */     protected $fillable = [         'name', 'email', 'password',     ];      /**      * The attributes that should be hidden for arrays.      *      * @var array      */     protected $hidden = [         'password', 'remember_token',     ]; } 

After that you need to modify config/auth.php like below Add in providers array

'admins' => [             'driver' => 'eloquent',             'model' => App\Admin::class,         ],  

and Add in guards array.

 'user' => [             'driver' => 'session',             'provider' => 'users',         ],  'admin' => [             'driver' => 'session',             'provider' => 'admins',         ], 

Now to authenticate from user table

 if (Auth::guard('user')->attempt(['email' => $email, 'password' => $password])) {         $details = Auth::guard('user')->user();         $user = $details['original'];         return $user;     } else {         return 'auth fail';     } 

Uthenticate from Admin table

 if (Auth::guard('admin')->attempt(['email' => $email, 'password' => $password])) {         $details = Auth::guard('admin')->user();         $user = $details['original'];         return $user;     } else {         return 'auth fail';     } 

Answers 6

Create a model for managers table and admins table. This model should extend Illuminate\Foundation\Auth\User

In config/auth.php,

Add to the providers array:

'managers' => [     'driver' => 'eloquent',     'model' => App\Manager::class,  ], 

Add to the guards array:

'web_manager' => [     'driver' => 'session',     'provider' => 'managers',  ], 

Then. in LoginController (create one for manager using php artisan make:auth) use the trait Illuminate\Foundation\Auth\AuthenticatesUsers and override guard and redirect properties.

protected $redirectTo = 'redirect_path_after_manager_login';  protected function guard() {   return Auth::guard('web_manager'); } 

The manager model is authenticated and you can get the auuthenticated manager's object Auth::guard('web_manager')->user();

Read More

Java: How to make API call with data?

Leave a Comment

I want to make API call similar to below curl command:

curl -X POST -H "Content-Type: application/json" -H "Authorization: Bearer  1djCb/mXV+KtryMxr6i1bXw"  -d '{"operands":[]}'  https://ads.line.me/api/v1.0/authority_delegations/get 

What I am trying

public void send_deligation_request(String details[]) throws Exception{     System.out.println(Arrays.toString(details));      URL line_api_url = new URL("https://ads.line.me/api/v1.0/authority_delegations/get");     String payload = "{operands:[]}";        HttpURLConnection linec = (HttpURLConnection)line_api_url.openConnection();     linec.setDoInput(true);     linec.setDoOutput(true);     linec.setRequestMethod("POST");     linec.setRequestProperty("Content-Type", "application/json");     linec.setRequestProperty("Authorization", "Bearer "+access_token);      OutputStreamWriter writer = new OutputStreamWriter(linec.getOutputStream(), "UTF-8");     writer.write(payload);       BufferedReader in = new BufferedReader(                             new InputStreamReader(                                     linec.getInputStream()));     String inputLine;      while ((inputLine = in.readLine()) != null)          System.out.println(inputLine);     in.close(); } 

But I am getting below error:

[naofumi.haida@torchlight.co.jp, 5514] 
java.io.IOException: Server returned HTTP response code: 400 for URL: https://ads.line.me/api/v1.0/authority_delegations/get   at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1840)   at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1441)   at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:254)   at AuthorityDelegation.send_deligation_request(AuthorityDelegation.java:66)   at AuthorityDelegation.read_csv(AuthorityDelegation.java:36)   at AuthorityDelegation.main(AuthorityDelegation.java:20) 

Could somebody please help me?

5 Answers

Answers 1

HTTP code 400 means a BAD REQUEST.

I can't access the endpoint you have shared but here is free online REST API which I am using for demonstrating ..

curl -X POST \   https://jsonplaceholder.typicode.com/posts \   -H 'cache-control: no-cache' \   -H 'postman-token: 907bbf75-73f5-703f-c8b6-3e1cd674ebf7' \   -d '{         "userId": 100,         "id": 100,         "title": "main title",         "body": "main body"     }' 
  • -H = headers
  • -d = data

Sample Run:

[/c]$ curl -X POST \ >   https://jsonplaceholder.typicode.com/posts \ >   -H 'cache-control: no-cache' \ >   -H 'postman-token: 907bbf75-73f5-703f-c8b6-3e1cd674ebf7' \ >   -d '{ >         "userId": 100, >         "id": 100, >         "title": "main title", >         "body": "main body" >     }'    % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current                                  Dload  Upload   Total   Spent    Left  Speed 100   258  100   150  100   108    147    106  0:00:01  0:00:01 --:--:--   192{   "{\n        \"userId\": 100,\n        \"id\": 100,\n        \"title\": \"main title\",\n        \"body\": \"main body\"\n    }": "",   "id": 101 } 

Java Code for the same is as follows:

OkHttpClient client = new OkHttpClient();  MediaType mediaType = MediaType.parse("application/octet-stream"); RequestBody body = RequestBody.create(mediaType, "{\n        \"userId\": 100,\n        \"id\": 100,\n        \"title\": \"main title\",\n        \"body\": \"main body\"\n    }"); Request request = new Request.Builder()   .url("https://jsonplaceholder.typicode.com/posts")   .post(body)   .addHeader("cache-control", "no-cache")   .addHeader("postman-token", "e11ce033-931a-0419-4903-ab860261a91a")   .build();  Response response = client.newCall(request).execute(); 

Another example of calling REST POST call with data ..

User user = new User(); user.setFirstName("john"); user.setLastName("Maclane");  ResteasyClient client = new ResteasyClientBuilder().build(); ResteasyWebTarget target = client.target("URL"); Response response = target.request().post(Entity.entity(user, <MEDIATYPE>)); //Read output in string format System.out.println(response.getStatus()); response.close();  

Here is the what your code looks like when I update it with my endpoints and payload.

import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.HttpURLConnection; import java.net.URL; import java.util.Arrays;  public class TestClass {      public static final String POST_URL = "https://jsonplaceholder.typicode.com/posts";      public static final String POST_DATA = "{\"userId\": 100,\"id\": 100,\"title\": \"main title\",\"body\": \"main body\"}";      public static void main(String[] args) throws Exception {         String[] details = {};         System.out.println(Arrays.toString(details));          URL line_api_url = new URL(POST_URL);         String payload = POST_DATA;          HttpURLConnection linec = (HttpURLConnection) line_api_url                 .openConnection();         linec.setDoInput(true);         linec.setDoOutput(true);         linec.setRequestMethod("POST");         linec.setRequestProperty("Content-Type", "application/json");         linec.setRequestProperty("Authorization", "Bearer "                 + "1djCb/mXV+KtryMxr6i1bXw");          OutputStreamWriter writer = new OutputStreamWriter(                 linec.getOutputStream(), "UTF-8");         writer.write(payload);          BufferedReader in = new BufferedReader(new InputStreamReader(                 linec.getInputStream()));         String inputLine;          while ((inputLine = in.readLine()) != null)             System.out.println(inputLine);         in.close();     } } 

In nutshell, check the API documentation and ensure the request payload is of correct format as 400 means BAD REQUEST.

Answers 2

It’s a 400 error, which means Bad Request. Please check this link below.

How to find out specifics of 400 Http error in Java?

Answers 3

OutputStreamWriter will buffer the output. After this line in your code:

writer.write(payload); 

add this line

writer.flush(); 

I would expect that to fix your problem.

Answers 4

Though this may not help you with precisely an existing HTTP call using the traditional HttpURLConnection. Yet an interesting way to achieve this in recent times is to use HTTP/2 Client and try out the latest introduced incubator module jdk.incubator.http form Java 9.

An easy way(quick-start) of mocking a POST call using the same is as follows :

  1. Create a within your project and define module-info.java as:

    module http.trial {      requires jdk.incubator.httpclient; } 
  2. Within the module create a package and a class named HttpPost with following content:

    import jdk.incubator.http.HttpRequest; import jdk.incubator.http.HttpClient; import jdk.incubator.http.HttpResponse; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException;  public class HttpPost {    public static void main(String[] args) {      // Request builder     URI uri = null;     try {         uri = new URI("https://ads.line.me/api/v1.0/authority_delegations/get");     } catch (URISyntaxException e) {         e.printStackTrace();     }     HttpRequest.BodyProcessor bodyProcessor = HttpRequest.BodyProcessor.fromString("{\"operands\":[]}");     HttpRequest request = HttpRequest.newBuilder().uri(uri)                     .header("Content-Type", "application/json")                     .header("Authorization", "Bearer 1djCb/mXV+KtryMxr6i1bXw")                     .POST(bodyProcessor)                     .build();      // Client     HttpClient httpClient = HttpClient.newBuilder().followRedirects(HttpClient.Redirect.ALWAYS).build();     System.out.println(httpClient.version());      // Response builder     HttpResponse response = null;     try {         response = httpClient.send(request, HttpResponse.BodyHandler.asString());     } catch (IOException | InterruptedException e) {         e.printStackTrace();     }      System.out.println("StatusCode = " + response.statusCode());     System.out.println("Response = " + response.body().toString());   } } 

Answers 5

Thanks everyone for your help. I used below code to make it work.

public JSONObject send_post() {     HttpClient httpClient = HttpClientBuilder.create().build();     JSONObject jsonObject = null;      try {          HttpPost request = new HttpPost(this.URL + this.object_type + this.request_type);         StringEntity params = null;         if (this.request_type.equals("/get")) {             params = new StringEntity("{\"accountId\":\"5514\"}");         } else if (this.request_type.equals("/set")) {             // params = new             // StringEntity("{\"accountId\":\"5514\",\"operands\":[{\"id\":40151,\"name\":\"ddddd\"}]}");             String output = String.format("{\"accountId\":\"5514\",\"operands\":[{\"id\":%s,\"name\":\"%s\"}]}",                     this.params[0], this.params[1]);             if (this.params[1].equals("OptimizationOff")) {                 output = String.format(                         "{\"accountId\":\"5514\",\"operands\":[{\"id\":%s,\"bidOptimizationType\":\"%s\"}]}",                         this.params[0], "NONE");             } else if (this.params[1].equals("OptimizationOn")) {                 output = String.format(                         "{\"accountId\":\"5514\",\"operands\":[{\"id\":%s,\"bidOptimizationType\":\"%s\",\"bidOptimizationGoal\":\"%s\"}]}",                         this.params[0], this.params[2], this.params[3]);             }             if (object_type.equals("/ads")) {                 output = String.format("{\"accountId\":\"5514\",\"operands\":[{\"id\":%s,\"bidAmount\":\"%s\"}]}",                         this.params[0], this.params[1]);             }             params = new StringEntity(output);         }         request.addHeader("content-type", "application/json");         request.addHeader("Authorization", "Bearer " + this.Access_Token);         request.setEntity(params);          HttpResponse response = httpClient.execute(request);          BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));         StringBuffer result = new StringBuffer();         String line = "";         while ((line = rd.readLine()) != null) {             result.append(line);         }          System.out.println("API Resonse :"+result.toString());         jsonObject = new JSONObject(result.toString());      } catch (Exception ex) {          ex.printStackTrace();      } finally {      }     return jsonObject;  } 
Read More

Solr Index-Time Document Boosts not working

Leave a Comment

I can't find any solid documentation on using index-time document boosts, aside from how set the boost and that omitNorms needs to be set to false on the field types you're querying. I'm really at a loss as to what's happening here. (again -- SIMPLE query, no filters or anything else)

Assuming I do a simple search for title:scissor or even just "scissor", I get back 5 results. If I set a boost of anything between 1.1-1000 on any of these results besides the first result, I would expect this result to have a higher score in the next search.

What's happening to me, however, is that these boosted results are coming back with LOWER scores than before I boosted them, and if I try to boost or negatively boost (0.1-0.9) the top result it NEVER changes position).

For example below, I added a boost of "5" to the fifth result (this is pre-boost):

"explain": {   "File #1": "\n6.312951 = weight(title:scissor in 495641) [ClassicSimilarity], result of:\n  6.312951 = fieldWeight in 495641, product of:\n    1.0 = tf(freq=1.0), with freq of:\n      1.0 = termFreq=1.0\n    12.625902 = idf(docFreq=10, maxDocs=1231567)\n    0.5 = fieldNorm(doc=495641)\n",   "File #2": "\n5.5238323 = weight(title:scissor in 984389) [ClassicSimilarity], result of:\n  5.5238323 = fieldWeight in 984389, product of:\n    1.0 = tf(freq=1.0), with freq of:\n      1.0 = termFreq=1.0\n    12.625902 = idf(docFreq=10, maxDocs=1231567)\n    0.4375 = fieldNorm(doc=984389)\n",   "File #3": "\n5.5238323 = weight(title:scissor in 1098172) [ClassicSimilarity], result of:\n  5.5238323 = fieldWeight in 1098172, product of:\n    1.0 = tf(freq=1.0), with freq of:\n      1.0 = termFreq=1.0\n    12.625902 = idf(docFreq=10, maxDocs=1231567)\n    0.4375 = fieldNorm(doc=1098172)\n",   "File #4": "\n4.7347136 = weight(title:scissor in 901186) [ClassicSimilarity], result of:\n  4.7347136 = fieldWeight in 901186, product of:\n    1.0 = tf(freq=1.0), with freq of:\n      1.0 = termFreq=1.0\n    12.625902 = idf(docFreq=10, maxDocs=1231567)\n    0.375 = fieldNorm(doc=901186)\n",   "File #5": "\n4.7347136 = weight(title:scissor in 1037808) [ClassicSimilarity], result of:\n  4.7347136 = fieldWeight in 1037808, product of:\n    1.0 = tf(freq=1.0), with freq of:\n      1.0 = termFreq=1.0\n    12.625902 = idf(docFreq=10, maxDocs=1231567)\n    0.375 = fieldNorm(doc=1037808)\n",   "File #6": "\n4.7347136 = weight(title:scissor in 1044468) [ClassicSimilarity], result of:\n  4.7347136 = fieldWeight in 1044468, product of:\n    1.0 = tf(freq=1.0), with freq of:\n      1.0 = termFreq=1.0\n    12.625902 = idf(docFreq=10, maxDocs=1231567)\n    0.375 = fieldNorm(doc=1044468)\n",   "File #7": "\n4.4639306 = weight(title:scissor in 972468) [ClassicSimilarity], result of:\n  4.4639306 = fieldWeight in 972468, product of:\n    1.4142135 = tf(freq=2.0), with freq of:\n      2.0 = termFreq=2.0\n    12.625902 = idf(docFreq=10, maxDocs=1231567)\n    0.25 = fieldNorm(doc=972468)\n",   "File #8": "\n3.9455943 = weight(title:scissor in 896318) [ClassicSimilarity], result of:\n  3.9455943 = fieldWeight in 896318, product of:\n    1.0 = tf(freq=1.0), with freq of:\n      1.0 = termFreq=1.0\n    12.625902 = idf(docFreq=10, maxDocs=1231567)\n    0.3125 = fieldNorm(doc=896318)\n",   "File #9": "\n3.9455943 = weight(title:scissor in 1037733) [ClassicSimilarity], result of:\n  3.9455943 = fieldWeight in 1037733, product of:\n    1.0 = tf(freq=1.0), with freq of:\n      1.0 = termFreq=1.0\n    12.625902 = idf(docFreq=10, maxDocs=1231567)\n    0.3125 = fieldNorm(doc=1037733)\n",   "File #10": "\n3.1564755 = weight(title:scissor in 1045578) [ClassicSimilarity], result of:\n  3.1564755 = fieldWeight in 1045578, product of:\n    1.0 = tf(freq=1.0), with freq of:\n      1.0 = termFreq=1.0\n    12.625902 = idf(docFreq=10, maxDocs=1231567)\n    0.25 = fieldNorm(doc=1045578)\n" }, 

And now the fifth result has become the sixth result:

"explain": {   "File #1": "\n6.269446 = weight(title:scissor in 495641) [ClassicSimilarity], result of:\n  6.269446 = fieldWeight in 495641, product of:\n    1.0 = tf(freq=1.0), with freq of:\n      1.0 = termFreq=1.0\n    12.538892 = idf(docFreq=11, maxDocs=1231568)\n    0.5 = fieldNorm(doc=495641)\n",   "File #2": "\n5.485765 = weight(title:scissor in 984389) [ClassicSimilarity], result of:\n  5.485765 = fieldWeight in 984389, product of:\n    1.0 = tf(freq=1.0), with freq of:\n      1.0 = termFreq=1.0\n    12.538892 = idf(docFreq=11, maxDocs=1231568)\n    0.4375 = fieldNorm(doc=984389)\n",   "File #3": "\n5.485765 = weight(title:scissor in 1098172) [ClassicSimilarity], result of:\n  5.485765 = fieldWeight in 1098172, product of:\n    1.0 = tf(freq=1.0), with freq of:\n      1.0 = termFreq=1.0\n    12.538892 = idf(docFreq=11, maxDocs=1231568)\n    0.4375 = fieldNorm(doc=1098172)\n",   "File #4": "\n4.7020845 = weight(title:scissor in 901186) [ClassicSimilarity], result of:\n  4.7020845 = fieldWeight in 901186, product of:\n    1.0 = tf(freq=1.0), with freq of:\n      1.0 = termFreq=1.0\n    12.538892 = idf(docFreq=11, maxDocs=1231568)\n    0.375 = fieldNorm(doc=901186)\n",   "File #6": "\n4.7020845 = weight(title:scissor in 1044468) [ClassicSimilarity], result of:\n  4.7020845 = fieldWeight in 1044468, product of:\n    1.0 = tf(freq=1.0), with freq of:\n      1.0 = termFreq=1.0\n    12.538892 = idf(docFreq=11, maxDocs=1231568)\n    0.375 = fieldNorm(doc=1044468)\n",   "File #5": "\n4.7020845 = weight(title:scissor in 0) [ClassicSimilarity], result of:\n  4.7020845 = fieldWeight in 0, product of:\n    1.0 = tf(freq=1.0), with freq of:\n      1.0 = termFreq=1.0\n    12.538892 = idf(docFreq=11, maxDocs=1231568)\n    0.375 = fieldNorm(doc=0)\n",   "File #7": "\n4.4331675 = weight(title:scissor in 972468) [ClassicSimilarity], result of:\n  4.4331675 = fieldWeight in 972468, product of:\n    1.4142135 = tf(freq=2.0), with freq of:\n      2.0 = termFreq=2.0\n    12.538892 = idf(docFreq=11, maxDocs=1231568)\n    0.25 = fieldNorm(doc=972468)\n",   "File #8": "\n3.9184036 = weight(title:scissor in 896318) [ClassicSimilarity], result of:\n  3.9184036 = fieldWeight in 896318, product of:\n    1.0 = tf(freq=1.0), with freq of:\n      1.0 = termFreq=1.0\n    12.538892 = idf(docFreq=11, maxDocs=1231568)\n    0.3125 = fieldNorm(doc=896318)\n",   "File #9": "\n3.9184036 = weight(title:scissor in 1037733) [ClassicSimilarity], result of:\n  3.9184036 = fieldWeight in 1037733, product of:\n    1.0 = tf(freq=1.0), with freq of:\n      1.0 = termFreq=1.0\n    12.538892 = idf(docFreq=11, maxDocs=1231568)\n    0.3125 = fieldNorm(doc=1037733)\n",   "File #10": "\n3.134723 = weight(title:scissor in 1045578) [ClassicSimilarity], result of:\n  3.134723 = fieldWeight in 1045578, product of:\n    1.0 = tf(freq=1.0), with freq of:\n      1.0 = termFreq=1.0\n    12.538892 = idf(docFreq=11, maxDocs=1231568)\n    0.25 = fieldNorm(doc=1045578)\n" }, 

Specifically, the before/after of the result in question:

"File #5": "\n4.7347136 = weight(title:scissor in 1037808) [ClassicSimilarity], result of:\n  4.7347136 = fieldWeight in 1037808, product of:\n    1.0 = tf(freq=1.0), with freq of:\n      1.0 = termFreq=1.0\n    12.625902 = idf(docFreq=10, maxDocs=1231567)\n    0.375 = fieldNorm(doc=1037808)\n",  "File #5": "\n4.7020845 = weight(title:scissor in 0) [ClassicSimilarity], result of:\n  4.7020845 = fieldWeight in 0, product of:\n    1.0 = tf(freq=1.0), with freq of:\n      1.0 = termFreq=1.0\n    12.538892 = idf(docFreq=11, maxDocs=1231568)\n    0.375 = fieldNorm(doc=0)\n", 

Any assistance in explaining to me what's happening here would be greatly appreciated. I'm at a loss as to why this is happening.

0 Answers

Read More

Tuesday, September 26, 2017

Spotify SDK Missing token refresh service?

Leave a Comment

i am trying to void popup grant permission for user every time session expired in Spotify for SDK , after one hour maybe a popup appear to grant permission again to user so he can play tracks from Spotify on my app , the Error i am getting when try to renew the session :

[PLAYER][PLAY][SPOTIFY] Error renew Session Optional(Error Domain=com.spotify.auth Code=0 "Missing token refresh service." UserInfo={NSLocalizedDescription=Missing token refresh service.}) [PLAYER][SPOTIFY] Session could not be renewed,popup login 

and here how i am trying to renew the session :

//Renew Session func renewSession(completion:@escaping (Bool)->()) {     print("[PLAYER][PLAY][SPOTIFY] Renew Session requested ")      let auth = SPTAuth.defaultInstance()         auth?.renewSession(auth?.session, callback: { (error, session) in              if (error != nil)             {                 print("[PLAYER][PLAY][SPOTIFY] Error renew Session \(String(describing: error))")                 completion(false)                 return             }              auth?.session = session              if auth?.session.isValid() == true             {                 print("[PLAYER][PLAY][SPOTIFY] Renew Session Success")                 completion(true)             }else             {                 print("[PLAYER][PLAY][SPOTIFY] Renew Session Failed")                 completion(false)             }     })  } 

any solution for this ?

1 Answers

Answers 1

Have you assigned these properties on your SPTAuth object?

[SPTAuth defaultInstance].tokenSwapURL = [NSURL URLWithString:@"swapURL"]; [SPTAuth defaultInstance].tokenRefreshURL = [NSURL URLWithString:@"refreshURL"];

Taken from https://github.com/spotify/ios-sdk/issues/427 which might have more info if that isn't sufficient.

There's also a reference for the SPTAuth class:

https://spotify.github.io/ios-sdk/Classes/SPTAuth.html

Read More