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;
}
 
Example 41
Project: cas4.1.9   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 42
Project: chaperone   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 43
Project: chaperone   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 44
Project: Camel   File: RestletConsumer.java   Source Code and License 5 votes vote down vote up
/**
 * Creates a new {@link org.restlet.Uniform} callback that restlet calls when its done sending the reply message.
 * <p/>
 * We use this to defer done on the exchange {@link org.apache.camel.spi.UnitOfWork} where resources is safe to be
 * cleaned up as part of the done process.
 */
private Uniform newResponseUniform(final Exchange exchange) {
    return new Uniform() {
        @Override
        public void handle(Request request, Response response) {
            if (exchange != null) {
                doneUoW(exchange);
            }
        }
    };
}
 
Example 45
Project: Camel   File: MethodBasedRouter.java   Source Code and License 5 votes vote down vote up
@Override
public void handle(Request request, Response response) {
    Method method = request.getMethod();
    LOG.debug("MethodRouter ({}) received request method: {}", uriPattern, method);
    
    Restlet target = routes.get(method);
    if (target != null) {
        target.handle(request, response);
    } else {
        LOG.debug("MethodRouter ({}) method not allowed: {}", uriPattern, method);
        response.setStatus(Status.CLIENT_ERROR_METHOD_NOT_ALLOWED);
        // must include list of allowed methods
        response.setAllowedMethods(routes.keySet());
    }
}
 
Example 46
Project: Camel   File: RestletProducer.java   Source Code and License 5 votes vote down vote up
protected RestletOperationException populateRestletProducerException(Exchange exchange, Response response, int responseCode) {
    RestletOperationException exception;
    String uri = response.getRequest().getResourceRef().toString();
    String statusText = response.getStatus().getDescription();
    Map<String, String> headers = parseResponseHeaders(response, exchange);
    String copy;
    if (response.getEntity() != null) {
        try {
            copy = response.getEntity().getText();
        } catch (Exception ex) {
            copy = ex.toString();
        }
    } else {
        copy = response.toString();
    }
    if (responseCode >= 300 && responseCode < 400) {
        String redirectLocation;
        if (response.getStatus().isRedirection()) {
            redirectLocation = response.getLocationRef().getHostIdentifier();
            exception = new RestletOperationException(uri, responseCode, statusText, redirectLocation, headers, copy);
        } else {
            //no redirect location
            exception = new RestletOperationException(uri, responseCode, statusText, null, headers, copy);
        }
    } else {
        //internal server error(error code 500)
        exception = new RestletOperationException(uri, responseCode, statusText, null, headers, copy);
    }

    return exception;
}
 
Example 47
Project: Camel   File: RestletProducer.java   Source Code and License 5 votes vote down vote up
protected Map<String, String> parseResponseHeaders(Object response, Exchange camelExchange) {

        Map<String, String> answer = new HashMap<String, String>();
        if (response instanceof Response) {

            for (Map.Entry<String, Object> entry : ((Response) response).getAttributes().entrySet()) {
                String key = entry.getKey();
                Object value = entry.getValue();
                LOG.trace("Parse external header {}={}", key, value);
                answer.put(key, value.toString());
            }
        }

        return answer;
    }
 
Example 48
Project: Camel   File: RestletRouteBuilderTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testConsumer() throws IOException {
    Client client = new Client(Protocol.HTTP);
    Response response = client.handle(new Request(Method.GET, 
        "http://localhost:" + portNum + "/orders/99991/6"));
    assertEquals("received GET request with id=99991 and x=6",
        response.getEntity().getText());
}
 
Example 49
Project: Camel   File: RestletRouteBuilderTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testConsumerWithSpaces() throws IOException {
    Client client = new Client(Protocol.HTTP);
    Response response = client.handle(new Request(Method.GET, 
        "http://localhost:" + portNum + "/orders with spaces in path/99991/6"));
    assertEquals("received GET request with id=99991 and x=6",
        response.getEntity().getText());
}
 
Example 50
Project: Camel   File: RestletRouteBuilderTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testUnhandledConsumer() throws IOException {
    Client client = new Client(Protocol.HTTP);
    Response response = client.handle(new Request(Method.POST, 
        "http://localhost:" + portNum + "/orders/99991/6"));
    // expect error status as no Restlet consumer to handle POST method
    assertEquals(Status.CLIENT_ERROR_METHOD_NOT_ALLOWED, response.getStatus());
    assertNotNull(response.getEntity().getText());
}
 
