Java Code Examples for org.restlet.Response

The following are top voted examples for showing how to use org.restlet.Response. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: fresco_floodlight   File: RestApiServer.java   Source Code and License 7 votes vote down vote up
@Override
public Restlet createInboundRoot() {
	Router baseRouter = new Router(context);
	baseRouter.setDefaultMatchingMode(Template.MODE_STARTS_WITH);
	for (RestletRoutable rr : restlets) {
		baseRouter.attach(rr.basePath(), rr.getRestlet(context));
	}

	Filter slashFilter = new Filter() {            
		@Override
		protected int beforeHandle(Request request, Response response) {
			Reference ref = request.getResourceRef();
			String originalPath = ref.getPath();
			if (originalPath.contains("//"))
			{
				String newPath = originalPath.replaceAll("/+", "/");
				ref.setPath(newPath);
			}
			return Filter.CONTINUE;
		}

	};
	slashFilter.setNext(baseRouter);

	return slashFilter;
}
 
Example 2
Project: FFS-Api   File: AuthAggregator.java   Source Code and License 6 votes vote down vote up
@Override
protected boolean authorize(Request request, Response response) {
	if (request.getMethod() == Method.OPTIONS) return true;

	if (request.getAttributes().get("account") != null) return true;
	
	String accessToken = request.getHeaders().getFirstValue(HttpHeaders.AUTHORIZATION);
	if (accessToken == null) return true;
	
	try {
		accessToken.replace("OAuth ", "");
		AccountBean acc = mAccounts.getAccountFromToken(accessToken);
	    if (acc != null) {
	    	request.getAttributes().put("account", acc);
	    	return true;
	    }
	} catch (Exception e) {
		Main.LOGGER.log(Level.WARNING, "Error while handling OAuth authentification", e);
		return false;
	}
    
	return false;
}
 
Example 3
Project: FFS-Api   File: OAuthVerifier.java   Source Code and License 6 votes vote down vote up
@Override
public int verify(Request request, Response response) {
	if (request.getMethod() == Method.OPTIONS) return RESULT_VALID;

	if (request.getAttributes().get("account") != null) return RESULT_VALID;
	
	String accessToken = request.getHeaders().getFirstValue(HttpHeaders.AUTHORIZATION);
	if (accessToken == null) return RESULT_MISSING;
	
	try {
		accessToken.replace("OAuth ", "");
		AccountBean acc = mAccounts.getAccountFromToken(accessToken);
	    if (acc != null) {
	    	request.getAttributes().put("account", acc);
	    	return RESULT_VALID;
	    }
	} catch (Exception e) {
		Main.LOGGER.log(Level.WARNING, "Error while handling OAuth authentification", e);
		return RESULT_INVALID;
	}
    
	return RESULT_INVALID;
}
 
Example 4
Project: QoS-floodlight   File: RestApiServer.java   Source Code and License 6 votes vote down vote up
@Override
public Restlet createInboundRoot() {
    Router baseRouter = new Router(context);
    baseRouter.setDefaultMatchingMode(Template.MODE_STARTS_WITH);
    for (RestletRoutable rr : restlets) {
        baseRouter.attach(rr.basePath(), rr.getRestlet(context));
    }

    Filter slashFilter = new Filter() {            
        @Override
        protected int beforeHandle(Request request, Response response) {
            Reference ref = request.getResourceRef();
            String originalPath = ref.getPath();
            if (originalPath.contains("//"))
            {
                String newPath = originalPath.replaceAll("/+", "/");
                ref.setPath(newPath);
            }
            return Filter.CONTINUE;
        }

    };
    slashFilter.setNext(baseRouter);
    
    return slashFilter;
}
 
Example 5
Project: floodlight1.2-delay   File: RestApiServer.java   Source Code and License 6 votes vote down vote up
@Override
public Restlet createInboundRoot() {
	Router baseRouter = new Router(context);
	baseRouter.setDefaultMatchingMode(Template.MODE_STARTS_WITH);
	for (RestletRoutable rr : restlets) {
		baseRouter.attach(rr.basePath(), rr.getRestlet(context));
	}

	Filter slashFilter = new Filter() {            
		@Override
		protected int beforeHandle(Request request, Response response) {
			Reference ref = request.getResourceRef();
			String originalPath = ref.getPath();
			if (originalPath.contains("//"))
			{
				String newPath = originalPath.replaceAll("/+", "/");
				ref.setPath(newPath);
			}
			return Filter.CONTINUE;
		}

	};
	slashFilter.setNext(baseRouter);

	return slashFilter;
}
 
