smallseo.info

grape

An opinionated micro-framework for creating REST-like APIs in Ruby. Ruby Grape | An opinionated micro-framework for creating REST-like APIs in Ruby.

Intellij IDEA not importing dependencies from @Grab in Groovy project

I have a groovy script I am working on, which imports dependencies using the @Grab annotation. This script will run within IDEA, and from the command line. However, within the IDE, the imports are shown in red (as unresolvable), and no auto-completion on the classes so imported is given.

I am accessing a corporate repository via a proxy, which has been configured as the Http Proxy within IDEA (the module should be, and is, in my local .m2 repo anyway!)

Anyone got any ideas (no pun intended!)?

I am using IntelliJ IDEA 12.5 Ultimate (IU-129.1135), JRE 1.7, and Groovy 2.1.6


Source: (StackOverflow)

Getting Groovy's Grape Going!

I've tried to use the new Groovy Grape capability in Groovy 1.6-beta-2 but I get an error message;

unable to resolve class com.jidesoft.swing.JideSplitButton

from the Groovy Console (/opt/groovy/groovy-1.6-beta-2/bin/groovyConsole) when running the stock example;

import com.jidesoft.swing.JideSplitButton
@Grab(group='com.jidesoft', module='jide-oss', version='[2.2.1,)')
public class TestClassAnnotation {
    public static String testMethod () {
        return JideSplitButton.class.name
    }
}

I even tried running the grape command line tool to ensure the library is imported. Like this;

 $ /opt/groovy/groovy-1.6-beta-2/bin/grape install com.jidesoft jide-oss

which does install the library just fine. How do I get the code to run/compile correctly from the groovyConsole?


Source: (StackOverflow)

groovy grape verbose

Is there a way to print Ivy output when using Groovy Grape.

when I use Grape, it's just hanging there till finishes downloading all dependencies. I would like to know what it's happening and what it's downloading.

Thanks,


Source: (StackOverflow)

User Authentication with Grape and Devise

I have difficulties to understand and also properly implement User Authentication in APIs. In other words, I have serious problem to understand the integration of Grape API with front-end frameworks such as Backbone.js, AngularJS or Ember.js.

I'm trying to pivot all different approaches and read a lot about that, but Google returns me truly bad resources and it seems to me, like there is no really good article on this topic - Rails and User authentication with Devise and front-end frameworks.

I will describe my current pivot and I hope you can provide me some feedback on my implementation and maybe point me to the right direction.

Current implementation

I have backend Rails REST API with following Gemfile(I will purposely shorten all file code)

gem 'rails', '4.1.6'
gem 'mongoid', '~> 4.0.0'
gem 'devise'
gem 'grape'
gem 'rack-cors', :require => 'rack/cors'

My current implementation has only APIs with following Routes(routes.rb):

api_base      /api        API::Base
     GET        /:version/posts(.:format)
     GET        /:version/posts/:id(.:format)
     POST       /:version/posts(.:format)
     DELETE     /:version/posts/:id(.:format)
     POST       /:version/users/authenticate(.:format)
     POST       /:version/users/register(.:format)
     DELETE     /:version/users/logout(.:format)

I created have following model user.rb

class User
  include Mongoid::Document
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  field :email,              type: String, default: ""
  field :encrypted_password, type: String, default: ""

  field :authentication_token,  type: String

  before_save :ensure_authentication_token!

  def ensure_authentication_token!
    self.authentication_token ||= generate_authentication_token
  end

  private

  def generate_authentication_token
    loop do
      token = Devise.friendly_token
      break token unless User.where(authentication_token: token).first
    end
  end   
end

In my controllers I created following folder structure: controllers->api->v1 and I have created following shared module Authentication (authentication.rb)

module API
  module V1
    module Authentication
      extend ActiveSupport::Concern

      included do
        before do
           error!("401 Unauthorized", 401) unless authenticated?
         end

         helpers do
           def warden
             env['warden']
           end

           def authenticated?
             return true if warden.authenticated?
             params[:access_token] && @user = User.find_by(authentication_token: params[:access_token])
           end

           def current_user
             warden.user || @user
           end
         end
       end
     end
   end
end

So every time when I want to ensure, that my resource will be called with Authentication Token, I can simply add this by calling: include API::V1::Authentication to the Grape resource:

module API
  module V1
    class Posts < Grape::API
      include API::V1::Defaults
      include API::V1::Authentication

