GithubHelp home page GithubHelp logo

webbit-rest's Introduction

Webbit-REST

Webbit-REST is a small Sinatra-inspired API for the Webbit web server. It is based on RFC 6570 and the excellent wo-furi library.

Sample usage:

WebServer webServer = new NettyWebServer(9991);
Rest rest = new Rest(webServer);
rest.GET("/people/{name}/pets/{petName}", new HttpHandler() {
    @Override
    public void handleHttpRequest(HttpRequest req, HttpResponse res, HttpControl ctl) {
        String name = Rest.param(req, "name");
        String petName = Rest.param(req, "petName");
        res.content(String.format("Name: %s\nPet: %s\n", name, petName)).end();
    }
});
webServer.start().get();
System.out.println("Try this: curl -i localhost:9991/people/Mickey/pets/Pluto");

Redirecting:

rest.GET("/people/{name}/animals/{petName}", new HttpHandler() {
    @Override
    public void handleHttpRequest(HttpRequest req, HttpResponse res, HttpControl ctl) {
        Rest.redirect(res, "/people/{name}/pets/{petName}",
                "name", param(req, "name"),
                "petName", param(req, "petName")
        );
    }
});

Installation

Maven

<dependency>
    <groupId>org.webbitserver</groupId>
    <artifactId>webbit-rest</artifactId>
    <version>0.2.0</version>
</dependency>

Not Maven

https://oss.sonatype.org/content/repositories/releases/org/webbitserver/webbit-rest/0.2.0/webbit-rest-0.2.0.jar

webbit-rest's People

Contributors

aslakhellesoy avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

webbit-rest's Issues

OPTIONS HTTP Verb handling

In order to implement CORS one need to handle OPTIONS HTTP Verb.

Is that possible to handle OPTIONS natively.

webbit-rest 0.3.0 with webbitserver 0.4.12 SocketException: Unexpected end of file from server

Every 5-7 days my rest client keeps getting "SocketException: Unexpected end of file from server". At times I can also reproduce this issue by hitting the REST URL using a web browser (Chrome returns Unable to load the webpage because the server sent no data.Error code: ERR_EMPTY_RESPONSE). Some basic googling shows this error typically means that the Content-Length header is not set. Is this a known issue? Should I file a defect against webbitserver rather than webbit-rest?

My webbit-rest app is super simple, supporting just 1 URI.

CoverityProxy.java

package com.somecompany.somepkg;

import java.util.concurrent.ExecutionException;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;

import javax.security.auth.callback.CallbackHandler;

import org.webbitserver.WebServer;
import org.webbitserver.netty.NettyWebServer;
import org.webbitserver.rest.Rest;

/**
 * <p>
 * A RESTful web service intended to sit in
 * front of Coverity Connect so that Groovy/Java clients
 * don't have to deal with JAX-WS.
 * 
 */
public class CoverityProxy {    

    private static final Logger LOG = Logger.getLogger(CoverityIssuesByImpactHttpHandler.class.getName());

    static {
        LOG.setLevel(Level.ALL) ;
    }   

    /**
     * The actual URI Template is specified {@link CoverityIssuesByImpactHttpHandler#ISSUES_BY_IMPACT_URI_TEMPLATE}.
     */
    private static final String EXAMPLE_URL = "Try this: curl -i localhost:9991/coverity-proxy/projects/JenkinsMaxviewStreams/issues?impact=High";

    private CallbackHandler authnHandler ;

    private WebServer server;


    private CoverityProxy(CallbackHandler authnHandler) {
        super();
        this.authnHandler = authnHandler;
    }

    /**
     * <p>
     * Requires <i>user</i> and <i>password</i> arguments.  Password should be in clear text.
     */ 
    public static void main(String[] args) throws InterruptedException, ExecutionException  
    {
        // The root logger's handlers default to INFO. We have to
        // crank them up. We could crank up only some of them
        // if we wanted, but we will turn them all up.
        java.util.logging.Handler[] handlers = Logger.getLogger("")
                .getHandlers();

        for (int index = 0; index < handlers.length; index++)
        {
            handlers[index].setLevel(Level.ALL);
        }

        CallbackHandler authnHandler = new AuthnCallbackHandler(args[0], args[1]);      
        CoverityProxy proxy = new CoverityProxy(authnHandler);
        proxy.start();

        ShutdownCoverityProxy shutdownThread = new ShutdownCoverityProxy(proxy);
        Runtime.getRuntime().addShutdownHook(new Thread(shutdownThread));
    }