Example 6
Project: ACAMPController   File: RestApiServer.java   Source Code and License 6 votes vote down vote up
@Override
public Restlet createInboundRoot() {
	Router baseRouter = new Router(context);
	baseRouter.setDefaultMatchingMode(Template.MODE_STARTS_WITH);
	for (RestletRoutable rr : restlets) {
		baseRouter.attach(rr.basePath(), rr.getRestlet(context));
	}

	Filter slashFilter = new Filter() {            
		@Override
		protected int beforeHandle(Request request, Response response) {
			Reference ref = request.getResourceRef();
			String originalPath = ref.getPath();
			if (originalPath.contains("//"))
			{
				String newPath = originalPath.replaceAll("/+", "/");
				ref.setPath(newPath);
			}
			return Filter.CONTINUE;
		}

	};
	slashFilter.setNext(baseRouter);

	return slashFilter;
}
 
Example 7
Project: Camel   File: RestletRequestAndResponseAPITest.java   Source Code and License 6 votes vote down vote up
@Test
public void testRestletProducer2() throws Exception {
    final Map<String, Object> headers = new HashMap<String, Object>();
    headers.put("id", 123);
    headers.put("beverage.beer", "Carlsberg");

    Exchange out = template.request("direct:start", new Processor() {
        @Override
        public void process(Exchange exchange) throws Exception {
            exchange.getIn().setHeaders(headers);
        }
    });
    assertNotNull(out);
    assertEquals("text/xml", out.getOut().getHeader(Exchange.CONTENT_TYPE));
    assertEquals(200, out.getOut().getHeader(Exchange.HTTP_RESPONSE_CODE));
    assertEquals("<response>Beer is Good</response>", out.getOut().getBody(String.class));

    // the restlet response should be accessible if needed
    Response response = out.getOut().getHeader(RestletConstants.RESTLET_RESPONSE, Response.class);
    assertNotNull(response);
    assertEquals(200, response.getStatus().getCode());
}
 
Example 8
Project: fast-failover-demo   File: RestApiServer.java   Source Code and License 6 votes vote down vote up
@Override
public Restlet createInboundRoot() {
	Router baseRouter = new Router(context);
	baseRouter.setDefaultMatchingMode(Template.MODE_STARTS_WITH);
	for (RestletRoutable rr : restlets) {
		baseRouter.attach(rr.basePath(), rr.getRestlet(context));
	}

	Filter slashFilter = new Filter() {            
		@Override
		protected int beforeHandle(Request request, Response response) {
			Reference ref = request.getResourceRef();
			String originalPath = ref.getPath();
			if (originalPath.contains("//"))
			{
				String newPath = originalPath.replaceAll("/+", "/");
				ref.setPath(newPath);
			}
			return Filter.CONTINUE;
		}

	};
	slashFilter.setNext(baseRouter);

	return slashFilter;
}
 
Example 9
Project: polygene-java   File: ContextResource.java   Source Code and License 6 votes vote down vote up
private boolean shouldShowCommandForm( Method interactionMethod )
{
    // Show form on GET/HEAD
    if( Request.getCurrent().getMethod().isSafe() )
    {
        return true;
    }

    if( interactionMethod.getParameterTypes().length > 0 )
    {
        return !( interactionMethod.getParameterTypes()[ 0 ].equals( Response.class ) || Request.getCurrent()
            .getEntity()
            .isAvailable() || Request.getCurrent().getEntityAsText() != null || Request.getCurrent()
                                                                                    .getResourceRef()
                                                                                    .getQuery() != null );
    }

    return false;
}
 
Example 10
Project: polygene-java   File: LinksResponseWriter.java   Source Code and License 6 votes vote down vote up
private Representation createTextHtmlRepresentation( final Object result, final Response response )
{
    return new WriterRepresentation( MediaType.TEXT_HTML )
                {
                    @Override
                    public void write( Writer writer )
                        throws IOException
                    {
                        Map<String, Object> context = new HashMap<>();
                        context.put( "request", response.getRequest() );
                        context.put( "response", response );
                        context.put( "result", result );
                        try
                        {
                            cfg.getTemplate( "links.htm" ).process( context, writer );
                        }
                        catch( TemplateException e )
                        {
                            throw new IOException( e );
                        }
                    }
                };
}
 
Example 11
Project: polygene-java   File: LinksResponseWriter.java   Source Code and License 6 votes vote down vote up
private Representation createAtomRepresentation( final Object result, final Response response )
{
    return new WriterRepresentation( MediaType.APPLICATION_ATOM )
    {
        @Override
        public void write( Writer writer )
            throws IOException
        {
            Map<String, Object> context = new HashMap<>();
            context.put( "request", response.getRequest() );
            context.put( "response", response );
            context.put( "result", result );
            try
            {
                cfg.getTemplate( "links.atom" ).process( context, writer );
            }
            catch( TemplateException e )
            {
                throw new IOException( e );
            }
        }
    };
}
 