Now I have another Grape resource called Users(users.rb) and here I implement methods for authentication, registration and logout.(I think that I mix here apples with pears, and I should extract the login/logout process to another Grape resource - Session).

module API
  module V1
    class Users < Grape::API
      include API::V1::Defaults

      resources :users do
        desc "Authenticate user and return user object, access token"
        params do
           requires :email, :type => String, :desc => "User email"
           requires :password, :type => String, :desc => "User password"
         end
         post 'authenticate' do
           email = params[:email]
           password = params[:password]

           if email.nil? or password.nil?
             error!({:error_code => 404, :error_message => "Invalid email or password."}, 401)
             return
           end

           user = User.find_by(email: email.downcase)
           if user.nil?
              error!({:error_code => 404, :error_message => "Invalid email or password."}, 401)
              return
           end

           if !user.valid_password?(password)
              error!({:error_code => 404, :error_message => "Invalid email or password."}, 401)
              return
           else
             user.ensure_authentication_token!
             user.save
             status(201){status: 'ok', token: user.authentication_token }
           end
         end

         desc "Register user and return user object, access token"
         params do
            requires :first_name, :type => String, :desc => "First Name"
            requires :last_name, :type => String, :desc => "Last Name"
            requires :email, :type => String, :desc => "Email"
            requires :password, :type => String, :desc => "Password"
          end
          post 'register' do
            user = User.new(
              first_name: params[:first_name],
              last_name:  params[:last_name],
              password:   params[:password],
              email:      params[:email]
            )

            if user.valid?
              user.save
              return user
            else
              error!({:error_code => 404, :error_message => "Invalid email or password."}, 401)
            end
          end

          desc "Logout user and return user object, access token"
           params do
              requires :token, :type => String, :desc => "Authenticaiton Token"
            end
            delete 'logout' do

              user = User.find_by(authentication_token: params[:token])

              if !user.nil?
                user.remove_authentication_token!
                status(200)
                {
                  status: 'ok',
                  token: user.authentication_token
                }
              else
                error!({:error_code => 404, :error_message => "Invalid token."}, 401)
              end
            end
      end
    end
  end
end

I realize that I present here a ton of code and it might not make sense, but this is what I currently have and I'm able to use the authentication_token for calls against my API which are protected by module Authentication.

I feel like this solution is not good, but I really looking for easier way how to achieve user authentication through APIs. I have several questions which I listed below.

Questions

  1. Do you think this kind of implementation is dangerous, if so, why? - I think that it is, because of the usage of one token. Is there a way how to improve this pattern? I've also seen implementation with separate model Token which has expiration time, etc. But I think this is almost like reinventing wheel, because for this purpose I can implement OAuth2. I would like to have lighter solution.
  2. It is good practice to create new module for Authentication and include it only into resources where it is needed?
  3. Do you know about any good tutorial on this topic - implementing Rails + Devise + Grape? Additionally, do you know about any good open-source Rails project, which is implemented this way?
  4. How can I implement it with different approach which is more safer?

I apologize for such a long post, but I hope that more people has the same problem and it might help me to find more answers on my questions.


Source: (StackOverflow)

Error compiling a Groovy project using @Grab annotation

I'm compiling a Groovy project with Gradle, but I've noticed that when I use the @Grab annotation in my code, I get the following error:

$ gradle compile
:buildInfo
:compileJava UP-TO-DATE
:compileGroovy FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':compileGroovy'.
> org/apache/ivy/core/report/ResolveReport