    void start()
    throws InterruptedException, ExecutionException
    {
        WebServer webServer = new NettyWebServer(9991);
        Rest rest = new Rest(webServer);
        rest.GET(CoverityIssuesByImpactHttpHandler.ISSUES_BY_IMPACT_URI_TEMPLATE, new CoverityIssuesByImpactHttpHandler(authnHandler));

        server = webServer.start().get();

        System.out
                .println(EXAMPLE_URL);

    }

    void stop()
    throws InterruptedException, ExecutionException
    {
        server.stop().get();
    }

    private static final class ShutdownCoverityProxy implements Runnable
    {
        private CoverityProxy coverityProxy ;

        private ShutdownCoverityProxy(CoverityProxy coverityProxy) {
            super();
            this.coverityProxy = coverityProxy;
        }

        public void run() 
        {
            LOG.fine("Shutdown hook was invoked. Shutting down App1.");
            try {
                coverityProxy.stop();
            } catch (Exception e) {
                LogRecord lr = new LogRecord(Level.SEVERE, "THROW");
                lr.setMessage("problem checking shutting down CoverityProxy");
                lr.setSourceClassName(ShutdownCoverityProxy.class.getName());
                lr.setSourceMethodName("stopCoverityProxy");
                lr.setThrown(e);
                LOG.log(lr);
            }
        }       
    }

}

CoverityIssuesByImpactHttpHandler.java

package com.somecompany.somepkg;

import java.io.Closeable;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;

import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.NameCallback;

import org.apache.cxf.endpoint.Client;
import org.apache.cxf.frontend.ClientProxy;
import org.apache.cxf.ws.security.wss4j.WSS4JOutInterceptor;
import org.apache.ws.security.WSConstants;
import org.apache.ws.security.handler.WSHandlerConstants;
import org.webbitserver.HttpControl;
import org.webbitserver.HttpHandler;
import org.webbitserver.HttpRequest;
import org.webbitserver.HttpResponse;
import org.webbitserver.rest.Rest;

import com.coverity.ws.v6.ConfigurationService;
import com.coverity.ws.v6.ConfigurationServiceService;
import com.coverity.ws.v6.DefectService;
import com.coverity.ws.v6.DefectServiceService;

/**
 * Handles REST requests for ISSUES_BY_IMPACT_URI_TEMPLATE. 
 * @author Administrator
 *
 */
final class CoverityIssuesByImpactHttpHandler implements HttpHandler
{
    private static final Logger LOG = Logger.getLogger(CoverityIssuesByImpactHttpHandler.class.getName());

    static {
        LOG.setLevel(Level.ALL) ;
    }

    private CallbackHandler authnCallback ;
    /**
     * <p>
     * URI Template for Coverity issues filtered by Impact.
     * 
     * <p>
     * URI Templates are specified in the "Internet Engineering Task Force Request for Comments 6570 URI Template".
     * 
     * @see http://dev.pageseeder.com/glossary/URI_Pattern.html
     * @see http://tools.ietf.org/html/rfc6570
     * @see http://www.weborganic.org/furi.html
     * @see http://code.google.com/p/wo-furi/
     * @see http://dev.pageseeder.com/glossary.html
     */
    static final String ISSUES_BY_IMPACT_URI_TEMPLATE = "/coverity-proxy/projects/{projectName}/issues/impacts/{impact}";


    public CoverityIssuesByImpactHttpHandler(CallbackHandler anAuthnCallback) {
        super();
        this.authnCallback = anAuthnCallback ;
    }