Example 12
Project: floodlight   File: RestApiServer.java   Source Code and License 6 votes vote down vote up
@Override
public Restlet createInboundRoot() {
    Router baseRouter = new Router(context);
    baseRouter.setDefaultMatchingMode(Template.MODE_STARTS_WITH);
    for (RestletRoutable rr : restlets) {
        baseRouter.attach(rr.basePath(), rr.getRestlet(context));
    }

    Filter slashFilter = new Filter() {            
        @Override
        protected int beforeHandle(Request request, Response response) {
            Reference ref = request.getResourceRef();
            String originalPath = ref.getPath();
            if (originalPath.contains("//"))
            {
                String newPath = originalPath.replaceAll("/+", "/");
                ref.setPath(newPath);
            }
            return Filter.CONTINUE;
        }

    };
    slashFilter.setNext(baseRouter);
    
    return slashFilter;
}
 
Example 13
Project: polygene-java   File: ContextResourceClient.java   Source Code and License 6 votes vote down vote up
public <T> ContextResourceClient onResource( final ResultHandler<T> handler)
{
    resourceHandler = new ResponseHandler()
    {
        @Override
        public HandlerCommand handleResponse( Response response, ContextResourceClient client )
        {
            final Class<T> resultType = (Class<T>) Classes.RAW_CLASS.apply(( (ParameterizedType) handler.getClass().getGenericInterfaces()[ 0 ] ).getActualTypeArguments()[0]);
            T result = contextResourceFactory.readResponse( response, resultType );

            if (result instanceof Resource)
            {
                resource = (Resource) result;
            }

            return handler.handleResult( result, client );
        }
    };
    return this;
}
 
Example 14
Project: polygene-java   File: ContextResourceClient.java   Source Code and License 6 votes vote down vote up
public <T> ContextResourceClient onQuery( String relation, final ResultHandler<T> handler
)
{
    final Class<T> resultType = (Class<T>) Classes.RAW_CLASS.apply(( (ParameterizedType) handler.getClass().getGenericInterfaces()[ 0 ] ).getActualTypeArguments()[0]);

    queryHandlers.put( relation,  new ResponseHandler()
    {
        @Override
        public HandlerCommand handleResponse( Response response, ContextResourceClient client )
        {
            T result = contextResourceFactory.readResponse( response, resultType );
            return handler.handleResult( result, client );
        }
    });

    return this;
}
 
Example 15
Project: polygene-java   File: ContextResourceClient.java   Source Code and License 6 votes vote down vote up
public <T> ContextResourceClient onProcessingError( String relation, final ResultHandler<T> handler)
{
    final Class<T> resultType = (Class<T>) Classes.RAW_CLASS.apply(( (ParameterizedType) handler.getClass().getGenericInterfaces()[ 0 ] ).getActualTypeArguments()[0]);

    processingErrorHandlers.put( relation,  new ResponseHandler()
    {
        @Override
        public HandlerCommand handleResponse( Response response, ContextResourceClient client )
        {
            T result = contextResourceFactory.readResponse( response, resultType );
            return handler.handleResult( result, client );
        }
    });

    return this;
}
 
Example 16
Project: polygene-java   File: DefaultResourceFactoryImpl.java   Source Code and License 6 votes vote down vote up
@Override
public T create( Class<T> entityType, Request request, Response response, Context context )
{
    final Map<String, Object> attributes = request.getAttributes();
    String id = (String) attributes.get( "id" );

    ValueBuilder<T> builder = vbf.newValueBuilderWithState(
        resourceType,
        descriptor -> findValue( attributes, descriptor ),
        descriptor -> null,
        descriptor -> null,
        descriptor -> null
    );
    //noinspection unchecked
    ServerResource.Parameters<T> params = builder.prototypeFor( ServerResource.Parameters.class );
    params.id().set( id );
    params.entityType().set( entityType );
    params.context().set( this.context );
    params.request().set( request );
    params.router().set( router );
    params.response().set( response );
    return builder.newInstance();
}
 
Example 17
Project: polygene-java   File: RootResource.java   Source Code and License 6 votes vote down vote up
@SubResource
public void administration()
{
    ChallengeResponse challenge = Request.getCurrent().getChallengeResponse();
    if( challenge == null )
    {
        Response.getCurrent()
            .setChallengeRequests( Collections.singletonList( new ChallengeRequest( ChallengeScheme.HTTP_BASIC, "Forum" ) ) );
        throw new ResourceException( Status.CLIENT_ERROR_UNAUTHORIZED );
    }

    User user = select( Users.class, Users.USERS_ID ).userNamed( challenge.getIdentifier() );
    if( user == null || !user.isCorrectPassword( new String( challenge.getSecret() ) ) )
    {
        throw new ResourceException( Status.CLIENT_ERROR_UNAUTHORIZED );
    }

    current().select( user );

    subResource( AdministrationResource.class );
}
 
