Java Code Examples for org.restlet.Context

The following examples show how to use org.restlet.Context. These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: vicinity-gateway-api   Source File: Api.java    License: 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 Project: uReplicator   Source File: WorkerStarter.java    License: 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 3
Source Project: DeviceConnect-Android   Source File: LocalOAuth2Main.java    License: 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 4
Source Project: DeviceConnect-Android   Source File: Reference.java    License: 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 5
Source Project: DeviceConnect-Android   Source File: Tag.java    License: 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 6
Source Project: DeviceConnect-Android   Source File: FormUtils.java    License: 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 7
Source Project: DeviceConnect-Android   Source File: InputRepresentation.java    License: 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 8
Source Project: DeviceConnect-Android   Source File: StringRepresentation.java    License: 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 9
Source Project: DeviceConnect-Android   Source File: Representation.java    License: 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 10
Source Project: DeviceConnect-Android   Source File: ReadingListener.java    License: 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 11
Source Project: DeviceConnect-Android   Source File: SelectionRegistration.java    License: 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 12
@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 13
Source Project: floodlight_with_topoguard   Source File: CoreWebRoutable.java    License: 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 14
Source Project: microservices-comparison   Source File: RemoteCarService.java    License: 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 15
@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 16
@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
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 18
Source Project: ontopia   Source File: RoleRouter.java    License: 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 19
Source Project: ontopia   Source File: OccurrenceRouter.java    License: 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 Project: ontopia   Source File: NamesRouter.java    License: 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
@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 Project: ipst   Source File: ITeslaRules.java    License: Mozilla Public License 2.0 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 23
Source Project: DeviceConnect-Android   Source File: LocalOAuth2Main.java    License: MIT License 5 votes vote down vote up
/**
 * コンストラクタ.
 */
public LocalOAuth2Main(final android.content.Context context, final String dbName) {
    // ログレベル設定
    Logger logger = sLogger;
    if (BuildConfig.DEBUG) {
        AndroidHandler handler = new AndroidHandler(logger.getName());
        handler.setFormatter(new SimpleFormatter());
        handler.setLevel(Level.ALL);
        logger.addHandler(handler);
        logger.setLevel(Level.ALL);
    } else {
        logger.setLevel(Level.OFF);
    }

    mContext = context;

    // DB初期化処理
    mDbHelper = new LocalOAuthOpenHelper(context, dbName);
    mDb = mDbHelper.getWritableDatabase();

    // 初期化処理
    mUserManager = new SampleUserManager();
    mClientManager = new SQLiteClientManager(mDb);
    mTokenManager = new SQLiteTokenManager(mDb);

    // ユーザー追加
    addUserData(SampleUser.LOCALOAUTH_USER, SampleUser.LOCALOAUTH_PASS);

    register(context);
}
 
Example 24
Source Project: DeviceConnect-Android   Source File: LocalOAuth2Main.java    License: MIT License 5 votes vote down vote up
/**
 * 認可の結果を受け取るためのLocalBroadcastReceiverを登録します.
 *
 * @param context 登録するコンテキスト
 */
private void register(android.content.Context context) {
    IntentFilter filter = new IntentFilter();
    filter.addAction(ACTION_TOKEN_APPROVAL);
    filter.addAction(ACTION_OAUTH_ACCEPT);
    filter.addAction(ACTION_OAUTH_DECLINE);
    LocalBroadcastManager.getInstance(context).registerReceiver(mBroadcastReceiver, filter);
    mContext.registerReceiver(mBroadcastReceiver, filter);
}
 
Example 25
Source Project: ontopia   Source File: ContextUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static Parameter getParameter(Context context, String name) {
	Series<Parameter> parameters = getParameters(context);
	if (parameters == null) {
		return null;
	}
	return parameters.getFirst(name);
}
 