Example 51
Project: Camel   File: RestletRouteBuilderTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testNotFound() throws IOException {
    Client client = new Client(Protocol.HTTP);
    Response response = client.handle(new Request(Method.POST,
        "http://localhost:" + portNum + "/unknown"));
    // expect error status as no Restlet consumer to handle POST method
    assertEquals(Status.CLIENT_ERROR_NOT_FOUND, response.getStatus());
    assertNotNull(response.getEntity().getText());
}
 
Example 52
Project: Camel   File: RestletRequestAndResponseAPITest.java   Source Code and License 5 votes vote down vote up
@Override
protected RouteBuilder createRouteBuilder() throws Exception {
    return new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            from("direct:start").to("restlet:http://localhost:" + portNum + "/users/{id}/like/{beverage.beer}");

            // START SNIPPET: e1
            from("restlet:http://localhost:" + portNum + "/users/{id}/like/{beer}")
                .process(new Processor() {
                    public void process(Exchange exchange) throws Exception {
                        // the Restlet request should be available if needed
                        Request request = exchange.getIn().getHeader(RestletConstants.RESTLET_REQUEST, Request.class);
                        assertNotNull("Restlet Request", request);

                        // use Restlet API to create the response
                        Response response = exchange.getIn().getHeader(RestletConstants.RESTLET_RESPONSE, Response.class);
                        assertNotNull("Restlet Response", response);
                        response.setStatus(Status.SUCCESS_OK);
                        response.setEntity("<response>Beer is Good</response>", MediaType.TEXT_XML);
                        exchange.getOut().setBody(response);
                    }
                });
            // END SNIPPET: e1
        }
    };
}
 
Example 53
Project: polygene-java   File: ContextResource.java   Source Code and License 5 votes vote down vote up
@Override
public final void handle( Request request, Response response )
{
    ObjectSelection objectSelection = current();

    // Check constraints for this resource
    if( !constraints.isValid( getClass(), objectSelection, module ) )
    {
        throw new ResourceException( Status.CLIENT_ERROR_FORBIDDEN );
    }

    // Find remaining segments
    List<String> segments = getSegments();

    if( segments.size() > 0 )
    {
        String segment = segments.remove( 0 );

        if( segments.size() > 0 )
        {
            handleSubResource( segment );
        }
        else
        {
            handleResource( segment );
        }
    }
}
 
Example 54
Project: polygene-java   File: ContextResource.java   Source Code and License 5 votes vote down vote up
private void result( Object resultValue )
    throws Exception
{
    if( resultValue != null )
    {
        if( !responseWriter.writeResponse( resultValue, Response.getCurrent() ) )
        {
            throw new ResourceException( Status.SERVER_ERROR_INTERNAL, "No result writer for type " + resultValue.getClass()
                .getName() );
        }
    }
}
 
Example 55
Project: polygene-java   File: ResourceValidity.java   Source Code and License 5 votes vote down vote up
void updateResponse( Response response )
{
    if( entity != null )
    {
        EntityState state = spi.entityStateOf( entity );
        Tag tag = new Tag( state.entityReference().identity() + "/" + state.version() );
        response.getEntity().setModificationDate( java.util.Date.from( state.lastModified() ) );
        response.getEntity().setTag( tag );
    }
}
 
Example 56
Project: polygene-java   File: ExtensionMediaTypeFilter.java   Source Code and License 5 votes vote down vote up
@Override
protected int beforeHandle( Request request, Response response )
{
    List<String> segments = request.getResourceRef().getSegments();
    if( segments.get( segments.size() - 1 ).equals( "" ) )
    {
        return Filter.CONTINUE;
    }

    String extensions = request.getResourceRef().getExtensions();
    if( extensions != null )
    {
        int idx = extensions.lastIndexOf( "." );
        if( idx != -1 )
        {
            extensions = extensions.substring( idx + 1 );
        }

        MetadataService metadataService = getApplication().getMetadataService();
        Metadata metadata = metadataService.getMetadata( extensions );
        if( metadata != null && metadata instanceof MediaType )
        {
            request.getClientInfo()
                .setAcceptedMediaTypes( Collections.singletonList( new Preference<MediaType>( (MediaType) metadata ) ) );
            String path = request.getResourceRef().getPath();
            path = path.substring( 0, path.length() - extensions.length() - 1 );
            request.getResourceRef().setPath( path );
        }
    }

    return Filter.CONTINUE;
}
 
Example 57
Project: polygene-java   File: ResponseWriterDelegator.java   Source Code and License 5 votes vote down vote up
@Override
public boolean writeResponse( Object result, Response response )
{
    for( ResponseWriter responseWriter : responseWriters )
    {
        if( responseWriter.writeResponse( result, response ) )
        {
            return true;
        }
    }
    return false;
}
 