Example 18
Project: prudence   File: PrudenceRouter.java   Source Code and License 6 votes vote down vote up
@Override
public void handle( Request request, Response response )
{
	// RIAP ignores hide
	if( request.getProtocol() != Protocol.RIAP )
	{
		String remainingPart = request.getResourceRef().getRemainingPart();
		for( Template hiddenUriTemplate : hiddenUriTemplates )
		{
			if( hiddenUriTemplate.match( remainingPart ) != -1 )
			{
				response.setStatus( Status.CLIENT_ERROR_NOT_FOUND );
				return;
			}
		}
	}

	super.handle( request, response );
}
 
Example 19
Project: prudence   File: GeneratedTextDeferredRepresentation.java   Source Code and License 6 votes vote down vote up
public void run()
{
	if( delay > 0 )
	{
		try
		{
			Thread.sleep( delay );
		}
		catch( InterruptedException e )
		{
			// Restore interrupt status
			Thread.currentThread().interrupt();
			return;
		}
	}

	Response response = resource.getResponse();
	response.setEntity( this );
	response.setStatus( Status.SUCCESS_OK );
	response.commit();
}
 
Example 20
Project: prudence   File: ResolvingRedirector.java   Source Code and License 6 votes vote down vote up
/**
 * Throw an exception if there is a recursive server-side redirect.
 * 
 * @param targetRef
 *        The target reference
 * @param request
 *        The request
 * @param response
 *        The response
 */
private void validateNotRecursiveServerRedirect( Reference targetRef, Request request, Response response )
{
	@SuppressWarnings("unchecked")
	Set<String> serverRedirectHistory = (Set<String>) request.getAttributes().get( SERVER_REDIRECT_HISTORY_ATTRIBUTE );
	if( serverRedirectHistory == null )
	{
		serverRedirectHistory = new HashSet<String>();
		@SuppressWarnings("unchecked")
		Set<String> existing = (Set<String>) request.getAttributes().putIfAbsent( SERVER_REDIRECT_HISTORY_ATTRIBUTE, serverRedirectHistory );
		if( existing != null )
			serverRedirectHistory = existing;
	}

	String targetRefString = targetRef.toString();
	if( serverRedirectHistory.contains( targetRefString ) )
	{
		String message = "Recursive server redirection to " + targetRef;
		getLogger().warning( message );
		throw new ResourceException( Status.SERVER_ERROR_INTERNAL, message );
	}

	serverRedirectHistory.add( targetRefString );
}
 
Example 21
Project: prudence   File: RestletUtil.java   Source Code and License 6 votes vote down vote up
/**
 * Gets the response headers, making sure to create them if they don't
 * exist.
 * 
 * @param response
 *        The response
 * @return The headers
 */
public static Series<Header> getResponseHeaders( Response response )
{
	ConcurrentMap<String, Object> attributes = response.getAttributes();
	@SuppressWarnings("unchecked")
	Series<Header> headers = (Series<Header>) attributes.get( HeaderConstants.ATTRIBUTE_HEADERS );
	if( headers == null )
	{
		headers = new Series<Header>( Header.class );
		@SuppressWarnings("unchecked")
		Series<Header> existing = (Series<Header>) attributes.putIfAbsent( HeaderConstants.ATTRIBUTE_HEADERS, headers );
		if( existing != null )
			headers = existing;
	}
	return headers;
}
 
Example 22
Project: floodlightLB   File: RestApiServer.java   Source Code and License 6 votes vote down vote up
@Override
public Restlet createInboundRoot() {
	Router baseRouter = new Router(context);
	baseRouter.setDefaultMatchingMode(Template.MODE_STARTS_WITH);
	for (RestletRoutable rr : restlets) {
		baseRouter.attach(rr.basePath(), rr.getRestlet(context));
	}

	Filter slashFilter = new Filter() {            
		@Override
		protected int beforeHandle(Request request, Response response) {
			Reference ref = request.getResourceRef();
			String originalPath = ref.getPath();
			if (originalPath.contains("//"))
			{
				String newPath = originalPath.replaceAll("/+", "/");
				ref.setPath(newPath);
			}
			return Filter.CONTINUE;
		}

	};
	slashFilter.setNext(baseRouter);

	return slashFilter;
}
 