    public void handleHttpRequest(HttpRequest req, HttpResponse res, HttpControl control)
    throws Exception
    {
        Object projectName = Rest.param(req, "projectName");
        Object impact = Rest.param(req, "impact");

        Client configClient = null;
        Client defectClient = null;
        try
        {
            NameCallback userCallback = new NameCallback("Enter Coverity Connect user:");
            authnCallback.handle( new NameCallback[] {userCallback} );
            String user = userCallback.getName();

            Map<String, Object> outProps = new HashMap<String, Object>();
            outProps.put(WSHandlerConstants.ACTION, WSHandlerConstants.USERNAME_TOKEN + " " + WSHandlerConstants.TIMESTAMP);
            outProps.put(WSHandlerConstants.PASSWORD_TYPE, WSConstants.PW_TEXT);            
            outProps.put(WSHandlerConstants.USER, user);
            outProps.put(WSHandlerConstants.PW_CALLBACK_REF, authnCallback);

            ConfigurationService configurationServicePort = null;
            DefectService defectServicePort = null;
            try
            {
                ConfigurationServiceService configurationServiceService = new ConfigurationServiceService(new URL("http://192.168.180.3:8081/ws/v6/configurationservice?wsdl"));
                configurationServicePort = configurationServiceService.getConfigurationServicePort();
                configClient = ClientProxy.getClient(configurationServicePort) ;
                org.apache.cxf.endpoint.Endpoint configEndpoint = configClient.getEndpoint();
                configEndpoint.getOutInterceptors().add(new WSS4JOutInterceptor(outProps));

                DefectServiceService defectServiceService = new DefectServiceService(new URL("http://192.168.180.3:8081/ws/v6/defectservice?wsdl"));
                defectServicePort = defectServiceService.getDefectServicePort();
                defectClient = ClientProxy.getClient(defectServicePort);
                org.apache.cxf.endpoint.Endpoint defectEndpoint = defectClient.getEndpoint();
                defectEndpoint.getOutInterceptors().add(new WSS4JOutInterceptor(outProps));

                CoverityWebserviceClient coverity = new CoverityWebserviceClient(configurationServicePort,
                        defectServicePort);

                List<Long> issues = coverity.getIssuesByImpact( String.valueOf(projectName), String.valueOf(impact) );

                coverity = null;

                res.content(String.format("%d", issues.size())).end();

            }
            catch (Exception e)
            {
                LogRecord lr = new LogRecord(Level.SEVERE, "THROW");
                lr.setMessage("problem checking metrics");
                lr.setSourceClassName(this.getClass().getName());
                lr.setSourceMethodName("handleHttpRequest");
                lr.setThrown(e);
                LOG.log(lr);

                // Also re-throw it so that the Jenkins groovy-post-build plugin
                // Will know we failed

                throw e;
            }
            finally
            {
                try
                {
                    if (configurationServicePort instanceof Closeable)
                    {
                        ((Closeable) configurationServicePort).close();
                    }
                }
                finally
                {
                    if (defectServicePort instanceof Closeable)
                    {
                        ((Closeable) defectServicePort).close();
                    }
                }
            }
        }
        finally
        {
            try
            {
                if (null != configClient)
                {
                    configClient.destroy();
                }
            }
            finally
            {            
                if (null != defectClient)
                {
                    defectClient.destroy();
                }            
            }
        }
    }
}

Here are the webbit artifact versions...

        <groupId>org.webbitserver</groupId>
        <artifactId>webbit</artifactId>
        <version>0.4.12</version>
        <scope>compile</scope>

        <groupId>org.webbitserver</groupId>
        <artifactId>webbit-rest</artifactId>
        <version>0.3.0</version>
        <scope>compile</scope>

Add querystrings / RFC 6570 Form-Style Query Expansion support to permit search URLs

I wanted to build a RESTful service which has a URL with a RFC 6570 Query Expansion portion like

/projects/{projectName}/issues{?impact}

Where an example URL might be

http://localhost:9991/project/someproject/issues?impact=High

This URL design is typical for searches e.g. http://stackoverflow.com/questions/207477/restful-url-design-for-search

Regrettably, the 0.3.0 webbit-rest implementation precludes this URL design because of this line of code

    String path = URI.create(request.uri()).getPath();

in org.webbitserver.rest.UriTemplateHandler#handleHttpRequest. By calling getPath(), it causes org.weborganic.furi.URIResolver#resolve to detect a mismatch betwen the matches group count and the pattern tokens.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.