Example 58
Project: polygene-java   File: ExtensionMediaTypeFilter.java   Source Code and License 5 votes vote down vote up
@Override
protected int beforeHandle( Request request, Response response )
{
    List<String> segments = request.getResourceRef().getSegments();
    if (segments.get( segments.size()-1 ).equals(""))
      return Filter.CONTINUE;

    String extensions = request.getResourceRef().getExtensions();
    if( extensions != null )
    {
        int idx = extensions.lastIndexOf( "." );
        if( idx != -1 )
        {
            extensions = extensions.substring( idx + 1 );
        }

        MetadataService metadataService = getApplication().getMetadataService();
        Metadata metadata = metadataService.getMetadata( extensions );
        if( metadata != null && metadata instanceof MediaType )
        {
            request.getClientInfo()
                .setAcceptedMediaTypes( Collections.singletonList( new Preference<>( (MediaType) metadata ) ) );
            String path = request.getResourceRef().getPath();
            path = path.substring( 0, path.length() - extensions.length() - 1 );
            request.getResourceRef().setPath( path );
        }
    }

    return Filter.CONTINUE;
}
 
Example 59
Project: polygene-java   File: JSONResponseReader.java   Source Code and License 5 votes vote down vote up
@Override
public Object readResponse( Response response, Class<?> resultType )
{
    if( response.getEntity().getMediaType().equals( MediaType.APPLICATION_JSON ) )
    {
        if( ValueComposite.class.isAssignableFrom( resultType ) )
        {
            String jsonValue = response.getEntityAsText();
            ValueCompositeType valueType = module.valueDescriptor( resultType.getName() ).valueType();
            return jsonDeserializer.deserialize( module, valueType, jsonValue );
        }
        else if( resultType.equals( Form.class ) )
        {
            try( JsonReader reader = jsonFactories.readerFactory()
                                                  .createReader( response.getEntity().getReader() ) )
            {
                JsonObject jsonObject = reader.readObject();
                Form form = new Form();
                jsonObject.forEach(
                    ( key, value ) ->
                    {
                        String valueString = value.getValueType() == JsonValue.ValueType.STRING
                                             ? ( (JsonString) value ).getString()
                                             : value.toString();
                        form.set( key, valueString );
                    } );
                return form;
            }
            catch( IOException | JsonException e )
            {
                throw new ResourceException( e );
            }
        }
    }
    return null;
}
 
Example 60
Project: ontopia   File: JacksonRepresentationImpl.java   Source Code and License 5 votes vote down vote up
@Override
protected ObjectMapper createObjectMapper() {
	ObjectMapper mapper = super.createObjectMapper();
	mapper.addMixInAnnotations(LocatorIF.class, MLocator.class);
	mapper.addMixInAnnotations(TopicIF.class, MTopic.class);
	mapper.addMixInAnnotations(TopicNameIF.class, MTopicName.class);
	mapper.addMixInAnnotations(VariantNameIF.class, MVariantName.class);
	mapper.addMixInAnnotations(OccurrenceIF.class, MOccurrence.class);
	mapper.addMixInAnnotations(AssociationIF.class, MAssociation.class);
	mapper.addMixInAnnotations(AssociationRoleIF.class, MAssociationRole.class);
	mapper.addMixInAnnotations(TopicMapIF.class, MTopicMapAsValue.class);
	mapper.addMixInAnnotations(TopicMapReferenceIF.class, MTopicMapReference.class);
	mapper.addMixInAnnotations(TopicMapSourceIF.class, MTopicMapSource.class);
	
	@SuppressWarnings("unchecked")
	Map<Class<?>, Class<?>> additional = (Map<Class<?>, Class<?>>) Response.getCurrent().getAttributes().get(ADDITIONAL_MIXINS_ATTRIBUTE);

	if ((additional != null) && (!additional.isEmpty())) {
		for (Map.Entry<Class<?>, Class<?>> entry : additional.entrySet()) {
			mapper.addMixInAnnotations(entry.getKey(), entry.getValue());
		}
	}
	
	for (JsonParser.Feature feature : JsonParser.Feature.values()) {
		Parameter parameter = ContextUtils.getParameter(ContextUtils.getCurrentApplicationContext(), JSONPARSER_FEATURE + feature.name());
		if (parameter != null) {
			mapper.configure(feature, ContextUtils.getParameterAsBoolean(parameter, feature.enabledByDefault() || DEFAULT_PARSER_FEATURES.contains(feature)));
		}
	}
	
	return mapper;
}