Example 23
Project: DSC   File: RestApiServer.java   Source Code and License 6 votes vote down vote up
@Override
public Restlet createInboundRoot() {
	Router baseRouter = new Router(context);
	baseRouter.setDefaultMatchingMode(Template.MODE_STARTS_WITH);
	for (RestletRoutable rr : restlets) {
		baseRouter.attach(rr.basePath(), rr.getRestlet(context));
	}

	Filter slashFilter = new Filter() {            
		@Override
		protected int beforeHandle(Request request, Response response) {
			Reference ref = request.getResourceRef();
			String originalPath = ref.getPath();
			if (originalPath.contains("//"))
			{
				String newPath = originalPath.replaceAll("/+", "/");
				ref.setPath(newPath);
			}
			return Filter.CONTINUE;
		}

	};
	slashFilter.setNext(baseRouter);

	return slashFilter;
}
 
Example 24
Project: Multipath-Hedera-system-in-Floodlight-controller   File: RestApiServer.java   Source Code and License 6 votes vote down vote up
@Override
public Restlet createInboundRoot() {
    Router baseRouter = new Router(context);
    baseRouter.setDefaultMatchingMode(Template.MODE_STARTS_WITH);
    for (RestletRoutable rr : restlets) {
        baseRouter.attach(rr.basePath(), rr.getRestlet(context));
    }

    Filter slashFilter = new Filter() {            
        @Override
        protected int beforeHandle(Request request, Response response) {
            Reference ref = request.getResourceRef();
            String originalPath = ref.getPath();
            if (originalPath.contains("//"))
            {
                String newPath = originalPath.replaceAll("/+", "/");
                ref.setPath(newPath);
            }
            return Filter.CONTINUE;
        }

    };
    slashFilter.setNext(baseRouter);
    
    return slashFilter;
}
 
Example 25
Project: springboot-shiro-cas-mybatis   File: TicketGrantingTicketResource.java   Source Code and License 5 votes vote down vote up
@Override
public void init(final Context context, final Request request, final Response response) {
    super.init(context, request, response);
    this.ticketGrantingTicketId = (String) request.getAttributes().get("ticketGrantingTicketId");
    this.setNegotiated(false);
    this.getVariants().add(new Variant(MediaType.APPLICATION_WWW_FORM));
}
 
Example 26
Project: open-rmbt   File: TileRestlet.java   Source Code and License 5 votes vote down vote up
@Override
public void handle(final Request req, final Response res)
{
    final String zoomStr = (String) req.getAttributes().get("zoom");
    final String xStr = (String) req.getAttributes().get("x");
    final String yStr = (String) req.getAttributes().get("y");
    
    final Path path = new Path(zoomStr, xStr, yStr, req.getResourceRef().getQueryAsForm().getFirstValue("path", true));
    final Params p = getTileParameters(path, req.getResourceRef().getQueryAsForm());
    res.setEntity(new PngOutputRepresentation(getTile(p)));
}
 
Example 27
Project: iTAP-controller   File: RestApiServer.java   Source Code and License 5 votes vote down vote up
@Override
public Restlet createInboundRoot() {
	Router baseRouter = new Router(context);
	baseRouter.setDefaultMatchingMode(Template.MODE_STARTS_WITH);
	for (RestletRoutable rr : restlets) {
		baseRouter.attach(rr.basePath(), rr.getRestlet(context));
	}

	Filter slashFilter = new Filter() {            
		@Override
		protected int beforeHandle(Request request, Response response) {
			Reference ref = request.getResourceRef();
			String originalPath = ref.getPath();
			if (originalPath.contains("//"))
			{
				String newPath = originalPath.replaceAll("/+", "/");
				ref.setPath(newPath);
			}
			return Filter.CONTINUE;
		}

	};
	slashFilter.setNext(baseRouter);

	return slashFilter;
}
 
Example 28
Project: SDN-Multicast   File: RestApiServer.java   Source Code and License 5 votes vote down vote up
@Override
public Restlet createInboundRoot() {
	Router baseRouter = new Router(context);
	baseRouter.setDefaultMatchingMode(Template.MODE_STARTS_WITH);
	for (RestletRoutable rr : restlets) {
		baseRouter.attach(rr.basePath(), rr.getRestlet(context));
	}

	Filter slashFilter = new Filter() {            
		@Override
		protected int beforeHandle(Request request, Response response) {
			Reference ref = request.getResourceRef();
			String originalPath = ref.getPath();
			if (originalPath.contains("//"))
			{
				String newPath = originalPath.replaceAll("/+", "/");
				ref.setPath(newPath);
			}
			return Filter.CONTINUE;
		}

	};
	slashFilter.setNext(baseRouter);

	return slashFilter;
}
 