Example 26
Source Project: DeviceConnect-Android   Source File: Reference.java    License: MIT License 5 votes vote down vote up
/**
     * Encodes a given string using the standard URI encoding mechanism and the
     * UTF-8 character set. Useful to prevent the usage of '+' to encode spaces
     * (%20 instead). The '*' characters are encoded as %2A and %7E are replaced
     * by '~'.
     * 
     * @param toEncode
     *            The string to encode.
     * @param queryString
     *            True if the string to encode is part of a query string instead
     *            of a HTML form post.
     * @param characterSet
     *            The supported character encoding.
     * @return The encoded string.
     */
    public static String encode(String toEncode, boolean queryString,
            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) ? toEncode : java.net.URLEncoder
                    .encode(toEncode, characterSet.getName());
        } catch (UnsupportedEncodingException uee) {
            Context.getCurrentLogger()
                    .log(Level.WARNING,
                            "Unable to encode the string with the UTF-8 character set.",
                            uee);
        }


        if (queryString) {
            result = result.replace("+", "%20").replace("*", "%2A")
                    .replace("%7E", "~");
        }

        return result;
    }
 
Example 27
@Override
public Restlet getRestlet(Context context) {
	Router router = new Router(context);
	router.attach("/admin/reloadConfig/json",FlowSpaceFirewallResource.class);
	router.attach("/admin/set_state/{slice}/{dpid}/{status}/json", FlowSpaceFirewallSetState.class);
	router.attach("/status/{slice}/{dpid}/json",SlicerStatusResource.class);
	router.attach("/flows/{slice}/{dpid}/json", SlicerFlowResource.class);
	router.attach("/admin/switches/json",FlowSpaceFirewallSwitches.class);
	router.attach("/admin/slices/json", FlowSpaceFirewallSlices.class);
	return router;
}
 
Example 28
Source Project: DeviceConnect-Android   Source File: Reference.java    License: MIT License 5 votes vote down vote up
/**
 * Returns the optional port number for server based hierarchical
 * identifiers.
 * 
 * @return The optional port number for server based hierarchical
 *         identifiers or -1 if the port number does not exist.
 */
public int getHostPort() {
    int result = -1;
    final String authority = getAuthority();

    if (authority != null) {
        // We must prevent the case where the userinfo part contains ':'
        // and the case of IPV6 addresses
        int indexUI = authority.indexOf('@'); // user info
        int indexIPV6 = authority.indexOf(']'); // IPV6
        int index = authority.indexOf(':', (indexIPV6 == -1) ? indexUI
                : indexIPV6);

        if (index != -1) {
            try {
                result = Integer.parseInt(authority.substring(index + 1));
            } catch (NumberFormatException nfe) {
                Context.getCurrentLogger().log(
                        Level.WARNING,
                        "Can't parse hostPort : [hostRef,requestUri]=["
                                + getBaseRef() + "," + this.internalRef
                                + "]");
            }
        }
    }

    return result;
}
 
Example 29
Source Project: DeviceConnect-Android   Source File: Series.java    License: MIT License 5 votes vote down vote up
/**
 * Creates a new entry.
 * 
 * @param name
 *            The name of the entry.
 * @param value
 *            The value of the entry.
 * @return A new entry.
 */
public T createEntry(String name, String value) {
    try {
        return this.entryClass.getConstructor(String.class, String.class)
                .newInstance(name, value);
    } catch (Exception e) {
        Context.getCurrentLogger().log(Level.WARNING,
                "Unable to create a series entry", e);
        return null;
    }
}
 
Example 30
Source Project: DeviceConnect-Android   Source File: SelectionRegistration.java    License: MIT License 5 votes vote down vote up
/**
 * Effectively registers the {@link #getSelectableChannel()} with the given
 * {@link Selector} for the {@link #getInterestOperations()} operations.
 * 
 * @param selector
 *            The NIO selector to register to.
 */
public SelectionKey register(Selector selector) {
    try {
        this.selectionKey = getSelectableChannel().register(selector,
                getInterestOperations(), this);
    } catch (ClosedChannelException cce) {
        Context.getCurrentLogger().log(Level.FINE,
                "Unable to register again", cce);
    }

    return this.selectionKey;
}