Java Code Examples for org.restlet.Request

The following are top voted examples for showing how to use org.restlet.Request. 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: 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 8
Project: prudence   File: ResolvingRedirector.java   Source Code and License 6 votes vote down vote up
@Override
protected Reference getTargetRef( Request request, Response response )
{
	// This is essentially the original Restlet code modified to use
	// ResolvingTemplate.

	// Create the template
	Template rt = new ResolvingTemplate( this.targetTemplate );
	rt.setLogger( getLogger() );

	// Return the formatted target URI
	if( new Reference( this.targetTemplate ).isRelative() )
		// Be sure to keep the resource's base reference.
		return new Reference( request.getResourceRef(), rt.format( request, response ) );

	return new Reference( rt.format( request, response ) );
}
 
Example 9
Project: polygene-java   File: AbstractResponseWriter.java   Source Code and License 6 votes vote down vote up
protected Variant getVariant( Request request,
                              List<Language> possibleLanguages,
                              List<MediaType> possibleMediaTypes
)
{
    Language language = request.getClientInfo().getPreferredLanguage( possibleLanguages );

    if( language == null )
    {
        language = possibleLanguages.get( 0 );
    }

    MediaType responseType = request.getClientInfo().getPreferredMediaType( possibleMediaTypes );

    if( responseType == null && request.getClientInfo()
                                    .getPreferredMediaType( Collections.singletonList( MediaType.ALL ) ) == MediaType.ALL )
    {
        responseType = possibleMediaTypes.get( 0 );
    }

    Variant variant = new Variant( responseType, language );
    variant.setCharacterSet( CharacterSet.UTF_8 );

    return variant;
}
 