Example 29
Project: ipst   File: ITeslaRules.java   Source Code and License 5 votes vote down vote up
@Override
public void init(Context context, Request request, Response response) {
    super.init(context, request, response);

    algoType = (String)getRequest().getAttributes().get("algoType");
    contingencyId = (String)getRequest().getAttributes().get("contingencyId");
    indexType = (String)getRequest().getAttributes().get("indexType");
}
 
Example 30
Project: eSDK_EC_SDK_Java   File: SecretVerifier.java   Source Code and License 5 votes vote down vote up
/**
 * Verifies that the proposed secret is correct for the specified request.
 * By default, it compares the inputSecret of the request's authentication
 * response with the one obtain by the {@link ChallengeResponse#getSecret()}
 * method and sets the {@link org.restlet.security.User} instance of the
 * request's {@link ClientInfo} if successful.
 * 
 * @param request
 *            The request to inspect.
 * @param response
 *            The response to inspect.
 * @return Result of the verification based on the RESULT_* constants.
 */
public int verify(Request request, Response response)
{
    int result = RESULT_VALID;
    
    if (request.getChallengeResponse() == null)
    {
        result = RESULT_MISSING;
    }
    else
    {
        String identifier = getIdentifier(request, response);
        char[] secret = getSecret(request, response);
        AccountInfo accountInfo = new AccountInfo();
        accountInfo.setUserId(identifier);
        accountInfo.setPassword(new String(secret));
        MessageContext mc = ThreadLocalHolder.get();
        mc.getEntities().put(ESDKConstant.ACCT_INFO_ESDK, accountInfo);
        
        if (authorize.isLocalAuth("uc"))//TODO zhili
        {
            result = verify(identifier, secret);
        }
        else
        {
            Map<String, String> message = new HashMap<String, String>();
            message.put(ESDKConstant.ESDK_USER_ID, identifier);
            message.put(ESDKConstant.ESDK_PLAIN_PWD, new String(secret));
            result = restAppAuthorize.verify(request.getOriginalRef().getPath(), message);
        }
        
        if (result == RESULT_VALID)
        {
            request.getClientInfo().setUser(createUser(identifier, request, response));
        }
    }
    
    return result;
}
 
Example 31
Project: bigstreams   File: TestFileTrackerStatusResource.java   Source Code and License 5 votes vote down vote up
protected Application setupApp() throws Exception {

		final MapTrackerMemory memory = new MapTrackerMemory();

		memory.updateFile(new FileTrackingStatus(1L, 10L, "test1.txt",
				FileTrackingStatus.STATUS.READY, 3, 4L, "testType1", new Date(), new Date()));
		memory.updateFile(new FileTrackingStatus(1L, 10L, "test2.txt",
				FileTrackingStatus.STATUS.READING, 3, 4L, "testType2", new Date(), new Date()));
		memory.updateFile(new FileTrackingStatus(1L, 10L, "test3.txt",
				FileTrackingStatus.STATUS.DONE, 3, 4L, "testType3", new Date(), new Date()));

		this.memory = memory;

		Finder finder = new Finder() {

			@Override
			public ServerResource find(Request request, Response response) {
				return fileTrackingStatusResource(memory);
			}

		};

		final Router router = new Router();
		router.attach("/files/list", finder);
		router.attach("/files/list/", finder);
		router.attach("/files/list/{status}", finder);

		return new Application() {

			@Override
			public Restlet createInboundRoot() {
				return router;
			}

		};

	}
 
Example 32
Project: bigstreams   File: TestFileTrackerStatusPathResource.java   Source Code and License 5 votes vote down vote up
protected Application setupApp() throws Exception {

		final MapTrackerMemory memory = new MapTrackerMemory();

		memory.updateFile(new FileTrackingStatus(1L, 10L, new File("test1.txt")
				.getAbsolutePath(), FileTrackingStatus.STATUS.READY, 3, 4L,
				"testType1", new Date(), new Date()));
		memory.updateFile(new FileTrackingStatus(1L, 10L, new File("test2.txt")
				.getAbsolutePath(), FileTrackingStatus.STATUS.READING, 3, 4L,
				"testType2", new Date(), new Date()));
		memory.updateFile(new FileTrackingStatus(1L, 10L, new File("test3.txt")
				.getAbsolutePath(), FileTrackingStatus.STATUS.DONE, 3, 4L,
				"testType3", new Date(), new Date()));

		this.memory = memory;

		Finder finder = new Finder() {

			@Override
			public ServerResource find(Request request, Response response) {
				return fileTrackingStatusPathResource(memory);
			}

		};

		final Router router = new Router();
		router.attach("/files/status", finder, Template.MODE_STARTS_WITH);
		Application app = new Application() {

			@Override
			public Restlet createInboundRoot() {
				return router;
			}

		};

		return app;
	}
 
