org.restlet.Context Java Examples

The following examples show how to use org.restlet.Context. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Api.java    From vicinity-gateway-api with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Constructor, initialises necessary objects and inserts the {@link org.apache.commons.configuration2.XMLConfiguration
 * configuration}, {@link java.util.logging.Logger logger} and {@link eu.bavenir.ogwapi.xmpp.CommunicationManager
 * CommunicationNode} into the RESTLET {@link org.restlet.Context context}.
 * 
 * All parameters are mandatory, failure to include them will lead to a swift end of application execution.
 * 
 * @param config Configuration object.
 * @param logger Java logger.
 */
public Api(XMLConfiguration config, Logger logger, MessageCounter messageCounter){
	this.config = config;
	this.logger = logger;
	
	// this will initialise the CommunicationNode
	communicationManager = new CommunicationManager(config, logger, messageCounter);
	
	// insert stuff into context
	applicationContext = new Context();
	
	applicationContext.getAttributes().put(CONTEXT_CONFIG, config);
	applicationContext.getAttributes().put(CONTEXT_LOGGER, logger);
	applicationContext.getAttributes().put(CONTEXT_COMMMANAGER, communicationManager);
	
	applicationContext.setLogger(logger);
	
	setContext(applicationContext);
	
	// load authentication challenge scheme method from configuration
	configureChallengeScheme();
}
 
Example #2
Source File: Tag.java    From DeviceConnect-Android with MIT License 6 votes vote down vote up
/**
 * Parses a tag formatted as defined by the HTTP standard.
 * 
 * @param httpTag
 *            The HTTP tag string; if it starts with 'W/' the tag will be
 *            marked as weak and the data following the 'W/' used as the
 *            tag; otherwise it should be surrounded with quotes (e.g.,
 *            "sometag").
 * @return A new tag instance.
 * @see <a
 *      href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.11">HTTP
 *      Entity Tags</a>
 */
public static Tag parse(String httpTag) {
    Tag result = null;
    boolean weak = false;
    String httpTagCopy = httpTag;

    if (httpTagCopy.startsWith("W/")) {
        weak = true;
        httpTagCopy = httpTagCopy.substring(2);
    }

    if (httpTagCopy.startsWith("\"") && httpTagCopy.endsWith("\"")) {
        result = new Tag(
                httpTagCopy.substring(1, httpTagCopy.length() - 1), weak);
    } else if (httpTagCopy.equals("*")) {
        result = new Tag("*", weak);
    } else {
        Context.getCurrentLogger().log(Level.WARNING,
                "Invalid tag format detected: " + httpTagCopy);
    }

    return result;
}
 
Example #3
Source File: FormUtils.java    From DeviceConnect-Android with MIT License 6 votes vote down vote up
/**
 * Parses a post into a given form.
 * 
 * @param form
 *            The target form.
 * @param post
 *            The posted form.
 * @param decode
 *            Indicates if the parameters should be decoded.
 */
public static void parse(Form form, Representation post, boolean decode) {
    if (post != null) {
        if (post.isAvailable()) {
            FormReader fr = null;

            try {
                fr = new FormReader(post, decode);
            } catch (IOException ioe) {
                Context.getCurrentLogger().log(Level.WARNING,
                        "Unable to create a form reader. Parsing aborted.",
                        ioe);
            }

            if (fr != null) {
                fr.addParameters(form);
            }
        } else {
            Context.getCurrentLogger()
                    .log(Level.FINE,
                            "The form wasn't changed as the given representation isn't available.");
        }
    }
}
 
Example #4
Source File: InputRepresentation.java    From DeviceConnect-Android with MIT License 6 votes vote down vote up
/**
 * Closes and releases the input stream.
 */
@Override
public void release() {
    if (this.stream != null) {
        try {
            this.stream.close();
        } catch (IOException e) {
            Context.getCurrentLogger().log(Level.WARNING,
                    "Error while releasing the representation.", e);
        }

        this.stream = null;
    }

    super.release();
}
 