Example 10
Project: microservices-comparison   File: RemoteCarService.java   Source Code and License 6 votes vote down vote up
@Override
public List<Car> list() {
    Client client = new Client(new Context(), Protocol.HTTPS);
    Series<Parameter> parameters = client.getContext().getParameters();
    parameters.add("truststorePath", System.getProperty("javax.net.ssl.trustStore"));

    ClientResource clientResource = new ClientResource("https://localhost:8043/api/cars/cars");
    clientResource.setNext(client);
    ChallengeResponse challenge = new ChallengeResponse(ChallengeScheme.HTTP_OAUTH_BEARER);
    challenge.setRawValue(Request.getCurrent().getAttributes().getOrDefault("token", "").toString());
    clientResource.setChallengeResponse(challenge);
    CarServiceInterface carServiceInterface = clientResource.wrap(CarServiceInterface.class);
    Car[] allCars = carServiceInterface.getAllCars();
    try {
        client.stop();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    return asList(allCars);
}
 
Example 11
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 12
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 13
Project: cyclops-rc   File: McnPuller.java   Source Code and License 6 votes vote down vote up
/**
 * Pull data from provided URL
 * @param url
 * @return output string or empty string
 */
private String pullData(String url) throws IOException {
    Client client = new Client(Protocol.HTTP);
    ClientResource cr = new ClientResource(url);
    Request req = cr.getRequest();

    // now header
    Series<Header> headerValue = new Series<Header>(Header.class);
    req.getAttributes().put(HeaderConstants.ATTRIBUTE_HEADERS, headerValue);
    headerValue.add("Accept", "application/json");
    headerValue.add("Content-Type", "application/json");

    // fire it up
    cr.get(MediaType.APPLICATION_JSON);
    Representation output = cr.getResponseEntity();

    // return null or received text
    return (output == null) ? "" : output.getText();
}
 
Example 14
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 15
Project: prudence   File: DelegatedResource.java   Source Code and License 6 votes vote down vote up
/**
 * Initializes the resource, and delegates to the <code>handleInit()</code>
 * entry point in the executable.
 */
@Override
protected void doInit() throws ResourceException
{
	super.doInit();
	setAnnotated( false );

	if( attributes.isSourceViewable() )
	{
		Request request = getRequest();
		Form query = request.getResourceRef().getQueryAsForm();
		if( TRUE.equals( query.getFirstValue( SOURCE ) ) )
			// Bypass doInit delegation
			return;
	}

	DelegatedResourceConversationService conversationService = new DelegatedResourceConversationService( this, null, null, attributes.getDefaultCharacterSet() );
	enter( attributes.getEntryPointNameForInit(), true, conversationService );
}
 
Example 16
Project: prudence   File: PhpExecutionController.java   Source Code and License 6 votes vote down vote up
public void initialize( ExecutionContext executionContext ) throws ExecutionException
{
	Request request = Request.getCurrent();

	LazyInitializationGet exposedGet = new LazyInitializationGet( request );
	LazyInitializationFile exposedFile = new LazyInitializationFile( request, fileItemFactory );
	LazyInitializationPost exposedPost = new LazyInitializationPost( request, exposedFile );
	LazyInitializationCookie exposedCookie = new LazyInitializationCookie( request );
	LazyInitializationRequest exposedRequest = new LazyInitializationRequest( exposedGet, exposedPost, exposedCookie );

	// Note that our maps will only contain the last parameter in case of
	// duplicates. This is PHP's defined behavior.

	executionContext.getServices().put( "_GET", Collections.unmodifiableMap( exposedGet ) );
	executionContext.getServices().put( "_FILE", Collections.unmodifiableMap( exposedFile ) );
	executionContext.getServices().put( "_POST", Collections.unmodifiableMap( exposedPost ) );
	executionContext.getServices().put( "_COOKIE", Collections.unmodifiableMap( exposedCookie ) );
	executionContext.getServices().put( "_REQUEST", Collections.unmodifiableMap( exposedRequest ) );
}
 
Example 17
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 18
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 19
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 20
Project: cf-mta-deploy-service   File: CustomActivitiRestAuthenticator.java   Source Code and License 5 votes vote down vote up
@Override
public boolean requestRequiresAuthentication(Request request) {
    
    // Get relevant information from the request
    String userId = getUserId(request);
    String userId2 = getUserIdFromHeader(request);
    String password = getPassword(request);
    String apiCalled = getApiCalled(request);
    
    // Check if the user is authorized to perform the operation
    ensureUserIsAuthorized(apiCalled, userId);

    // If the BASIC authentication header is present and the user is the session user,
    // persist the user in the Activiti database
    if (userId2 != null && password != null && userId2.equals(userId)) {
        persistUser(userId, password);
    }
    
    // Set authenticated user id for this Activiti thread
    Authentication.setAuthenticatedUserId(userId);
    
    // Update request client info
    setRequestClientInfo(request, userId);
    
    // Return false to skip any Activiti-specific authentication
    return false;
}
 
Example 21
Project: cf-mta-deploy-service   File: CustomActivitiRestAuthenticator.java   Source Code and License 5 votes vote down vote up
private void setRequestClientInfo(Request request, String userId) {
    ClientInfo ci = request.getClientInfo();
    User user = new User();
    user.setIdentifier(userId);
    ci.setUser(user);
    request.setClientInfo(ci);
}
 
Example 22
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 23
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 24
Project: eSDK_FC_SDK_Java   File: RestletClient.java   Source Code and License 5 votes vote down vote up
/**
 * 设置标准http header
 * 
 * @param request {@code void}
 * @since eSDK Cloud V100R003C50
 */
private void setDefaultHttpHeader(Request request, String version)
{
	ClientInfo clientInfo = new ClientInfo();

	List<Preference<MediaType>> acceptedMediaTypes = new ArrayList<Preference<MediaType>>();
	Preference<MediaType> preferenceMediaType = new Preference<MediaType>();

	String acceptStr = "application/json;";
	if (null == version)
	{
		acceptStr += "charset=UTF-8;";
	}
	else
	{
		acceptStr += version + "charset=UTF-8;";
	}
	MediaType mediaType = MediaType.register(acceptStr, "");
	preferenceMediaType.setMetadata(mediaType);
	acceptedMediaTypes.add(preferenceMediaType);
	clientInfo.setAcceptedMediaTypes(acceptedMediaTypes);

	List<Preference<Language>> acceptedLanguages = new ArrayList<Preference<Language>>();

	Preference<Language> preferenceLanguage = new Preference<Language>();
	Language language = new Language("zh_CN", "");
	preferenceLanguage.setMetadata(language);
	acceptedLanguages.add(preferenceLanguage);

	clientInfo.setAcceptedLanguages(acceptedLanguages);
	request.setClientInfo(clientInfo);
}
 
Example 25
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 26
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 27
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 28
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 29
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 30
Project: bigstreams   File: CoordinationFileTrackingResource.java   Source Code and License 5 votes vote down vote up
@Get("json")
public Collection<FileTrackingStatus> getFileTrackingStatusList() {
	List<Range> ranges = getRanges();

	Request request = super.getRequest();

	Reference resource = request.getResourceRef();
	String query = resource.getQueryAsForm().getFirstValue("query");

	int from = 0, max = 1000;

	if (ranges != null && ranges.size() > 0) {
		Range range = ranges.get(0);
		from = (int) range.getIndex();
		max = (int) range.getSize();
	}

	Collection<FileTrackingStatus> coll = (query == null) ? fileTrackerMemory
			.getFiles(from, max) : fileTrackerMemory.getFilesByQuery(query,
			from, max);

	//sort by file date
	List<FileTrackingStatus> list = null;
	if(coll instanceof List){
		list = (List<FileTrackingStatus>)coll;
	}else{
		list = new ArrayList<FileTrackingStatus>(coll);
	}
	
	Collections.sort(list, FileDateComparator.INSTANCE);
	
	return coll;
}
 
Example 31
Project: bigstreams   File: CoordinationFileTrackingHistoryResource.java   Source Code and License 5 votes vote down vote up
@Get("json")
public Collection<FileTrackerHistoryItem> getAgentHistory() {
	List<Range> ranges = getRanges();

	Request request = super.getRequest();

	Reference resource = request.getResourceRef();
	Form form = resource.getQueryAsForm();

	String agentName = form.getFirstValue("agent");

	if (agentName == null) {
		agentName = (String) getRequestAttributes().get("agent");
	}

	Collection<FileTrackerHistoryItem> coll = null;

	if (agentName != null) {
		int from = 0, max = 1000;

		if (ranges != null && ranges.size() > 0) {
			Range range = ranges.get(0);
			from = (int) range.getIndex();
			max = (int) range.getSize();
		}

		coll = fileTrackerMemory.getAgentHistory(agentName, from, max);
	}

	if (coll == null) {
		coll = new ArrayList<FileTrackerHistoryItem>();
	}

	return coll;
}
 
Example 32
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 33
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 34
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 35
Project: uReplicator   File: ControllerRequestURLBuilder.java   Source Code and License 5 votes vote down vote up
public Request getTopicExternalViewRequestUrl(String topic) {
  String requestUrl = StringUtils.join(new String[]{
      _baseUrl, "/topics/", topic
  });

  Request request = new Request(Method.GET, requestUrl);
  return request;
}
 
Example 36
Project: uReplicator   File: ControllerRequestURLBuilder.java   Source Code and License 5 votes vote down vote up
public Request getTopicDeleteRequestUrl(String topic) {
  String requestUrl = StringUtils.join(new String[]{
      _baseUrl, "/topics/", topic
  });

  Request request = new Request(Method.DELETE, requestUrl);
  return request;
}
 
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: ControllerRequestURLBuilder.java   Source Code and License 5 votes vote down vote up
public Request getTopicExternalViewRequestUrl(String topic) {
  String requestUrl = StringUtils.join(new String[] {
      _baseUrl, "/topics/", topic
  });

  Request request = new Request(Method.GET, requestUrl);
  return request;
}
 
Example 43
Project: chaperone   File: ControllerRequestURLBuilder.java   Source Code and License 5 votes vote down vote up
public Request getTopicDeleteRequestUrl(String topic) {
  String requestUrl = StringUtils.join(new String[] {
      _baseUrl, "/topics/", topic
  });

  Request request = new Request(Method.DELETE, requestUrl);
  return request;
}
 
Example 44
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 45
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 46
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 47
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 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
protected Locale getLocale()
{
    Request request = Request.getCurrent();

    List<Preference<Language>> preferenceList = request.getClientInfo().getAcceptedLanguages();

    if( preferenceList.isEmpty() )
    {
        return Locale.getDefault();
    }

    Language language = preferenceList
        .get( 0 ).getMetadata();
    String[] localeStr = language.getName().split( "-" );

    Locale locale;
    switch( localeStr.length )
    {
    case 1:
        locale = new Locale( localeStr[ 0 ] );
        break;
    case 2:
        locale = new Locale( localeStr[ 0 ], localeStr[ 1 ] );
        break;
    case 3:
        locale = new Locale( localeStr[ 0 ], localeStr[ 1 ], localeStr[ 2 ] );
        break;
    default:
        locale = Locale.getDefault();
    }
    return locale;
}
 
Example 55
Project: search   File: TestRestManager.java   Source Code and License 5 votes vote down vote up
@Test
public void testResolveResourceIdDecodeUrlEntities () throws Exception {
  Request testRequest = new Request();
  Reference rootRef = new Reference("http://solr.apache.org/");
  testRequest.setRootRef(rootRef);

  Reference resourceRef = new Reference("http://solr.apache.org/schema/analysis/synonyms/de/%C3%84ndern");
  testRequest.setResourceRef(resourceRef);

  String resourceId = RestManager.ManagedEndpoint.resolveResourceId(testRequest);
  assertEquals(resourceId, "/schema/analysis/synonyms/de/Ändern");
}
 
Example 56
Project: SecureBPMN   File: ActivitiRestApplication.java   Source Code and License 5 votes vote down vote up
public String authenticate(Request request, Response response) {
  if (!request.getClientInfo().isAuthenticated()) {
    authenticator.challenge(response, false);
    return null;
  }
  return request.getClientInfo().getUser().getIdentifier();
}
 
Example 57
Project: polygene-java   File: ContextResource.java   Source Code and License 5 votes vote down vote up
private Object convert( Object result )
{
    if( converter != null )
    {
        result = converter.convert( result, Request.getCurrent(), (Object[]) Request.getCurrent()
            .getAttributes()
            .get( ARGUMENTS ) );
    }

    return result;
}
 
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>( (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: 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 60
Project: MCRest   File: AuthResourceTest.java   Source Code and License 5 votes vote down vote up
private Response getRequestResult(String path) {
    Client client =  new Client(Protocol.HTTP);
    Request request = new Request(Method.GET, serverUrl+path);
    Response response = client.handle(request);
    String s = response.getEntityAsText();
    return response;
}