Example 33
Project: bigstreams   File: CollectorDI.java   Source Code and License 5 votes vote down vote up
/**
 * Helper method to attch the server resource to the router.
 * 
 * @param router
 * @param pathTemplate
 * @param resourceClass
 * @param matchingMode
 */
private final void attachFinder(Router router, String pathTemplate,
		final Class<? extends ServerResource> resourceClass,
		int matchingMode) {

	Finder finder = new Finder() {

		@Override
		public ServerResource find(Request request, Response response) {
			return beanFactory.getBean(resourceClass);
		}

	};

	router.attach(pathTemplate, finder, matchingMode);
}
 
Example 34
Project: bigstreams   File: CoordinationDI.java   Source Code and License 5 votes vote down vote up
/**
 * Helper method to attch the server resource to the router.
 * 
 * @param router
 * @param pathTemplate
 * @param resourceClass
 * @param matchingMode
 */
private final void attachFinder(Router router, String pathTemplate,
		final Class<? extends ServerResource> resourceClass,
		int matchingMode) {

	Finder finder = new Finder() {

		@Override
		public ServerResource find(Request request, Response response) {
			return beanFactory.getBean(resourceClass);
		}

	};

	router.attach(pathTemplate, finder, matchingMode);
}
 
Example 35
Project: bigstreams   File: AlwaysOKRestlet.java   Source Code and License 5 votes vote down vote up
/**
 * Creates a Component that will used this reasource to always return ok.
 * 
 * @param port
 * @return
 */
public static Component createComponent(int port) {

	Finder finder = new Finder() {

		@Override
		public ServerResource find(Request request, Response response) {
			return new AlwaysOKRestlet();
		}

	};

	final Router router = new Router();
	router.attach("/", finder, Template.MODE_STARTS_WITH);
	
	Application app = new Application() {

		@Override
		public Restlet createInboundRoot() {
			return router;
		}

	};

	Component component = new Component();
	component.getServers().add(org.restlet.data.Protocol.HTTP, port);
	component.getDefaultHost().attach(app);

	return component;
}
 