Example #5
Source File: Reference.java    From DeviceConnect-Android with MIT License 6 votes vote down vote up
/**
     * Decodes a given string using the standard URI encoding mechanism. If the
     * provided character set is null, the string is returned but not decoded.
     * <em><strong>Note:</strong> The <a
     * href="http://www.w3.org/TR/html40/appendix/notes.html#non-ascii-chars">
     * World Wide Web Consortium Recommendation</a> states that UTF-8 should be
     * used. Not doing so may introduce incompatibilities.</em>
     * 
     * @param toDecode
     *            The string to decode.
     * @param characterSet
     *            The name of a supported character encoding.
     * @return The decoded string or null if the named character encoding is not
     *         supported.
     */
    public static String decode(String toDecode, CharacterSet characterSet) {
//        if (Edition.CURRENT == Edition.GWT) {
//            if (!CharacterSet.UTF_8.equals(characterSet)) {
//                throw new IllegalArgumentException(
//                        "Only UTF-8 URL encoding is supported under GWT");
//            }
//        }
        String result = null;
        try {
            result = (characterSet == null) ? toDecode : java.net.URLDecoder
                    .decode(toDecode, characterSet.getName());
        } catch (UnsupportedEncodingException uee) {
            Context.getCurrentLogger()
                    .log(Level.WARNING,
                            "Unable to decode the string with the UTF-8 character set.",
                            uee);
        }


        return result;
    }
 
Example #6
Source File: StringRepresentation.java    From DeviceConnect-Android with MIT License 6 votes vote down vote up
/**
 * Updates the expected size according to the current string value.
 */
protected void updateSize() {
    if (getText() != null) {
        try {
            if (getCharacterSet() != null) {
                setSize(getText().getBytes(getCharacterSet().getName()).length);
            } else {
                setSize(getText().getBytes().length);
            }
        } catch (UnsupportedEncodingException e) {
            Context.getCurrentLogger().log(Level.WARNING,
                    "Unable to update size", e);
            setSize(UNKNOWN_SIZE);
        }
    } else {
        setSize(UNKNOWN_SIZE);
    }
}
 
Example #7
Source File: Representation.java    From DeviceConnect-Android with MIT License 6 votes vote down vote up
/**
 * Sets a listener for NIO read events. If the listener is null, it clear
 * any existing listener.
 * 
 * @param readingListener
 *            The listener for NIO read events.
 */
public void setListener(org.restlet.util.ReadingListener readingListener) {
    try {
        org.restlet.util.SelectionRegistration sr = getRegistration();

        if ((readingListener == null)) {
            sr.setNoInterest();
        } else {
            sr.setReadInterest();
        }

        sr.setSelectionListener(readingListener);
    } catch (IOException ioe) {
        Context.getCurrentLogger().log(Level.WARNING,
                "Unable to register the reading listener", ioe);
    }
}
 
Example #8
Source File: ReadingListener.java    From DeviceConnect-Android with MIT License 6 votes vote down vote up
/**
 * Callback invoked when new content is available. It reads the available
 * bytes from the source channel into an internal buffer then calls
 * {@link #onContent(ByteBuffer)} method or the {@link #onEnd()} method or
 * the {@link #onError(IOException)} method.
 */
public final void onSelected(SelectionRegistration selectionRegistration)
        throws IOException {
    try {
        synchronized (this.byteBuffer) {
            this.byteBuffer.clear();
            int result = this.byteChannel.read(this.byteBuffer);

            if (result > 0) {
                this.byteBuffer.flip();
                onContent(this.byteBuffer);
            } else if (result == -1) {
                onEnd();
            } else {
                Context.getCurrentLogger().fine(
                        "NIO selection detected with no content available");
            }
        }
    } catch (IOException ioe) {
        onError(ioe);
    }
}
 
Example #9
Source File: CoreWebRoutable.java    From floodlight_with_topoguard with Apache License 2.0 6 votes vote down vote up
@Override
public Restlet getRestlet(Context context) {
    Router router = new Router(context);
    router.attach("/module/all/json", ModuleLoaderResource.class);
    router.attach("/module/loaded/json", LoadedModuleLoaderResource.class);
    router.attach("/switch/{switchId}/role/json", SwitchRoleResource.class);
    router.attach("/switch/all/{statType}/json", AllSwitchStatisticsResource.class);
    router.attach("/switch/{switchId}/{statType}/json", SwitchStatisticsResource.class);
    router.attach("/controller/switches/json", ControllerSwitchesResource.class);
    router.attach("/counter/{counterTitle}/json", CounterResource.class);
    router.attach("/counter/{switchId}/{counterName}/json", SwitchCounterResource.class);
    router.attach("/counter/categories/{switchId}/{counterName}/{layer}/json", SwitchCounterCategoriesResource.class);
    router.attach("/memory/json", ControllerMemoryResource.class);
    router.attach("/packettrace/json", PacketTraceResource.class);
    router.attach("/storage/tables/json", StorageSourceTablesResource.class);
    router.attach("/controller/summary/json", ControllerSummaryResource.class);
    router.attach("/role/json", ControllerRoleResource.class);
    router.attach("/health/json", HealthCheckResource.class);
    router.attach("/system/uptime/json", SystemUptimeResource.class);
    return router;
}
 