(full stack trace here http://pastebin.com/0ty4jNct)

I've found out that the only way to get it working is to add the 'groovy' and 'ivy' module to the groovy classpath, but I would like to avoid this, since the groovy classpath is deprecated.

Is this a Gradle bug? or there's a better way to manage the @Grab dependency?


Source: (StackOverflow)

grape doesn't work in Eclipse

groovy eclipse plugin version: 1.7.5.xx-20101020-1000-e36-release.

import com.jidesoft.swing.JideSplitButton

@Grab(group='com.jidesoft', module='jide-oss', version='[2.2.1,2.3.0)')
public class TestClassAnnotation {
    public static String testMethod () {
        return JideSplitButton.class.name
    }
}

new TestClassAnnotation().testMethod()

the first line error: Groovy:unable to resolve class com.jidesoft.swing.JideSplitButton

it can run as groovy shell, but the error warning is bore


Source: (StackOverflow)

RestSharp Accept header change

I am using RestSharp for developing client side. Also I am using Ruby Grape gem for my custom API on server side. Grape gem can do versioning by setting Accept HTTP header f.e to application/vnd.twitter-v1+json

And test command via console works perfect curl -H Accept=application/vnd.twitter-v1+json /statuses/public_timeline

But when I am trying to set up header for RestRequest I am getting error 404 on the server. I have no ideas why so. I have found another issue that server returns 406 error - but in my case 404.

How can I put custom value for Accept header?


Source: (StackOverflow)

Why am I getting "Unable to autoload constant" with Rails and grape?

I want to do an API for an Android app. When searching, I found {grape}. I'm following this tutorial, but I have a problem launching the Rails server:

=> Booting WEBrick
=> Rails 4.0.2 application starting in development on http://0.0.0.0:80
=> Run `rails server -h` for more startup options
=> Ctrl-C to shutdown server
Exiting
C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/activesupport-4.0.2/lib/act
ive_support/dependencies.rb:464:in `load_missing_constant': Unable to autoload c
onstant Usuarios, expected C:/Sites/appCerca/app/api/v1/usuarios.rb to define it
 (LoadError)

My directory:

app
..api
....api.rb
....v1
......root.rb
......usuarios.rb

and the files:

#application.rb
module AppCerca
  class Application < Rails::Application
      config.paths.add "app/api", glob: "**/*.rb"
       config.autoload_paths += Dir["#{Rails.root}/app/api/*"]
  end
end

#routes.rb
AppCerca::Application.routes.draw do
  mount API::Root => '/'
  [...]

#app/api/root.rb
module API
    class Root < Grape::API
        prefix 'api'
        mount API::V1::Root
    end
end

# app/api/v1/root.rb
module API
    module V1
        class Root < Grape::API
            mount API::V1::Usuarios
        end
    end
end

# app/api/v1/usuarios.rb
module API
    module V1
        class Usuarios < Grape::API
            version 'v1'
            format :json

            resource :usuarios do
                desc "Return list of authors"
                get do
                    Usuario.all
                end
            end
        end
    end
end

Why am I getting this error? I am using Ruby 1.9.3p484 and Rails-4.0.2.


Source: (StackOverflow)

Groovy with Grape and AntBuilder classloader problem

I wanted to use groovy for a little ftp script and found this post http://www.hhhhq.org/blog/2009/05/01/ftp-using-groovy-and-ant/ Since there were several dependencies I wanted to use Grape. All dependencies are resolved and present in the cache. But I can't get Ant to find the optional tasks in the other libs. It always says

Caught: : Problem: failed to create task or type ftp
Cause: the class org.apache.tools.ant.taskdefs.optional.net.FTP was not found.
        This looks like one of Ant's optional components.
Action: Check that the appropriate optional JAR exists in
        -ANT_HOME\lib
        -the IDE Ant configuration dialogs

Do not panic, this is a common problem.
The commonest cause is a missing JAR.

This is not a bug; it is a configuration problem

        at GrabTest.runMe(GrabTest.groovy:15)
        at GrabTest.run(GrabTest.groovy:26)

Groovy Version: 1.6.5 JVM: 1.6.0_15

Here is my source code

@Grab(group='ant', module='ant', version='[1.6.5,)')
@Grab(group='ant', module='ant-nodeps', version='[1.0,)')
@Grab(group='ant', module='ant-apache-oro', version='[1.0,)') 
@Grab(group='ant', module='ant-commons-net', version='[1.0,)') 
@Grab(group='apache-oro', module='jakarta-oro', version='[2.0.8,)')
@Grab(group='commons-net', module='commons-net', version='[1.4,)')
def runMe() {
    // works
    println getClass().getClassLoader().loadClass("org.apache.tools.ant.taskdefs.optional.net.FTP")

    def ant = new AntBuilder()

    println getClass().getClassLoader() //groovy.lang.GroovyClassLoader$InnerLoader
    println ant.getClass().getClassLoader() //org.codehaus.groovy.tools.RootLoader
    ant.ftp( server:"ftp.foo.com",
            userid:"user",
            password:"passwd",
            passive:"yes",
            verbose:"yes",
            remotedir:"/pub/incoming",
            binary:"yes" ) {
                fileset( dir:"." ) { include( name:"**/*.gz" ) }
            }
}

runMe()

As you can see I suspect the classloader of being the problem, it seems that Grape doesn't inject the dependencies there. Any idea of how I can get it to work?


Source: (StackOverflow)

Make groovy script grab a jar off the filesystem like grape

Grape seems to work fairly well for adding jars to your classpath. It also does a lot of other things such as fetching and dependency management. e.g.

#!/home/robert/bin/groovy

import org.apache.commons.lang.StringUtils

@Grab(group='commons-lang', module='commons-lang', version='2.4')

def strings = ['Hello', 'Groovy', 'AVeryLongWord!', 'A simple sentence']
strings.each { String aString ->
    println "$aString: ${StringUtils.abbreviate(aString,10)}"
}

Unfortunately if there is a jar on my filesystem that I want to dynamically add to the filesystem then I have to resort to a much uglier solution.

#!/home/robert/bin/groovy

def loader = this.class.classLoader.rootLoader
loader.addURL(new File("/home/robert/somejars/arithmetic-1.1.jar").toURI().toURL())

// can't use traditional package import
arithmeticMainClass = Class.forName("org.scharp.arithmetic.Main")

println "42 - 23 = " + arithmeticMainClass.subtract(42, 23)

// can't use "new" operator
myArithmeticObject = arithmeticMainClass.newInstance()

Is there a way to make grape grab a jar from the filesystem? If not, can I somehow replicate what grape is doing in groovy/java?

I would like this solution to work for scripts that can be run by many users and many incompatible jars so adding jars to a common directory such as ~/.groovy/lib/ won't work.

I could create a local maven repository for local, jar libaries but that seems like overkill.


Source: (StackOverflow)

Groovy: How does @Grab inclusion differ from classpath inclusion?

1. Generally, how is @Grape/@Grab inclusion different than classpath inclusion?

2. Specifically, what might cause the following behavior difference?

I've got a requirement on xpp3 which I express as:

// TestScript.groovy
@Grab(group='xpp3', module='xpp3', version='1.1.3.4.O')
import org.xmlpull.v1.XmlPullParserFactory;
println "Created: " + XmlPullParserFactory.newInstance()

Running $ groovy TestScript.groovy fails with

Caught: org.xmlpull.v1.XmlPullParserException: caused by: org.xmlpull.v1.XmlPullParserException:

If, however, I manually add the .jar fetched by Grape to my Groovy classpath:

$ groovy -cp ~/.groovy/grapes/xpp3/xpp3/jars/xpp3-1.1.3.4.O.jar \
         TestScript.groovy 

... then everything works.


Source: (StackOverflow)

Ruby Grape JSON-over-HTTP API, custom JSON representation

I have a small prototype subclass of Grape::API as a rack service, and am using Grape::Entity to present my application's internal objects.

I like the Grape::Entity DSL, but am having trouble finding out how I should go beyond the default JSON representation, which is too lightweight for our purposes. I have been asked to produce output in "jsend or similar" format: http://labs.omniti.com/labs/jsend

I am not at all sure what nature of change is most in keeping with the Grape framework (I'd like a path-of-least-resistance here). Should I create a custom Grape formatter (I have no idea how to do this), new rack middleware (I have done this in order to log API ins/outs via SysLog - but formatting seems bad as I'd need to parse the body back from JSON to add container level), or change away from Grape::Entity to e.g. RABL?

Example code ("app.rb")

require "grape"
require "grape-entity"

class Thing
  def initialize llama_name
    @llama_name = llama_name
  end
  attr_reader :llama_name
end

class ThingPresenter < Grape::Entity
  expose :llama_name
end

class MainService < Grape::API
  prefix      'api'
  version     'v2'
  format      :json
  rescue_from :all

  resource :thing do
    get do
      thing = Thing.new 'Henry'
      present thing, :with => ThingPresenter
    end
  end
end

Rackup file ("config.ru")

require File.join(File.dirname(__FILE__), "app")
run MainService

I start it up:

rackup -p 8090

And call it:

curl http://127.0.0.1:8090/api/v2/thing
{"llama_name":"Henry"}

What I'd like to see:

curl http://127.0.0.1:8090/api/v2/thing
{"status":"success","data":{"llama_name":"Henry"}}

Obviously I could just do something like

  resource :thing do
    get do
      thing = Thing.new 'Henry'
      { :status => "success", :data => present( thing, :with => ThingPresenter ) }
    end
  end

in every route - but that doesn't seem very DRY. I'm looking for something cleaner, and less open to cut&paste errors when this API becomes larger and maintained by the whole team


Weirdly, when I tried { :status => "success", :data => present( thing, :with => ThingPresenter ) } using grape 0.3.2, I could not get it to work. The API returned just the value from present - there is more going on here than I initially thought.


Source: (StackOverflow)

Groovy 1.8 @Grab fails unless I manually call grape resolve

When running a script that is using grape system to @Grab a dependency in the ibiblio repo, it fails till I manually call grape resolve from the command line. After that, it's in the local cache and the script runs fine.

Is there some other annotation that I need to use to get it to work the first time from the script? It feels kludgy to tell users to first "grape resolve" and then @Grab works.

This is the script, grabbing the jedis jar for redis:

#!/usr/bin/env groovy
@Grab('redis.clients:jedis:2.0.0')

import redis.clients.jedis.*

Jedis redis = new Jedis("localhost")

Which fails with this exception if I have a clean ~/.groovy/grapes cache:

org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
General error during conversion: Error grabbing Grapes -- [unresolved dependency: redis.clients#jedis;2.0.0: ibiblio: unable to get resource for redis/clients#jedis;2.0.0: res=/redis/clients/jedis/2.0.0/jedis-2.0.0.pom: java.net.MalformedURLException: no protocol:  /redis/clients/jedis/2.0.0/jedis-2.0.0.pom]

It only runs once I execute grape resolve manually from the command line:

grape -V resolve redis.clients jedis 2.0.0

(part of the output shows it's downloading from ibiblio):

...
ibiblio: found md file for redis.clients#jedis;2.0.0
    => http://repo1.maven.org/maven2/redis/clients/jedis/2.0.0/jedis-2.0.0.pom (2.0.0)
downloading http://repo1.maven.org/maven2/redis/clients/jedis/2.0.0/jedis-2.0.0.pom ...
    ibiblio: downloading http://repo1.maven.org/maven2/redis/clients/jedis/2.0.0/jedis-2.0.0.pom
    ibiblio: downloading http://repo1.maven.org/maven2/redis/clients/jedis/2.0.0/jedis-2.0.0.pom.sha1
sha1 OK for http://repo1.maven.org/maven2/redis/clients/jedis/2.0.0/jedis-2.0.0.pom
    [SUCCESSFUL ] redis.clients#jedis;2.0.0!jedis.pom(pom.original) (1184ms)
...

After it's in the local cache, the script works fine with @Grab.

I have not manually added a ~/.groovy/grapeConfig.xml file so it's using the default one that comes with groovy. I'm using groovy 1.8:

groovy -v
Groovy Version: 1.8.0 JVM: 1.6.0_24

I tried adding this manually above the grab:

@GrabResolver(name='ibiblio', m2Compatible='true', root='http://repo1.maven.org/maven2/')

but that didn't help. Am I missing something?


Source: (StackOverflow)

how to get the remote ip (requester) on grape-api rails application

I have a working rails application with grape-gem working as an end point for some APIs in the application. I need to get the remote ip for the requester and return it back in the response. I could do that on regular controllers using

request.remote_ip

however, in grape calls, the 'request' is not a defined variable.

how can I get access to the remote ip on grape?


Source: (StackOverflow)

grape-entity represent not working

I am using grape gem for API and grape-entity to generate responses.

Simple show/get request is responding fine like returning only data from ActiveRecord Object. Fine

When i try to include data from has_many relation it return all the data related to that object. Fine

But when I represent data like

post = Post.first
data = V1::Entities::PostEntities.represent(post, only: [:id, { comments: [:id, :body] }])
data.as_json

It should return something like this as per documentation:

{
  id: 1,
  comments: [{
    id: 1,
    body: 'example'
  }]
}

But it returns:

{
  id: 1,
  comments: [{
    id: 1,
    user_id: 1,
    body: 'example',
    created_at: 'some_timestamp',
    updated_at: 'also_some_timestamp',
    is_deleted: 0,
  }]
}

My PostEntities contains:

module V1
  module Entities
    class PostEntities < Grape::Entity
      expose :id
      expose :comments, with: V1::Entities::CommentEntities
    end
  end
end

My CommentEntities contains:

module V1
  module Entities
    class CommentEntities < Grape::Entity
      expose :id
      expose :user_id
      expose :body
      expose :created_at
      expose :updated_at
      expose :is_deleted
    end
  end
end

there is something wrong with represent method. i am not getting what the issue is?


Source: (StackOverflow)