Example 36
Project: QoS-floodlight   File: RestApiServer.java   Source Code and License 5 votes vote down vote up
public void run(FloodlightModuleContext fmlContext, String restHost, int restPort) {
    setStatusService(new StatusService() {
        @Override
        public Representation getRepresentation(Status status,
                                                Request request,
                                                Response response) {
            return new JacksonRepresentation<Status>(status);
        }                
    });
    
    // Add everything in the module context to the rest
    for (Class<? extends IFloodlightService> s : fmlContext.getAllServices()) {
        if (logger.isTraceEnabled()) {
            logger.trace("Adding {} for service {} into context",
                         s.getCanonicalName(), fmlContext.getServiceImpl(s));
        }
        context.getAttributes().put(s.getCanonicalName(), 
                                    fmlContext.getServiceImpl(s));
    }
    
    // Start listening for REST requests
    try {
        final Component component = new Component();
        if (restHost == null) {
        	component.getServers().add(Protocol.HTTP, restPort);
        } else {
        	component.getServers().add(Protocol.HTTP, restHost, restPort);
        }
        component.getClients().add(Protocol.CLAP);
        component.getDefaultHost().attach(this);
        component.start();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example 37
Project: uReplicator   File: ControllerStarterTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testPost() {
  // Create topic
  Request request = ControllerRequestURLBuilder.baseUrl(REQUEST_URL)
      .getTopicCreationRequestUrl("testTopic1", 16);
  Response response = HTTP_CLIENT.handle(request);
  Assert.assertEquals(response.getStatus(), Status.SUCCESS_OK);
  Assert.assertEquals(response.getEntityAsText(),
      "Successfully add new topic: {topic: testTopic1, partition: 16}");
  Assert.assertTrue(ZK_CLIENT.exists("/" + HELIX_CLUSTER_NAME + "/CONFIGS/RESOURCE/testTopic1"));

  // Create existed topic
  request = ControllerRequestURLBuilder.baseUrl(REQUEST_URL)
      .getTopicCreationRequestUrl("testTopic1", 16);
  response = HTTP_CLIENT.handle(request);
  Assert.assertEquals(response.getStatus(), Status.CLIENT_ERROR_NOT_FOUND);
  Assert.assertEquals(response.getEntityAsText(),
      "Failed to add new topic: testTopic1, it is already existed!");

  // Delete topic
  request =
      ControllerRequestURLBuilder.baseUrl(REQUEST_URL).getTopicDeleteRequestUrl("testTopic1");
  response = HTTP_CLIENT.handle(request);
  Assert.assertEquals(response.getStatus(), Status.SUCCESS_OK);
  Assert.assertEquals(response.getEntityAsText(),
      "Successfully finished delete topic: testTopic1");

}
 
Example 38
Project: uReplicator   File: ControllerStarterTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testPut() {
  // Create topic
  Request request = ControllerRequestURLBuilder.baseUrl(REQUEST_URL)
      .getTopicCreationRequestUrl("testTopic2", 8);
  Response response = HTTP_CLIENT.handle(request);
  Assert.assertEquals(response.getStatus(), Status.SUCCESS_OK);
  Assert.assertEquals(response.getEntityAsText(),
      "Successfully add new topic: {topic: testTopic2, partition: 8}");
  Assert.assertTrue(ZK_CLIENT.exists("/" + HELIX_CLUSTER_NAME + "/CONFIGS/RESOURCE/testTopic2"));

  // Expand topic
  request = ControllerRequestURLBuilder.baseUrl(REQUEST_URL)
      .getTopicExpansionRequestUrl("testTopic2", 16);
  response = HTTP_CLIENT.handle(request);
  Assert.assertEquals(response.getStatus(), Status.SUCCESS_OK);
  Assert.assertEquals(response.getEntityAsText(),
      "Successfully expand topic: {topic: testTopic2, partition: 16}");

  // Expand non-existed topic
  request = ControllerRequestURLBuilder.baseUrl(REQUEST_URL)
      .getTopicExpansionRequestUrl("testTopic22", 16);
  response = HTTP_CLIENT.handle(request);
  Assert.assertEquals(response.getStatus(), Status.CLIENT_ERROR_NOT_FOUND);
  Assert.assertEquals(response.getEntityAsText(),
      "Failed to expand topic, topic: testTopic22 is not existed!");

  // Delete topic
  request =
      ControllerRequestURLBuilder.baseUrl(REQUEST_URL).getTopicDeleteRequestUrl("testTopic2");
  response = HTTP_CLIENT.handle(request);
  Assert.assertEquals(response.getStatus(), Status.SUCCESS_OK);
  Assert.assertEquals(response.getEntityAsText(),
      "Successfully finished delete topic: testTopic2");

}
 
Example 39
Project: eSDK_IVS_Java   File: SecretVerifier.java   Source Code and License 5 votes vote down vote up
/**
 * Verifies that the proposed secret is correct for the specified request.
 * By default, it compares the inputSecret of the request's authentication
 * response with the one obtain by the {@link ChallengeResponse#getSecret()}
 * method and sets the {@link org.restlet.security.User} instance of the
 * request's {@link ClientInfo} if successful.
 * 
 * @param request
 *            The request to inspect.
 * @param response
 *            The response to inspect.
 * @return Result of the verification based on the RESULT_* constants.
 */
public int verify(Request request, Response response)
{
    int result = RESULT_VALID;
    
    if (request.getChallengeResponse() == null)
    {
        result = RESULT_MISSING;
    }
    else
    {
        String identifier = getIdentifier(request, response);
        char[] secret = getSecret(request, response);
        AccountInfo accountInfo = new AccountInfo();
        accountInfo.setUserId(identifier);
        accountInfo.setPassword(new String(secret));
        MessageContext mc = ThreadLocalHolder.get();
        mc.getEntities().put(ESDKConstant.ACCT_INFO_ESDK, accountInfo);
        
        if (authorize.isLocalAuth("uc"))//TODO zhili
        {
            result = verify(identifier, secret);
        }
        else
        {
            Map<String, String> message = new HashMap<String, String>();
            message.put(ESDKConstant.ESDK_USER_ID, identifier);
            message.put(ESDKConstant.ESDK_PLAIN_PWD, new String(secret));
            result = restAppAuthorize.verify(request.getOriginalRef().getPath(), message);
        }
        
        if (result == RESULT_VALID)
        {
            request.getClientInfo().setUser(createUser(identifier, request, response));
        }
    }
    
    return result;
}
 
Example 40
Project: floodlight-hardware   File: RestApiServer.java   Source Code and License 5 votes vote down vote up
@Override
public Restlet createInboundRoot() {
	Router baseRouter = new Router(context);
	baseRouter.setDefaultMatchingMode(Template.MODE_STARTS_WITH);
	for (RestletRoutable rr : restlets) {
		baseRouter.attach(rr.basePath(), rr.getRestlet(context));
	}

	Filter slashFilter = new Filter() {
		@Override
		protected int beforeHandle(Request request, Response response) {
			Reference ref = request.getResourceRef();
			String originalPath = ref.getPath();
			if (originalPath.contains("//"))
			{
				String newPath = originalPath.replaceAll("/+", "/");
				ref.setPath(newPath);
			}
			return Filter.CONTINUE;
		}

	};
	slashFilter.setNext(baseRouter);

	return slashFilter;
}