Example #10
Source File: LocalOAuth2Main.java    From DeviceConnect-Android with MIT License 6 votes vote down vote up
/**
 * Intentの共通設定処理
 *
 * @param context コンテキスト
 * @param request リクエストパラメータ
 * @param displayScopes 要求する権限のリスト
 * @param intent Intent
 */
private void putExtras(android.content.Context context, ConfirmAuthRequest request, String[] displayScopes, Intent intent) {
    long threadId = request.getThreadId();
    ConfirmAuthParams params = request.getConfirmAuthParams();
    intent.putExtra(ConfirmAuthActivity.EXTRA_THREAD_ID, threadId);
    if (params.getServiceId() != null) {
        intent.putExtra(ConfirmAuthActivity.EXTRA_SERVICE_ID, params.getServiceId());
    }
    intent.putExtra(ConfirmAuthActivity.EXTRA_APPLICATION_NAME, params.getApplicationName());
    intent.putExtra(ConfirmAuthActivity.EXTRA_SCOPES, params.getScopes());
    intent.putExtra(ConfirmAuthActivity.EXTRA_DISPLAY_SCOPES, displayScopes);
    intent.putExtra(ConfirmAuthActivity.EXTRA_REQUEST_TIME, request.getRequestTime());
    intent.putExtra(ConfirmAuthActivity.EXTRA_IS_FOR_DEVICEPLUGIN, params.isForDevicePlugin());
    if (!params.isForDevicePlugin()) {
        intent.putExtra(ConfirmAuthActivity.EXTRA_PACKAGE_NAME, context.getPackageName());
        intent.putExtra(ConfirmAuthActivity.EXTRA_KEYWORD, params.getKeyword());
    }
    intent.putExtra(ConfirmAuthActivity.EXTRA_AUTO_FLAG, request.isAutoFlag());
}
 
Example #11
Source File: RemoteCarService.java    From microservices-comparison with Apache License 2.0 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 #12
Source File: IndexingUIDOperation.java    From bonita-studio with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
    monitor.subTask(Messages.indexingUIDPages);
    PageDesignerURLFactory urlBuilder = pageDesignerURLBuilder == null
            ? new PageDesignerURLFactory(getPreferenceStore()) : pageDesignerURLBuilder;
    URI uri = null;
    try {
        uri = urlBuilder.indexation().toURI();
    } catch (MalformedURLException | URISyntaxException e1) {
        throw new InvocationTargetException(new MigrationException(e1));
    }
    Context currentContext = Context.getCurrent();
    try {
        ClientResource clientResource = new ClientResource(uri);
        clientResource.setRetryOnError(true);
        clientResource.setRetryDelay(500);
        clientResource.setRetryAttempts(10);
        clientResource.post(new EmptyRepresentation());
    } catch (ResourceException e) {
        throw new InvocationTargetException(new MigrationException(e),
                "Failed to post on " + uri);
    }finally {
        Context.setCurrent(currentContext);
    }
}
 
Example #13
Source File: WorkerStarter.java    From uReplicator with Apache License 2.0 6 votes vote down vote up
public void runRestApplication() throws Exception {
  if (workerConf.getWorkerPort() == 0) {
    return;
  }
  Component _component = new Component();
  _component.getServers().add(Protocol.HTTP, workerConf.getWorkerPort());
  _component.getClients().add(Protocol.FILE);
  _component.getClients().add(Protocol.JAR);

  Context applicationContext = _component.getContext().createChildContext();
  LOGGER.info("Injecting workerInstance to the api context, port {}", workerConf.getWorkerPort());
  applicationContext.getAttributes().put(WorkerInstance.class.toString(), workerInstance);

  Application restletApplication = new RestletApplication(null);
  restletApplication.setContext(applicationContext);

  _component.getDefaultHost().attach(restletApplication);
  _component.start();
}
 
Example #14
Source File: DefaultResourceFactoryImpl.java    From attic-polygene-java with Apache License 2.0 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 #15
Source File: PurdueCourseRequestsValidationProvider.java    From unitime with Apache License 2.0 6 votes vote down vote up
public PurdueCourseRequestsValidationProvider() {
	List<Protocol> protocols = new ArrayList<Protocol>();
	protocols.add(Protocol.HTTP);
	protocols.add(Protocol.HTTPS);
	iClient = new Client(protocols);
	Context cx = new Context();
	cx.getParameters().add("readTimeout", getSpecialRegistrationApiReadTimeout());
	try {
		String clazz = ApplicationProperty.CustomizationExternalTerm.value();
		if (clazz == null || clazz.isEmpty())
			iExternalTermProvider = new BannerTermProvider();
		else
			iExternalTermProvider = (ExternalTermProvider)Class.forName(clazz).getConstructor().newInstance();
	} catch (Exception e) {
		sLog.error("Failed to create external term provider, using the default one instead.", e);
		iExternalTermProvider = new BannerTermProvider();
	}
}
 
