下面列出了org.osgi.framework.ServiceListener#org.restlet.data.Protocol 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public void start(BundleContext context) throws Exception {
context.addServiceListener(new ServiceListener() {
@Override
public void serviceChanged(ServiceEvent event) {
if (event.getType() == ServiceEvent.REGISTERED){
component = new Component();
Server server = new Server(Protocol.HTTP, 8182);
component.getServers().add(server);
component.setLogService(new LogService(false));
final Application app = new ApiApplication();
component.getDefaultHost().attachDefault(app);
try {
component.start();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}, "(objectclass=" + ApiStartServiceToken.class.getName() +")");
}
@Before
public void setUp() throws UnknownHostException {
mongo = new Mongo();
helper = new ApiHelper();
PongoFactory.getInstance().getContributors().add(new OsgiPongoFactoryContributor());
platform = Platform.getInstance();
platform.setMongo(mongo);
platform.initialize();
WORKER_ID = Configuration.getInstance().getSlaveIdentifier();
// Register Worker
platform.getAnalysisRepositoryManager().getWorkerService().registerWorker(WORKER_ID);
Component component = new Component();
Server server = new Server(Protocol.HTTP, 8182);
component.getServers().add(server);
final Application app = new ApiApplication();
component.getDefaultHost().attachDefault(app);
try {
component.start();
} catch (Exception e) {
e.printStackTrace();
}
}
@Before
public void setUp() throws UnknownHostException {
mongo = new Mongo();
helper = new ApiHelper();
PongoFactory.getInstance().getContributors().add(new OsgiPongoFactoryContributor());
platform = Platform.getInstance();
platform.setMongo(mongo);
platform.initialize();
WORKER_ID = Configuration.getInstance().getSlaveIdentifier();
// Register Worker
platform.getAnalysisRepositoryManager().getWorkerService().registerWorker(WORKER_ID);
Component component = new Component();
Server server = new Server(Protocol.HTTP, 8182);
component.getServers().add(server);
final Application app = new ApiApplication();
component.getDefaultHost().attachDefault(app);
try {
component.start();
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void testEclipse() {
Client client = new Client(Protocol.HTTP);
Request request = new Request(Method.POST, "http://localhost:8182/projects/import");
ObjectMapper mapper = new ObjectMapper();
ObjectNode n = mapper.createObjectNode();
n.put("url", "https://projects.eclipse.org/projects/modeling.epsilon");
request.setEntity(n.toString(), MediaType.APPLICATION_JSON);
Response response = client.handle(request);
validateResponse(response, 201);
System.out.println(response.getEntityAsText());
}
@Test
public void testGitHub() {
Client client = new Client(Protocol.HTTP);
Request request = new Request(Method.POST, "http://localhost:8182/projects/import");
ObjectMapper mapper = new ObjectMapper();
ObjectNode n = mapper.createObjectNode();
n.put("url", "https://github.com/jrwilliams/gif-hook");
request.setEntity(n.toString(), MediaType.APPLICATION_JSON);
Response response = client.handle(request);
validateResponse(response, 201);
System.out.println(response.getEntityAsText());
}
@BeforeTest
public void setup() throws Exception {
InstanceTopicPartitionHolder fakeInstance1 = new InstanceTopicPartitionHolder("0");
InstanceTopicPartitionHolder fakeInstance2 = new InstanceTopicPartitionHolder("2");
fakeInstance1.addTopicPartition(faketp1);
fakeInstance1.addTopicPartition(faketp2);
fakeInstance2.addTopicPartition(faketp3);
fakeInstance2.addTopicPartition(faketp4);
fakeItphList.add(fakeInstance1);
fakeItphList.add(fakeInstance2);
applicationContext.getAttributes().put(HelixMirrorMakerManager.class.toString(),
_helixMirrorMakerManager);
_controllerRestApp.setContext(applicationContext);
_component.getServers().add(Protocol.HTTP, Integer.parseInt(CONTROLLER_PORT));
_component.getClients().add(Protocol.FILE);
_component.getDefaultHost().attach(_controllerRestApp);
_component.start();
}
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();
}
@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);
}
public static void main( String[] args )
throws Exception
{
Energy4Java polygene = new Energy4Java( );
Server server = new Server( Protocol.HTTP, 8888 );
Application app = polygene.newApplication( new ForumAssembler(), new MetadataService() );
app.activate();
ContextRestlet restlet = app.findModule( "REST", "Restlet" ).newObject( ContextRestlet.class, new org.restlet.Context() );
ChallengeAuthenticator guard = new ChallengeAuthenticator(null, ChallengeScheme.HTTP_BASIC, "testRealm");
MapVerifier mapVerifier = new MapVerifier();
mapVerifier.getLocalSecrets().put("rickard", "secret".toCharArray());
guard.setVerifier(mapVerifier);
guard.setNext(restlet);
server.setNext( restlet );
server.start();
}
public SimplifiedCourseRequestsValidationProvider() {
List<Protocol> protocols = new ArrayList<Protocol>();
protocols.add(Protocol.HTTP);
protocols.add(Protocol.HTTPS);
iClient = new Client(protocols);
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();
}
}
public XEStudentEnrollment() {
List<Protocol> protocols = new ArrayList<Protocol>();
protocols.add(Protocol.HTTP);
protocols.add(Protocol.HTTPS);
iClient = new Client(protocols);
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();
}
}
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();
}
}
public DegreeWorksCourseRequests() {
List<Protocol> protocols = new ArrayList<Protocol>();
protocols.add(Protocol.HTTP);
protocols.add(Protocol.HTTPS);
iClient = new Client(protocols);
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();
}
}
public DegreeWorksPlanScraper(Set<String> filter) {
List<Protocol> protocols = new ArrayList<Protocol>();
protocols.add(Protocol.HTTP);
protocols.add(Protocol.HTTPS);
iClient = new Client(protocols);
iFilter = filter;
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();
}
}
@BeforeSuite
public void beforeSuite() throws Exception {
// TODO: use logging.properties file to config java.util.logging.Logger levels
java.util.logging.Logger topJavaLogger = java.util.logging.Logger.getLogger("");
topJavaLogger.setLevel(Level.WARNING);
// start zk
_zkServer = TestHelper.startZkServer(ZK_ADDR);
AssertJUnit.assertTrue(_zkServer != null);
ZKClientPool.reset();
_gZkClient =
new ZkClient(ZK_ADDR, ZkClient.DEFAULT_SESSION_TIMEOUT, ZkClient.DEFAULT_CONNECTION_TIMEOUT,
new ZNRecordSerializer());
_gSetupTool = new ClusterSetup(_gZkClient);
// start admin
_adminThread = new AdminThread(ZK_ADDR, ADMIN_PORT);
_adminThread.start();
// create a client
_gClient = new Client(Protocol.HTTP);
// wait for the web service to start
Thread.sleep(100);
}
public static void main(String[] args) {
try {
// Create a new Component.
Component component = new Component();
// Add a new HTTP server listening on port 8082.
component.getServers().add(Protocol.HTTP, 8080);
// Attach the sample application.
component.getDefaultHost().attach(new RestletApplication());
// Start the component.
component.start();
} catch (Exception e) {
// Something is wrong.
e.printStackTrace();
}
}
@Test
public void testGet() {
Client client = new Client(Protocol.HTTP);
Request request = new Request(Method.GET, "http://localhost:8182/projects/p/ant");
Response response = client.handle(request);
validateResponse(response, 200);
// TODO: check the JSON
}
@Test
public void testPostInsert() throws Exception {
Request request = new Request(Method.POST, "http://localhost:8182/projects/");
ObjectMapper mapper = new ObjectMapper();
ObjectNode p = mapper.createObjectNode();
p.put("name", "test");
p.put("shortName", "test-short");
p.put("description", "this is a description");
request.setEntity(p.toString(), MediaType.APPLICATION_JSON);
Client client = new Client(Protocol.HTTP);
Response response = client.handle(request);
System.out.println(response.getEntity().getText() + " " + response.isEntityAvailable());
validateResponse(response, 201);
// Now try again, it should fail
response = client.handle(request);
validateResponse(response, 409);
// Clean up
Mongo mongo = new Mongo();
DB db = mongo.getDB("scava");
DBCollection col = db.getCollection("projects");
BasicDBObject query = new BasicDBObject("name", "test");
col.remove(query);
mongo.close();
}
public void start() throws Exception {
_component.getServers().add(Protocol.HTTP, _config.getManagerPort());
_component.getClients().add(Protocol.FILE);
_component.getClients().add(Protocol.JAR);
Context applicationContext = _component.getContext().createChildContext();
LOGGER.info("Injecting conf and helix to the api context");
applicationContext.getAttributes().put(ManagerConf.class.toString(), _config);
applicationContext.getAttributes()
.put(ControllerHelixManager.class.toString(), _controllerHelixManager);
applicationContext.getAttributes()
.put(KafkaClusterValidationManager.class.toString(), _kafkaValidationManager);
Application managerRestApp = new ManagerRestApplication(null);
managerRestApp.setContext(applicationContext);
_component.getDefaultHost().attach(managerRestApp);
try {
LOGGER.info("Starting helix manager");
_controllerHelixManager.start();
LOGGER.info("Starting src and dst kafka cluster validation manager");
_kafkaValidationManager.start();
LOGGER.info("Starting API component");
_component.start();
} catch (final Exception e) {
LOGGER.error("Caught exception while starting uReplicator-Manager", e);
throw e;
}
}
@BeforeTest
public void setup() throws Exception {
applicationContext.getAttributes().put(HelixMirrorMakerManager.class.toString(),
_helixMirrorMakerManager);
_controllerRestApp.setContext(applicationContext);
_component.getServers().add(Protocol.HTTP, Integer.parseInt(CONTROLLER_PORT));
_component.getClients().add(Protocol.FILE);
_component.getDefaultHost().attach(_controllerRestApp);
_component.start();
}
public void start(final BundleContext context) throws Exception {
component = new Component();
component.getServers().add(Protocol.HTTP, 8888);
component.getClients().add(Protocol.CLAP);
component.getDefaultHost().attach("", new RestService(context));
component.start();
}
@Override
public Restlet getRestlet(Context context) {
Router router = new Router(context);
router.attach("", new Directory(context, "clap://classloader/web/"));
context.setClientDispatcher(new Client(context, Protocol.CLAP));
return router;
}
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);
}
}
@Inject
public RestComponent(@Hello Application helloApp, @Car Application carApp, Verifier authTokenVerifier) {
getClients().add(Protocol.HTTPS);
Server secureServer = getServers().add(Protocol.HTTPS, 8043);
Series<Parameter> parameters = secureServer.getContext().getParameters();
parameters.add("sslContextFactory", "org.restlet.engine.ssl.DefaultSslContextFactory");
parameters.add("keyStorePath", System.getProperty("javax.net.ssl.keyStorePath"));
getDefaultHost().attach("/api/hello", secure(helloApp, authTokenVerifier, "ame"));
getDefaultHost().attach("/api/cars", secure(carApp, authTokenVerifier, "ame"));
replaceConverter(JacksonConverter.class, new JacksonCustomConverter());
}
@Override
public void startServer()
throws Exception
{
configuration.refresh();
component = new Component();
component.getServers().add( Protocol.HTTP, configuration.get().port().get() );
RestApplication application = module.newObject( RestApplication.class, component.getContext() );
component.getDefaultHost().attach( application );
component.start();
}
@Override
public void afterPropertiesSet() throws Exception {
List<Protocol> protocols = new ArrayList<Protocol>();
protocols.add(Protocol.HTTP);
protocols.add(Protocol.HTTPS);
iClient = new Client(protocols);
}
public static void main(String[] args) throws Exception {
Component component = new Component();
component.getServers().add(Protocol.HTTP, 8082);
component.getDefaultHost().attach(new FoxbpmRestApplication());
component.start();
System.out.println("The restlet server started ...");
}
@Override
public void start() throws UnknownHostException {
if (isEnabled) {
final boolean isRunning = this.isRunning.getAndSet(true);
if (!isRunning) {
if (isEnabled && port <= 0) {
this.isEnabled = false;
TestServerConsole.log("Could not start RestService. Parameter missing: 'server.service.rest.port'", 1, TestServerServiceEnum.TEST_SERVER);
}
Component component = new Component();
Server s = component.getServers().add(isSsl ? Protocol.HTTPS : Protocol.HTTP, InetAddress.getLocalHost().getHostAddress(), port);
if (isSsl) {
Series<Parameter> parameters = s.getContext().getParameters();
parameters.add("keystorePath", QOS_KEY_FILE_ABSOLUTE);
parameters.add("keystorePassword", TestServer.QOS_KEY_PASSWORD);
parameters.add("keyPassword", TestServer.QOS_KEY_PASSWORD);
parameters.add("keystoreType", TestServer.QOS_KEY_TYPE);
}
component.getDefaultHost().attach("", new RestletApplication());
try {
component.start();
TestServerConsole.log("[" + getName() + "] started: " + toString(), 1, TestServerServiceEnum.TEST_SERVER);
} catch (Exception e) {
TestServerConsole.error(getName(), e, 0, TestServerServiceEnum.TEST_SERVER);
}
}
}
}
public StuffComponent() {
getClients().add(Protocol.FILE);
getDefaultHost().attach("/", new StuffApplication());
}
public void start(BundleContext context) throws Exception {
System.err.println("Starting Admin bundle");
context.addServiceListener(new ServiceListener() {
@Override
public void serviceChanged(ServiceEvent event) {
System.err.println(event);
if (event.getType() == ServiceEvent.REGISTERED){
Application application = new AdminApplication();
component = new Component();
component.getServers().add(Protocol.HTTP, 8183);
component.getClients().add(Protocol.FILE);
boolean useAuth = Boolean.valueOf(Configuration.getInstance().getProperty("adminapi.use_authentication", "false"));
if (useAuth) {
String username = Configuration.getInstance().getProperty("adminapi.username", null);
String password = Configuration.getInstance().getProperty("adminapi.password", null);
ChallengeAuthenticator guard = new ChallengeAuthenticator(null, ChallengeScheme.HTTP_BASIC, "myRealm");
MapVerifier verifier = new MapVerifier();
verifier.getLocalSecrets().put(username, password.toCharArray());
guard.setVerifier(verifier);
guard.setNext(application);
component.getDefaultHost().attachDefault(guard);
} else {
component.getDefaultHost().attachDefault(application);
}
try {
component.start();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}, "(objectclass=" + ApiStartServiceToken.class.getName() +")");
}