Example #16
Source File: RoleRouter.java    From ontopia with Apache License 2.0 6 votes vote down vote up
public RoleRouter(Context context) {
	super(context);
	
	setName("Role router");
	setDescription("Binds the resources related to association role operations");
	
	attach("", RoleResource.class);

	// list
	// ClassInstanceIndexIF.getAssociationRoles
	attach("/typed/{roletype}", RolesResource.class);

	// ClassInstanceIndexIF.getAssociationRoleTypes
	attach("/types", RoleTypesResource.class);

	// single
	attach("/{id}", RoleResource.class);
}
 
Example #17
Source File: SelectionRegistration.java    From DeviceConnect-Android with MIT License 6 votes vote down vote up
/**
 * Unblocks the optionally blocked thread.
 * 
 * @throws IOException
 * 
 * @see #block()
 */
public void unblock() throws IOException {
    if (Context.getCurrentLogger().isLoggable(Level.FINEST)) {
        Context.getCurrentLogger().log(
                Level.FINEST,
                "Calling thread about to unblock the NIO selection registration. Timeout: "
                        + TimeUnit.MILLISECONDS
                                .toMillis(/*IoUtils.TIMEOUT_MS*/60000)
                        + " ms. Waiting: "
                        + this.barrier.getNumberWaiting());
    }

    try {
        this.barrier.await(/*IoUtils.TIMEOUT_MS*/60000, TimeUnit.MILLISECONDS);
    } catch (Exception e) {
        Context.getCurrentLogger()
                .log(Level.WARNING,
                        "Unable to unblock the waiting thread at the cyclic barrier",
                        e);
        IOException ioe = new IOException(
                "Unable to unblock the waiting thread at the cyclic barrier.");
        ioe.initCause(e);
        throw ioe;
    }
}
 
Example #18
Source File: MigrateUIDOperation.java    From bonita-studio with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
    monitor.subTask(Messages.migratingUID);
    PageDesignerURLFactory urlBuilder = pageDesignerURLBuilder == null
            ? new PageDesignerURLFactory(getPreferenceStore()) : pageDesignerURLBuilder;
    URI uri = null;
    try {
        uri = urlBuilder.migrate().toURI();
    } catch (MalformedURLException | URISyntaxException e1) {
        throw new InvocationTargetException(new MigrationException(e1));
    }
    Context currentContext = Context.getCurrent();
    try {
        ClientResource clientResource = new ClientResource(uri);
        clientResource.setRetryOnError(true);
        clientResource.setRetryDelay(500);
        clientResource.setRetryAttempts(10);
        clientResource.post(new EmptyRepresentation());
    } catch (ResourceException e) {
        throw new InvocationTargetException(new MigrationException(e),
                "Failed to post on " + uri);
    }finally {
        Context.setCurrent(currentContext);
    }
}
 
Example #19
Source File: OccurrenceRouter.java    From ontopia with Apache License 2.0 6 votes vote down vote up
public OccurrenceRouter(Context context) {
	super(context);
	
	setName("Occurrence router");
	setDescription("Binds the resources related to occurrence operations");

	//add
	attach("", OccurrenceResource.class);

	// list
	// ClassInstanceIndexIF.getOccurrences
	attach("/typed/{type}", OccurrencesResource.class);

	// ClassInstanceIndexIF.getOccurrenceTypes
	attach("/types", OccurrenceTypesResource.class);
	
	// OccurrenceIndexIF
	attach("/index/{type}", IndexResource.class);

	// single
	attach("/{id}", OccurrenceResource.class);
}
 
Example #20
Source File: NamesRouter.java    From ontopia with Apache License 2.0 6 votes vote down vote up
public NamesRouter(Context context) {
	super(context);
	
	setName("Names router");
	setDescription("Binds the resources related to name operations");

	//add
	attach("", TopicNameResource.class);

	// list
	// ClassInstanceIndexIF.getTopicNames
	attach("/typed/{type}", TopicNamesResource.class);
	
	// ClassInstanceIndexIF.getTopicNameTypes
	attach("/types", TopicNameTypesResource.class);
	
	// NameIndexIF.getTopicNames
	attach("/index", IndexResource.class);

	// single
	attach("/{id}", TopicNameResource.class);
	
	// variants
	attach("/{topicname}/variants", VariantsResource.class);
	
}
 
Example #21
Source File: TicketGrantingTicketResource.java    From springboot-shiro-cas-mybatis with MIT 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 #22
Source File: ContextUtils.java    From ontopia with Apache License 2.0 5 votes vote down vote up
public static Context getCurrentApplicationContext() {
	Application application = Application.getCurrent();
	if (application == null) {
		return null;
	}
	return application.getContext();
}
 
Example #23
Source File: TopologyWebRoutable.java    From floodlight_with_topoguard with Apache License 2.0 5 votes vote down vote up
/**
 * Create the Restlet router and bind to the proper resources.
 */
@Override
public Router getRestlet(Context context) {
    Router router = new Router(context);
    router.attach("/links/json", LinksResource.class);
    router.attach("/directed-links/json", DirectedLinksResource.class);
    router.attach("/external-links/json", ExternalLinksResource.class);
    router.attach("/tunnellinks/json", TunnelLinksResource.class);
    router.attach("/switchclusters/json", SwitchClustersResource.class);
    router.attach("/broadcastdomainports/json", BroadcastDomainPortsResource.class);
    router.attach("/enabledports/json", EnabledPortsResource.class);
    router.attach("/blockedports/json", BlockedPortsResource.class);
    router.attach("/route/{src-dpid}/{src-port}/{dst-dpid}/{dst-port}/json", RouteResource.class);
    return router;
}
 
Example #24
Source File: OntopiaRestApplication.java    From ontopia with Apache License 2.0 5 votes vote down vote up
public OntopiaRestApplication(Context context) {
	super(context);
	objectResolver = new DefaultParameterResolver(this);
	topicmapResolver = new DefaultTopicMapResolver();
	
	setStatusService(new OntopiaStatusService());
	
	getConnegService().setStrict(ContextUtils.getParameterAsBoolean(context, Constants.STRICT_MIME_MATCHING_PARAMETER, true));
}
 
Example #25
Source File: FirewallWebRoutable.java    From floodlight_with_topoguard with Apache License 2.0 5 votes vote down vote up
/**
 * Create the Restlet router and bind to the proper resources.
 */
@Override
public Router getRestlet(Context context) {
    Router router = new Router(context);
    router.attach("/module/{op}/json", FirewallResource.class);
    router.attach("/rules/json", FirewallRulesResource.class);
    return router;
}
 
Example #26
Source File: RestApplication.java    From attic-polygene-java with Apache License 2.0 5 votes vote down vote up
public RestApplication( @Uses Context parentContext )
{
    super( parentContext );

    getMetadataService().addExtension( "srj", APPLICATION_SPARQL_JSON );

    getTunnelService().setExtensionsTunnel( true );
}
 
Example #27
Source File: SelectionRegistration.java    From DeviceConnect-Android with MIT License 5 votes vote down vote up
/**
 * Resume interest in new listener notifications. This should be called
 * after a {@link #suspend()} call.
 */
public void resume() {
    if (Context.getCurrentLogger().isLoggable(Level.FINER)) {
        Context.getCurrentLogger().log(Level.FINER,
                "Resuming previous NIO interest");
    }

    setInterestOperations(this.previousInterest);
}
 
Example #28
Source File: DebugEventRoutable.java    From floodlight_with_topoguard with Apache License 2.0 5 votes vote down vote up
@Override
public Restlet getRestlet(Context context) {
    Router router = new Router(context);
    router.attach("/{param1}/{param2}/", DebugEventResource.class);
    router.attach("/{param1}/{param2}", DebugEventResource.class);
    router.attach("/{param1}/", DebugEventResource.class);
    router.attach("/{param1}", DebugEventResource.class);
    router.attach("/", DebugEventResource.class);
    return router;
}
 
Example #29
Source File: DeviceRoutable.java    From floodlight_with_topoguard with Apache License 2.0 5 votes vote down vote up
@Override
public Restlet getRestlet(Context context) {
    Router router = new Router(context);
    router.attach("/", DeviceResource.class);
    router.attach("/debug", DeviceEntityResource.class);
    return router;
}
 
Example #30
Source File: PerfWebRoutable.java    From floodlight_with_topoguard with Apache License 2.0 5 votes vote down vote up
@Override
public Restlet getRestlet(Context context) {
    Router router = new Router(context);
    router.attach("/data/json", PerfMonDataResource.class);
    router.attach("/{perfmonstate}/json", PerfMonToggleResource.class); // enable, disable, or reset
    return router;
}