Java Examples for org.restlet.Component
The following java examples will help you to understand the usage of org.restlet.Component. These source code samples are taken from different open source projects.
Example 1
| Project: hive-mrc-master File: Main.java View source code |
public static void main(String[] args) {
try {
// Create a new Component.
Component component = new Component();
// Add a new HTTP server listening on port 8182.
component.getServers().add(Protocol.HTTP, 8182);
// Attach the sample application.
component.getDefaultHost().attach(new SKOSResourceApplication());
// Start the component.
component.start();
} catch (Exception e) {
e.printStackTrace();
}
}Example 2
| Project: sandboxes-master File: RestServer.java View source code |
public static void main(String[] args) throws Exception {
final File nodesDirectory = new File(FilesystemUtils.getRootOfTmpDirectory(), "nodes");
nodesDirectory.mkdirs();
Component component = new Component();
component.getServers().add(Protocol.HTTP, 8182);
component.getClients().add(Protocol.FILE);
component.getDefaultHost().attach("/step", new FirstStepsApplication());
component.getDefaultHost().attach("/nodes", new ServerStaticContentFromDirectory());
component.start();
}Example 3
| Project: skysail-server-ext-master File: SkysailServerExtJenkinsOsgiIT.java View source code |
@Test
public void a() {
ComponentProvider dummyComponentProvider = new ComponentProvider() {
@Override
public Component getComponent() {
return new Component();
}
@Override
public Verifier getVerifier() {
return Mockito.mock(Verifier.class);
}
};
EntityManagerFactory dummyEmf = new EntityManagerFactory() {
@Override
public EntityManager createEntityManager() {
// TODO Auto-generated method stub
return null;
}
@Override
public EntityManager createEntityManager(Map map) {
// TODO Auto-generated method stub
return null;
}
@Override
public CriteriaBuilder getCriteriaBuilder() {
// TODO Auto-generated method stub
return null;
}
@Override
public Metamodel getMetamodel() {
// TODO Auto-generated method stub
return null;
}
@Override
public boolean isOpen() {
// TODO Auto-generated method stub
return false;
}
@Override
public void close() {
// TODO Auto-generated method stub
}
@Override
public Map<String, Object> getProperties() {
// TODO Auto-generated method stub
return null;
}
@Override
public Cache getCache() {
// TODO Auto-generated method stub
return null;
}
@Override
public PersistenceUnitUtil getPersistenceUnitUtil() {
// TODO Auto-generated method stub
return null;
}
};
// Mockito.mock(EntityManagerFactory.class);
// provide the required services, so that the configuration constraints are fulfilled.
context.registerService(ComponentProvider.class.getName(), dummyComponentProvider, null);
Dictionary props = new Hashtable();
props.put("osgi.unit.name", "JenkinsPU");
context.registerService(EntityManagerFactory.class.getName(), dummyEmf, props);
// check the service which should have been created by the configuration
ServiceReference serviceReference = context.getServiceReference(ApplicationProvider.class.getName());
// assertThat(serviceReference, is(notNullValue()));
ApplicationProvider service = (ApplicationProvider) context.getService(serviceReference);
Application applicationFromService = service.getApplication();
assertTrue(applicationFromService.getName().equals("jenkins"));
}Example 4
| Project: buddycloud-media-server-master File: Main.java View source code |
private static void startRestletComponent(Properties configuration) throws Exception {
Component component = new Component();
if (Boolean.valueOf(configuration.getProperty(MediaServerConfiguration.HTTPS_ENABLED))) {
Server server = component.getServers().add(Protocol.HTTPS, Integer.valueOf(configuration.getProperty(MediaServerConfiguration.HTTPS_PORT)));
server.getContext().getParameters().add("sslContextFactory", "org.restlet.ext.ssl.PkixSslContextFactory");
server.getContext().getParameters().add("keystorePath", configuration.getProperty(MediaServerConfiguration.HTTPS_KEYSTORE_PATH));
server.getContext().getParameters().add("keystorePassword", configuration.getProperty(MediaServerConfiguration.HTTPS_KEYSTORE_PASSWORD));
server.getContext().getParameters().add("keyPassword", configuration.getProperty(MediaServerConfiguration.HTTPS_KEY_PASSWORD));
server.getContext().getParameters().add("keystoreType", configuration.getProperty(MediaServerConfiguration.HTTPS_KEYSTORE_TYPE));
} else {
component.getServers().add(Protocol.HTTP, Integer.valueOf(configuration.getProperty(MediaServerConfiguration.HTTP_PORT)));
}
Context context = component.getContext().createChildContext();
component.getDefaultHost().attach(new MediaServerApplication(context));
component.start();
LOGGER.info("Buddycloud Media Server HTTP server started!");
}Example 5
| Project: CarpoolBackend-master File: ServerMain.java View source code |
/**
* Start the Thread, accept incoming connections
*
* Use this entry point to start with embedded HTTP Server
*
* @throws Exception
*/
public void start() throws Exception {
component = new Component();
// Add a new HTTP server listening on port
Server server = component.getServers().add(Protocol.HTTP, 8015);
server.getContext().getParameters().add("maxThreads", "256");
// Attach the sample application
RoutingService routingService = new RoutingService();
component.getDefaultHost().attach(routingService);
// Start the component.
//log.info("ready to start");
DebugLog.d("ready to start");
component.start();
}Example 6
| Project: erica-master File: ComponentProxy.java View source code |
@Override
public Restlet createRestlet() {
Component component = new Component();
for (ServerProxy serverProxy : servers) {
component.getServers().add((Server) serverProxy.createRestlet());
}
for (RouteProxy route : routes) {
if (RestletRegistry.getInstance().isRestletId(route.getTargetId()))
component.getDefaultHost().attach(route.getUrlTemplate(), RestletRegistry.getInstance().getRestlet(route.getTargetId()));
else
component.getDefaultHost().attach(route.getUrlTemplate(), RestletRegistry.getInstance().getResource(route.getTargetId()));
}
return component;
}Example 7
| Project: jflicks-master File: BaseApplication.java View source code |
private void attach() {
if (!isAttached()) {
// We are not attached so we will try as long as we have valid
// ServerComponent instance.
ServerComponent sc = getServerComponent();
if (sc != null) {
Component c = sc.getComponent();
if (c != null) {
try {
setAttached(true);
String att = "/jflicks/" + getAlias();
c.getDefaultHost().attach(att, (Application) this);
c.start();
} catch (Exception ex) {
LogUtil.log(LogUtil.DEBUG, ex.getMessage());
}
}
}
}
}Example 8
| Project: milton-master File: RestletFileserver.java View source code |
public static void main(String[] args) throws Exception {
Component component = new Component();
component.getServers().add(Protocol.HTTP, 8080);
// Restlet logs requests by default
// component.getLogService().setEnabled(false);
component.getDefaultHost().attach(new Application() {
@Override
public Restlet createInboundRoot() {
FileSystemResourceFactory factory = new FileSystemResourceFactory(new File(System.getProperty("user.home")), new NullSecurityManager());
factory.setContentService(new SimpleFileContentService());
factory.setLockManager(new FsMemoryLockManager());
return new WebDavRestlet(factory);
}
});
component.start();
System.out.println("Restlet demo fileserver started, open http://localhost:8080 in your browser or WebDAV client...");
}Example 9
| Project: milton2-master File: RestletFileserver.java View source code |
public static void main(String[] args) throws Exception {
Component component = new Component();
component.getServers().add(Protocol.HTTP, 8080);
// Restlet logs requests by default
// component.getLogService().setEnabled(false);
component.getDefaultHost().attach(new Application() {
@Override
public Restlet createInboundRoot() {
FileSystemResourceFactory factory = new FileSystemResourceFactory(new File(System.getProperty("user.home")), new NullSecurityManager());
factory.setContentService(new SimpleFileContentService());
factory.setLockManager(new FsMemoryLockManager());
return new WebDavRestlet(factory);
}
});
component.start();
System.out.println("Restlet demo fileserver started, open http://localhost:8080 in your browser or WebDAV client...");
}Example 10
| Project: OpenSextantToolbox-master File: OpenSextantAdminResource.java View source code |
@Override
public void run() {
try {
Thread.sleep(t);
} catch (InterruptedException ex) {
} finally {
try {
this.app.stop();
Component comp = (Component) app.getContext().getAttributes().get("component");
comp.stop();
} catch (Exception e) {
LOGGER.error("Couldnt handle provided form", e);
}
}
}Example 11
| Project: qi4j-libraries-master File: RestServerMixin.java View source code |
public void activate() throws Exception {
component = new Component();
component.getServers().add(Protocol.HTTP, 8182);
ObjectBuilder<RestApplication> builder = obf.newObjectBuilder(RestApplication.class);
builder.use(component.getContext());
RestApplication application = builder.newInstance();
component.getDefaultHost().attach(application);
component.start();
}Example 12
| Project: restlet-framework-java-master File: DirectoryTestCase.java View source code |
public void testDirectory() throws Exception {
// Create a temporary directory for the tests
this.testDir = new File(System.getProperty("java.io.tmpdir"), "DirectoryTestCase/tests1" + new Date().getTime());
// Create a new Restlet component
final Component clientComponent = new Component();
clientComponent.getClients().add(Protocol.FILE);
// Create an application
final MyApplication application = new MyApplication(this.testDir);
// Attach the application to the component and start it
clientComponent.getDefaultHost().attach("", application);
// Now, let's start the component!
clientComponent.start();
doTests(application);
// Now, let's stop the component!
clientComponent.stop();
}Example 13
| Project: sesametools-master File: SparqlAskTest.java View source code |
@BeforeClass
public static void setUp() throws Exception {
// add test data
final Repository repo = new SailRepository(sail);
try (RepositoryConnection con = repo.getConnection()) {
con.add(SparqlAskTest.class.getResourceAsStream(DATA_FILE), "", RDFFormat.TRIG);
}
// turn off verbose logging in Restlet engine
Engine.setLogLevel(Level.WARNING);
// configure SPARQL endpoint
final Component component = new Component();
component.getServers().add(Protocol.HTTP, ENDPOINT_URL.getPort());
component.getDefaultHost().attach(ENDPOINT_URL.getPath(), new SparqlResource());
server.setInboundRoot(component);
server.start();
}Example 14
| Project: SlipStreamServer-master File: Main.java View source code |
public static void main(String[] args) throws ValidationException {
Component component = new Component();
component.getServers().add(Protocol.HTTP, 8182);
component.getClients().add(Protocol.FILE);
component.getClients().add(Protocol.HTTP);
Application rootApplication = new RootApplication();
component.getDefaultHost().attach("", rootApplication);
try {
component.start();
} catch (Exception e) {
log.log(Level.SEVERE, "Start error", e);
log.severe("Starting SlipStream FAILED!");
System.exit(1);
}
log.finest("SlipStream started!");
log.finer("SlipStream started!");
log.fine("SlipStream started!");
log.info("SlipStream started!");
}Example 15
| Project: streamflow-core-master File: MainWeb.java View source code |
public void start() throws Throwable {
/*
// Remove default handlers - we do our own logging!
for (Handler handler : Logger.getLogger( "" ).getHandlers())
{
Logger.getLogger( "" ).removeHandler( handler );
}
// Install SL4J Bridge. This will eventually delegate to log4j for logging
SLF4JBridgeHandler.install();
URL logConfig = getClass().getResource( "/log4j.xml" );
DOMConfigurator.configure( logConfig );
*/
logger = LoggerFactory.getLogger(getClass());
logger.info("Starting Streamflow");
Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
try {
component = new Component();
component.getClients().add(Protocol.CLAP);
component.getClients().add(Protocol.FILE);
component.getClients().add(Protocol.HTTP);
application = new StreamflowRestApplication(component.getContext().createChildContext());
component.getDefaultHost().attach("/streamflow", application);
/*
VirtualHost virtualHost = new VirtualHost(component.getContext());
virtualHost.setHostDomain("jayway.local");
virtualHost.getContext().getAttributes().put("streamflow.host", virtualHost.getHostDomain());
Application virtualApplication = new StreamflowRestApplication(virtualHost.getContext());
virtualHost.attach("/streamflow", virtualApplication);
component.getHosts().add(virtualHost);
*/
component.start();
logger.info("Started Streamflow");
} catch (Throwable e) {
logger.info("Could not start Streamflow", e);
if (component != null)
try {
component.stop();
} catch (Exception e1) {
}
throw e;
} finally {
Thread.currentThread().setContextClassLoader(null);
}
}Example 16
| Project: sync-android-p2p-example-master File: MainActivity.java View source code |
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// create datastore
File path = getApplicationContext().getDir("datastores", MODE_PRIVATE);
DatastoreManager manager = new DatastoreManager(path.getAbsolutePath());
Datastore ds = manager.openDatastore("mydb");
ds.close();
Component component = new Component();
component.getServers().add(Protocol.HTTP, 8182);
component.getDefaultHost().attachDefault(HttpListener.class);
try {
component.start();
} catch (Exception e) {
throw new RuntimeException(e);
}
}Example 17
| Project: helix-master File: HelixAdminWebApp.java View source code |
public synchronized void start() throws Exception {
LOG.info("helixAdminWebApp starting");
if (_component == null) {
_zkClient = new ZkClient(_zkServerAddress, ZkClient.DEFAULT_SESSION_TIMEOUT, ZkClient.DEFAULT_CONNECTION_TIMEOUT, new ZNRecordSerializer());
_component = new Component();
_component.getServers().add(Protocol.HTTP, _helixAdminPort);
Context applicationContext = _component.getContext().createChildContext();
applicationContext.getAttributes().put(RestAdminApplication.ZKSERVERADDRESS, _zkServerAddress);
applicationContext.getAttributes().put(RestAdminApplication.PORT, "" + _helixAdminPort);
applicationContext.getAttributes().put(RestAdminApplication.ZKCLIENT, _zkClient);
_adminApp = new RestAdminApplication(applicationContext);
// Attach the application to the component and start it
_component.getDefaultHost().attach(_adminApp);
_component.start();
}
LOG.info("helixAdminWebApp started on port " + _helixAdminPort);
}Example 18
| Project: juxta-service-master File: JuxtaWS.java View source code |
public static void main(String[] args) throws Exception {
// be sure to use the saxon parser
System.setProperty("javax.xml.transform.TransformerFactory", "net.sf.saxon.TransformerFactoryImpl");
// initialize application context
initApplicationContext();
// kill the console loggers and rely on logging from
// these classes only
Logger rootLogger = LogManager.getLogManager().getLogger("");
Handler[] handlers = rootLogger.getHandlers();
rootLogger.removeHandler(handlers[0]);
// Start the Restlet component
Component component = (Component) context.getBean("top");
component.start();
String authUser = (String) context.getBean("authenticatorUser");
String authPass = (String) context.getBean("authenticatorPass");
if ((Boolean) context.getBean("useAuthenticator") == true && (authPass.length() == 0 || authUser.length() == 0)) {
String msg = "Juxta WS is running in AUTHENTICATED mode, but credientials are not set";
LoggerFactory.getLogger(Constants.WS_LOGGER_NAME).error(msg);
System.exit(0);
}
// init all common filters and public workspace
((QNameFilters) context.getBean(QNameFilters.class)).initialize();
if ((Boolean) context.getBean("captureMetrics")) {
((MetricsHelper) context.getBean(MetricsHelper.class)).init();
}
LoggerFactory.getLogger(Constants.WS_LOGGER_NAME).info("Juxta Web service started");
if ((Boolean) context.getBean("useAuthenticator") == false) {
String msg = "*** Juxta WS is running in NON-AUTHENTICATED mode, and is viewable/editabe by anyone ***";
LoggerFactory.getLogger(Constants.WS_LOGGER_NAME).info(msg);
System.out.println(msg);
}
if ((Boolean) context.getBean("captureMetrics") == false) {
String msg = "*** Juxta WS not capturing usage metrics ***";
LoggerFactory.getLogger(Constants.WS_LOGGER_NAME).info(msg);
System.out.println(msg);
}
}Example 19
| Project: bonita-web-master File: RestletTest.java View source code |
private String start() throws Exception {
component = new Component();
final Server server = component.getServers().add(Protocol.HTTP, 0);
// server.getContext().getParameters().add("tracing", "true");
final Application application = configureApplication();
component.getDefaultHost().attach(application);
component.start();
return "http://localhost:" + server.getEphemeralPort();
}Example 20
| Project: BridgeDb-master File: Server.java View source code |
public void run(int port, File configFile, boolean transitive) {
component = new Component();
component.getServers().add(Protocol.HTTP, port);
component.getDefaultHost().attach(new IDMapperService(configFile, transitive));
try {
System.out.println("Starting server on port " + port);
component.start();
} catch (Exception e) {
e.printStackTrace();
}
}Example 21
| Project: GeoGig-master File: Main.java View source code |
static void startServer(String repo) throws Exception {
GeoGIG geogig = loadGeoGIG(repo);
org.restlet.Context context = new org.restlet.Context();
Application application = new Main(geogig);
application.setContext(context);
Component comp = new Component();
comp.getDefaultHost().attach(application);
comp.getServers().add(Protocol.HTTP, 8182);
comp.start();
}Example 22
| Project: gig-master File: Main.java View source code |
static void startServer(String repo) throws Exception {
GeoGIG geogig = loadGeoGIG(repo);
org.restlet.Context context = new org.restlet.Context();
Application application = new Main(geogig);
application.setContext(context);
Component comp = new Component();
comp.getDefaultHost().attach(application);
comp.getServers().add(Protocol.HTTP, 8182);
comp.start();
}Example 23
| Project: larkc-platform-2.5-rev1797-with-sim-master File: ManagementInterfaceMain.java View source code |
/**
* Main method to start the management interface server.
*
* @param args
* unused
* @throws Exception
* on server initialization error
*/
public static void main(String[] args) throws Exception {
// Create a new Component.
component = new Component();
// Create a new server
server = new Server(Protocol.HTTP, SERVER_PORT);
// Add the new HTTP server listening on port 8182.
component.getServers().add(server);
server.getContext().getParameters().add("maxTotalConnections", "512");
server.getContext().getParameters().add("maxThreads", "512");
// The following application will handle the representation of HTML
// files
component.getClients().add(Protocol.FILE);
// The application will also handle files which are possibly packed
// inside a JAR file
component.getClients().add(Protocol.JAR);
Application application = new Application() {
@Override
public Restlet createInboundRoot() {
try {
// URL systemResource = ClassLoader
// .getSystemResource(Resources.MGMT_HTML_ROOT);
URI localUri;
java.io.File tmpFile = new java.io.File(Resources.MGMT_HTML_ROOT);
if (tmpFile.exists())
localUri = tmpFile.toURI();
else {
URL systemResource = eu.larkc.core.Larkc.class.getClassLoader().getResource(Resources.MGMT_HTML_ROOT);
localUri = systemResource.toURI();
}
logger.debug("8182: {}", localUri);
LocalReference lr = new LocalReference(localUri.toString());
return new Directory(getContext(), lr);
} catch (IllegalArgumentException iae) {
logger.error("Cannot read management interface properties");
iae.printStackTrace();
} catch (URISyntaxException e) {
e.printStackTrace();
}
return null;
}
};
// Attach the applications to the component and start it
component.getDefaultHost().attach(application);
component.getDefaultHost().attach("/workflow", new WorkflowManagementInterface());
component.getDefaultHost().attach("/registry", RegistryManagementInterface.class);
component.getDefaultHost().attach("/hosts", HostManagementInterface.class);
component.getDefaultHost().attach("/workflows", WorkflowsManagementInterface.class);
// to be backward compatible
component.getDefaultHost().attach("/rdf/workflows", new WorkflowManagementInterface());
component.getDefaultHost().attach("/n3/workflows", new WorkflowManagementInterface());
component.start();
logger.info("Management server started on " + SERVER_PORT);
initialized = true;
}Example 24
| Project: rest-assured-master File: StressITest.java View source code |
@Before
public void setUp() throws Exception {
url = "http://localhost:8081/restlet/test";
component = new Component();
component.getLogService().setEnabled(true);
component.getServers().add(Protocol.HTTP, 8081);
component.getDefaultHost().attach("/restlet", new StressApp());
component.start();
RestAssured.config = RestAssuredConfig.config().connectionConfig(new ConnectionConfig().closeIdleConnectionsAfterEachResponse());
}Example 25
| Project: archived-net-virt-platform-master File: RestApiServer.java View source code |
public void run(ModuleContext fmlContext, 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 IPlatformService> 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();
component.getServers().add(Protocol.HTTP, restPort);
component.getDefaultHost().attach(this);
component.start();
} catch (Exception e) {
throw new RuntimeException(e);
}
}Example 26
| Project: claudia-master File: Main.java View source code |
public static void main(String[] args) throws Exception {
// Load the configuration file
Map<String, Object> configuration = new HashMap<String, Object>();
configuration.put("hibernate.connection.url", "jdbc:mysql://62.217.120.136:3306/monitoring?noDatetimeStringSync=true");
configuration.put("hibernate.connection.driver_class", "com.mysql.jdbc.Driver");
configuration.put("hibernate.connection.username", "claudia");
configuration.put("hibernate.connection.password", "ClaudiaPass");
configuration.put("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
configuration.put("hibernate.c3p0.min_size", "5");
configuration.put("hibernate.c3p0.max_size", "50");
configuration.put("hibernate.c3p0.timeout", "5000");
configuration.put("hibernate.c3p0.max_statements", "100");
createEntityManagerFactory("ClaudiaPU", configuration);
Properties prop = new Properties();
prop.load(new FileInputStream(PATH_TO_PROPERTIES_FILE));
try {
serverPort = Integer.parseInt(prop.getProperty(KEY_PORT));
} catch (NumberFormatException nfe) {
log.error("Error parsing the " + KEY_PORT + " property. A number was expected, but '" + prop.getProperty(KEY_PORT) + "' was found.");
System.exit(ERROR_CODE_INITIALIZATION);
}
serverHost = prop.getProperty(KEY_HOST);
// Load the appropiate drivers
URLClassLoader cl = loadDrivers();
// Create a new Component.
Component component = new Component();
// Add a new HTTP server listening on port.
component.getServers().add(Protocol.HTTP, serverPort);
TaskApplication taskApp = new TaskApplication();
component.getDefaultHost().attach(taskApp);
((Router) taskApp.getRoot()).attach(HEARTBEAT_URI, HeartbeatResource.class);
// Load the driver for TaskManager
if (prop.get(KEY_DRIVER_TASKMANAGER) != null && !prop.get(KEY_DRIVER_TASKMANAGER).equals("")) {
try {
Class classDriver = cl.loadClass(prop.getProperty(KEY_DRIVER_TASKMANAGER));
// Initialize the Task Manager
TaskManager taskManager = TaskApplication.setDriver(classDriver, prop);
taskManager.createManager(taskManager);
log.info("TaskManager active.");
} catch (IllegalArgumentException iae) {
log.error("Driver didn't extend the expected class.");
System.exit(ERROR_CODE_DRIVERS);
} catch (ClassNotFoundException cnfe) {
log.error("The TaksManager class was not loaded. Check the driver folder contents.");
System.out.println("The TaksManager class was not loaded. Check the driver folder contents.");
System.exit(ERROR_CODE_DRIVERS);
}
} else {
log.error("No TaskManager driver was specified. Task driver is mandatory.");
System.out.println("No TaskManager driver was specified. Task driver is mandatory.");
System.exit(ERROR_CODE_DRIVERS);
}
// Load the driver for each API
if (prop.get(KEY_DRIVER_MONITORING) != null && !prop.get(KEY_DRIVER_MONITORING).equals("")) {
try {
Class classDriver = cl.loadClass(prop.getProperty(KEY_DRIVER_MONITORING));
/*
* Properties prop = new Properties(); try { prop.load(new
* FileInputStream("./conf/tcloud.properties")); } catch
* (FileNotFoundException e1) { // TODO Auto-generated catch block
* e1.printStackTrace(); } catch (IOException e1) { // TODO
* Auto-generated catch block e1.printStackTrace(); }
*/
/* for (String s : names) {
try{
providers.add((PersistenceProvider)loader.loadClass(s).newInstance());
} catch (ClassNotFoundException exc){
} catch (InstantiationException exc){
} catch (IllegalAccessException exc){
}*/
MonitoringApplication.setDriver(classDriver, prop);
MonitoringApplication app = new MonitoringApplication();
app.modifyRoot((Router) taskApp.getRoot());
log.info("Monitoring application active.");
} catch (IllegalArgumentException iae) {
log.error("Driver didn't extend the expected class.");
} catch (ClassNotFoundException cnfe) {
log.error("The Monitoring class was not loaded. Check the driver folder contents.");
System.out.println("The Monitoring class was not loaded. Check the driver folder contents.");
System.exit(ERROR_CODE_DRIVERS);
}
}
if (prop.get(KEY_DRIVER_DEPLOYMENT) != null && !prop.get(KEY_DRIVER_DEPLOYMENT).equals("")) {
try {
Class classDriver = cl.loadClass(prop.getProperty(KEY_DRIVER_DEPLOYMENT));
DeploymentApplication.setDriver(classDriver, prop);
DeploymentApplication app = new DeploymentApplication();
app.modifyRoot((Router) taskApp.getRoot());
log.info("Deployment application active.");
} catch (IllegalArgumentException iae) {
log.error("Driver didn't extend the expected class.");
} catch (ClassNotFoundException cnfe) {
log.error("The Deployment class was not loaded. Check the driver folder contents.");
System.out.println("The Deployment class was not loaded. Check the driver folder contents.");
System.exit(ERROR_CODE_DRIVERS);
}
}
if (prop.get(KEY_DRIVER_PROVISIONING) != null && !prop.get(KEY_DRIVER_PROVISIONING).equals("")) {
try {
Class classDriver = cl.loadClass(prop.getProperty(KEY_DRIVER_PROVISIONING));
ProvisioningApplication.setDriver(classDriver, prop);
ProvisioningApplication app = new ProvisioningApplication();
app.modifyRoot((Router) taskApp.getRoot());
log.info("Provisioning application active.");
} catch (IllegalArgumentException iae) {
log.error("Driver didn't extend the expected class.");
} catch (ClassNotFoundException cnfe) {
log.error("The Provisioning driver class was not loaded. Check the driver folder contents.");
System.out.println("The Provisioning driver class was not loaded. Check the driver folder contents.");
System.exit(ERROR_CODE_DRIVERS);
}
}
if (prop.get(KEY_DRIVER_TEMPLATEMANAGEMENT) != null && !prop.get(KEY_DRIVER_TEMPLATEMANAGEMENT).equals("")) {
try {
Class classDriver = cl.loadClass(prop.getProperty(KEY_DRIVER_TEMPLATEMANAGEMENT));
TemplateManagementApplication.setDriver(classDriver, prop);
TemplateManagementApplication app = new TemplateManagementApplication();
app.modifyRoot((Router) taskApp.getRoot());
log.info("TemplateManagement application active.");
} catch (IllegalArgumentException iae) {
log.error("Driver didn't extend the expected class.");
} catch (ClassNotFoundException cnfe) {
log.error("The Template Manager driver class was not loaded. Check the driver folder contents.");
System.out.println("The Template Manager class was not loaded. Check the driver folder contents.");
System.exit(ERROR_CODE_DRIVERS);
}
}
if (prop.get(KEY_DRIVER_CONSOLE) != null && !prop.get(KEY_DRIVER_CONSOLE).equals("")) {
try {
Class classDriver = cl.loadClass(prop.getProperty(KEY_DRIVER_CONSOLE));
ConsoleApplication.setDriver(classDriver, prop);
ConsoleApplication app = new ConsoleApplication();
app.modifyRoot((Router) taskApp.getRoot());
log.info("Console application active.");
} catch (IllegalArgumentException iae) {
log.error("Driver didn't extend the expected class.");
} catch (ClassNotFoundException cnfe) {
log.error("The Console driver class was not loaded. Check the driver folder contents.");
System.out.println("The Console driver class was not loaded. Check the driver folder contents.");
System.exit(ERROR_CODE_DRIVERS);
}
}
final String staticDocRoot = prop.getProperty("com.telefonica.claudia.server.docroot");
if (staticDocRoot != null && staticDocRoot.trim().equals("") == false) {
// start serving static files
// @see http://www.restlet.org/documentation/1.1/tutorial#part06
Application application = new Application(component.getContext().createChildContext()) {
@Override
public Restlet createRoot() {
return new Directory(getContext(), staticDocRoot);
}
};
((Router) taskApp.getRoot()).attach("", application);
}
// Start the component.
component.getDefaultHost().attach(taskApp);
component.start();
log.info("Service started");
}Example 27
| Project: floodlight-qos-beta-master File: RestApiServer.java View source code |
public void run(FloodlightModuleContext fmlContext, 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();
component.getServers().add(Protocol.HTTP, restPort);
component.getClients().add(Protocol.CLAP);
component.getDefaultHost().attach(this);
component.start();
} catch (Exception e) {
throw new RuntimeException(e);
}
}Example 28
| Project: FL_HAND-master File: RestApiServer.java View source code |
public void run(FloodlightModuleContext fmlContext, 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();
component.getServers().add(Protocol.HTTP, restPort);
component.getClients().add(Protocol.CLAP);
component.getDefaultHost().attach(this);
component.start();
} catch (Exception e) {
throw new RuntimeException(e);
}
}Example 29
| Project: freedomotic-master File: RestApi.java View source code |
@Override
public void onStart() {
try {
super.onStart();
component = new Component();
component.getClients().add(Protocol.FILE);
//TODO: To test with the restlet 2.1 Maybe the maxTotalConnections could be avoided
// see: http://restlet-discuss.1400322.n2.nabble.com/rejectedExecution-td4513620.html
//component.getServers().add(Protocol.HTTP, SERVER_PORT);
Server server = new Server(Protocol.HTTP, SERVER_PORT);
component.getServers().add(server);
server.getContext().getParameters().add("maxTotalConnections", "50");
//end TODO
// enable SSL
Server SSLserver = new Server(Protocol.HTTPS, configuration.getIntProperty("SSL_PORT", SERVER_PORT + 2));
component.getServers().add(SSLserver);
Series<Parameter> parameters = SSLserver.getContext().getParameters();
parameters.add("sslContextFactory", "org.restlet.ext.ssl.PkixSslContextFactory");
// Certificate's data is taken from config file
parameters.add("keystorePath", new File(this.getFile().getParent() + "/data/" + configuration.getStringProperty("KEYSTORE_FILE", "keystore")).getAbsolutePath());
parameters.add("keystorePassword", configuration.getStringProperty("KEYSTORE_PASSWORD", "password"));
parameters.add("keyPassword", configuration.getStringProperty("KEYSTORE_PASSWORD", "password"));
parameters.add("keystoreType", configuration.getStringProperty("KEYSTORE_TYPE", "JKS"));
// end enable SSL
// Engine.getInstance().getRegisteredServers().clear();
// Engine.getInstance().getRegisteredServers().add(new HttpServerHelper(server));
// Engine.getInstance().getRegisteredServers().add(new HttpServerHelper(SSLserver));
component.getClients().add(Protocol.FILE);
OriginFilter originFilter = new OriginFilter(component.getContext().createChildContext(), this);
Application FDapp = new FreedomRestServer(Info.PATHS.PATH_RESOURCES_FOLDER.getAbsolutePath(), component.getContext().createChildContext());
if (getApi().getAuth().isInited()) {
// Instantiates a Verifier of identifier/secret couples based on Freedomotic Auth
Verifier v = new SecretVerifier() {
@Override
public int verify(String identifier, char[] secret) {
if (getApi().getAuth().login(identifier, secret)) {
return RESULT_VALID;
}
return RESULT_INVALID;
}
};
// Guard the restlet with BASIC authentication.
ChallengeAuthenticator guard = new ChallengeAuthenticator(component.getContext().createChildContext(), false, ChallengeScheme.HTTP_BASIC, "testRealm", v);
// WIP: Guard the restlet with DIGEST authentication.
DigestAuthenticator dguard = new DigestAuthenticator(component.getContext().createChildContext(), "DigestRealm", configuration.getStringProperty("DIGEST_SECRET", "s3cr3t"));
dguard.setOptional(true);
// TODO: set proper verifier before enabling DIGEST AUTH.
originFilter.setNext(guard);
guard.setNext(FDapp);
} else {
originFilter.setNext(FDapp);
}
component.getDefaultHost().attachDefault(originFilter);
component.start();
freedomoticApi = getApi();
} catch (Exception ex) {
Logger.getLogger(RestApi.class.getName()).log(Level.SEVERE, null, ex);
}
}Example 30
| Project: geni-openflow-vertical-handover-master File: RestApiServer.java View source code |
public void run(FloodlightModuleContext fmlContext, 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();
component.getServers().add(Protocol.HTTP, restPort);
component.getClients().add(Protocol.CLAP);
component.getDefaultHost().attach(this);
component.start();
} catch (Exception e) {
throw new RuntimeException(e);
}
}Example 31
| Project: geotools-2.7.x-master File: MockSimpleFeatureService.java View source code |
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, 8082);
// Attach the application which has all the mock url added
component.getDefaultHost().attach("/simplefeatureservice", new MockSimpleFeatureService());
// Start the component.
component.start();
} catch (Exception e) {
System.out.println("Exception in StandAloneApplication " + e.getMessage());
}
}Example 32
| Project: geotools-master File: MockSimpleFeatureService.java View source code |
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, 8082);
// Attach the application which has all the mock url added
component.getDefaultHost().attach("/simplefeatureservice", new MockSimpleFeatureService());
// Start the component.
component.start();
} catch (Exception e) {
System.out.println("Exception in StandAloneApplication " + e.getMessage());
}
}Example 33
| Project: geotools-old-master File: MockSimpleFeatureService.java View source code |
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, 8082);
// Attach the application which has all the mock url added
component.getDefaultHost().attach("/simplefeatureservice", new MockSimpleFeatureService());
// Start the component.
component.start();
} catch (Exception e) {
System.out.println("Exception in StandAloneApplication " + e.getMessage());
}
}Example 34
| Project: geotools_trunk-master File: MockSimpleFeatureService.java View source code |
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, 8082);
// Attach the application which has all the mock url added
component.getDefaultHost().attach("/simplefeatureservice", new MockSimpleFeatureService());
// Start the component.
component.start();
} catch (Exception e) {
System.out.println("Exception in StandAloneApplication " + e.getMessage());
}
}Example 35
| Project: HederaInFloodlight-master File: RestApiServer.java View source code |
public void run(FloodlightModuleContext fmlContext, 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();
component.getServers().add(Protocol.HTTP, restPort);
component.getClients().add(Protocol.CLAP);
component.getDefaultHost().attach(this);
component.start();
} catch (Exception e) {
throw new RuntimeException(e);
}
}Example 36
| Project: jpasskit-master File: PKRestServer.java View source code |
private void createPKRestWebService() {
restTrustedServerComponent = new Component();
String bindIp = serverConfigurationProperties.getProperty(SERVER_BIND_IP_KEY);
int bindPort = Integer.parseInt(serverConfigurationProperties.getProperty(SERVER_BIND_PORT_KEY));
boolean useSSL = Boolean.parseBoolean(serverConfigurationProperties.getProperty(SERVER_BIND_SSL_ENABLED_KEY));
Protocol httpProtocol = Protocol.HTTP;
if (useSSL) {
httpProtocol = Protocol.HTTPS;
}
restTrustedServer = new Server(httpProtocol, bindIp, bindPort);
restTrustedServerComponent.getServers().add(restTrustedServer);
if (useSSL) {
setupSSL();
}
final Router router = new Router(restTrustedServerComponent.getContext().createChildContext());
restTrustedServerComponent.getDefaultHost().attach("", router);
PKDeviceResourceFactory pkDeviceResourceFactory = new PKDeviceResourceFactory(pkRestletServerResourceFactory);
PKPassResourceFactory pkPassResourceFactory = new PKPassResourceFactory(pkRestletServerResourceFactory);
PKPersonalizePassResourceFactory pkPersonalizePassResourceFactory = new PKPersonalizePassResourceFactory(pkRestletServerResourceFactory);
PKLogResourceFactory pkLogResourceFactory = new PKLogResourceFactory(pkRestletServerResourceFactory);
router.attach("/" + version + "/devices/{deviceLibraryIdentifier}/registrations/{passTypeIdentifier}/{serialNumber}", pkDeviceResourceFactory);
router.attach("/" + version + "/devices/{deviceLibraryIdentifier}/registrations/{passTypeIdentifier}", pkDeviceResourceFactory);
router.attach("/" + version + "/passes/{passTypeIdentifier}/{serialNumber}", pkPassResourceFactory);
router.attach("/" + version + "/passes/{passTypeIdentifier}/{serialNumber}/personalize", pkPersonalizePassResourceFactory);
router.attach("/" + version + "/log", pkLogResourceFactory);
LOGGER.debug("Created Restlet components");
}Example 37
| Project: open-rmbt-master File: RestService.java View source code |
@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);
}
}
}
}Example 38
| Project: resthub-master File: ServerWorker.java View source code |
public void startServer() throws Exception {
if (Files.exists(FOLDER)) {
Files.walkFileTree(FOLDER, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
Files.delete(file);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
Files.delete(dir);
return FileVisitResult.CONTINUE;
}
});
}
ServerAppConfig cfg = new ServerAppConfig();
cfg.setUpdateInterval(10);
cfg.setServiceVersion("1.11.11");
if (tunnelExecutor != null) {
cf = new TestConnectionFactory(tunnel_url, username, password);
} else {
cf = new TestConnectionFactory(url, username, password);
}
ServerApp app = new ServerApp(cf, new TableFactory.Builder().add(new XmlResourceTableFactory(XML_RESOURCE)).add(new XmlFolderTableFactory(XML_FOLDER)).add(new TestSqlTableFactory()).build(), cfg);
comp = new Component();
comp.getServers().add(Protocol.HTTP, 8112);
comp.getDefaultHost().attach(app);
comp.start();
}Example 39
| Project: spring-open-master File: TestRestApiServer.java View source code |
/**
* Run the Application on an open port.
*
*/
public void run() {
try {
setStatusService(new StatusService() {
@Override
public Representation getRepresentation(Status status, Request request, Response response) {
return new JacksonRepresentation<>(status);
}
});
// Start listening for REST requests
component = new Component();
server = component.getServers().add(Protocol.HTTP, 0);
component.getDefaultHost().attach(this);
component.start();
} catch (Exception e) {
throw new IllegalStateException(e);
}
}Example 40
| Project: ubuntu-packaging-floodlight-master File: RestApiServer.java View source code |
public void run(FloodlightModuleContext fmlContext, 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.isDebugEnabled()) {
logger.debug("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();
component.getServers().add(Protocol.HTTP, restPort);
component.getClients().add(Protocol.CLAP);
component.getDefaultHost().attach(this);
component.start();
} catch (Exception e) {
throw new RuntimeException(e);
}
}Example 41
| Project: yaqp-turbo-master File: YAQP.java View source code |
private static final void startHttpServer() throws Exception {
Logger L = Logger.getLogger("grizzly");
L.setLevel(Level.SEVERE);
int PORT = Configuration.PORT;
YaqpApplication application = new Applecation();
Component component = new Component();
component.getServers().add(Protocol.HTTP, PORT);
application.setContext(component.getContext().createChildContext());
component.getDefaultHost().attach("", application);
component.start();
System.out.print("[ DONE ] \n");
fancyPrint("*\n* Server is up and accepts connections on port " + PORT + "!\n*\n", 10);
}Example 42
| Project: floodlight-nfv-master File: RestApiServer.java View source code |
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 43
| Project: floodlightUI-master File: RestApiServer.java View source code |
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 44
| Project: floodlight_with_topoguard-master File: RestApiServer.java View source code |
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 45
| Project: kd-cloud-master File: RestletTestCase.java View source code |
@Before
public void setUp() {
testContext = new Context();
component = new Component();
component.getServers().add(Protocol.HTTP, PORT);
component.getClients().add(Protocol.CLAP);
component.getClients().add(Protocol.FILE);
component.getDefaultHost().attach(testApp);
try {
component.start();
factory.setUp();
} catch (Exception e) {
e.printStackTrace();
Assert.fail();
}
}Example 46
| Project: lzusdn-master File: RestApiServer.java View source code |
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 47
| Project: moxie-master File: Launcher.java View source code |
/**
* Start Moxie Proxy
* @param config
*/
static void start(ProxyConfig config) throws Exception {
Engine.setRestletLogLevel(Level.INFO);
Component c = new Component();
// turn off Restlet url access logging
c.getLogService().setEnabled(config.getAccessLog());
// specify the Jetty helpers
String httpHelper = "org.restlet.ext.jetty.HttpServerHelper";
String httpsHelper = "org.restlet.ext.jetty.HttpsServerHelper";
// create a Restlet server
if (config.getBindAddresses().size() == 0) {
// start server on all available addresses
if (config.getHttpPort() > 0) {
Server server = new Server(null, Arrays.asList(Protocol.HTTP), null, config.getHttpPort(), c, httpHelper);
c.getServers().add(server);
}
if (config.getHttpsPort() > 0) {
Server server = new Server(null, Arrays.asList(Protocol.HTTPS), null, config.getHttpsPort(), c, httpsHelper);
c.getServers().add(server);
configureHttps(server, config);
}
} else {
// start server on specific address(es)
for (String address : config.getBindAddresses()) {
if (config.getHttpPort() > 0) {
Server server = new Server(null, Arrays.asList(Protocol.HTTP), address, config.getHttpPort(), c, httpHelper);
c.getServers().add(server);
}
if (config.getHttpsPort() > 0) {
Server server = new Server(null, Arrays.asList(Protocol.HTTPS), address, config.getHttpsPort(), c, httpsHelper);
c.getServers().add(server);
configureHttps(server, config);
}
}
}
// add client classpath protocol to enable resource loading from the jar
c.getClients().add(Protocol.CLAP);
// add client file protocol to enable serving artifacts from filesystem
c.getClients().add(Protocol.FILE);
// override the default error pages
c.setStatusService(new ErrorStatusService(c.getContext()));
// get the default virtual host
VirtualHost host = c.getDefaultHost();
MoxieProxy app = new MoxieProxy(config);
// Guard Moxie Proxy with BASIC authentication.
Authenticator guard = new Authenticator(app);
host.attachDefault(guard);
guard.setNext(app);
// start the shutdown monitor
if (config.getShutdownPort() > 0) {
Thread shutdownMonitor = new ShutdownMonitorThread(c, app, config);
shutdownMonitor.start();
}
// start the Restlet http/https server
c.start();
}Example 48
| Project: pinot-master File: StarTreeIndexViewer.java View source code |
private void startServer(final File segmentDirectory, final String json) throws Exception {
Component component = new Component();
int port = 8090;
component.getServers().add(Protocol.HTTP, port);
component.getClients().add(Protocol.FILE);
Application application = new Application() {
@Override
public Restlet createInboundRoot() {
Router router = new Router(getContext());
StarTreeViewRestResource.json = json;
router.attach("/data", StarTreeViewRestResource.class);
Directory directory = new Directory(getContext(), getClass().getClassLoader().getResource("star-tree.html").toString());
router.attach(directory);
return router;
}
};
VirtualHost defaultHost = component.getDefaultHost();
defaultHost.attach(application);
component.start();
LOGGER.info("Go to http://{}:{}/ to view the star tree", VirtualHost.getLocalHostName(), port);
}Example 49
| Project: snoozenode-master File: Main.java View source code |
/**
* Initializes the component.
*
* @param component The component
* @param context The context
* @param configuration The node parameters
* @throws Exception
*/
private static void initializeRESTletComponent(Component component, Context context, NodeConfiguration configuration) throws Exception {
Guard.check(component, context, configuration);
log_.debug("Initializing the RESTlet component");
Engine.getInstance().getRegisteredClients().clear();
Engine.getInstance().getRegisteredClients().add(new HttpClientHelper(null));
component.getClients().add(Protocol.HTTP);
Server jettyServer = new Server(context, Protocol.HTTP, configuration.getNetworking().getListen().getControlDataAddress().getPort(), component);
HTTPdSettings settings = configuration.getHTTPd();
jettyServer.getContext().getParameters().add("maxThreads", settings.getMaximumNumberOfThreads());
jettyServer.getContext().getParameters().add("maxTotalConnections", settings.getMaximumNumberOfConnections());
jettyServer.getContext().getParameters().add("maxThreads", settings.getMaximumNumberOfThreads());
jettyServer.getContext().getParameters().add("maxTotalConnections", settings.getMaximumNumberOfConnections());
jettyServer.getContext().getParameters().add("minThreads", settings.getMinThreads());
jettyServer.getContext().getParameters().add("lowThreads", settings.getLowThreads());
jettyServer.getContext().getParameters().add("maxThreads", settings.getMaxThreads());
jettyServer.getContext().getParameters().add("maxQueued", settings.getMaxQueued());
jettyServer.getContext().getParameters().add("maxIoIdleTimeMs", settings.getMaxIoIdleTimeMs());
component.getServers().add(jettyServer);
}Example 50
| Project: floodlight-master File: RestApiServer.java View source code |
public void run(FloodlightModuleContext fmlContext, String restHost) {
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));
}
/*
* Specifically add the FML for use by the REST API's /wm/core/modules/...
*/
context.getAttributes().put(fmlContext.getModuleLoader().getClass().getCanonicalName(), fmlContext.getModuleLoader());
/* Start listening for REST requests */
try {
final Component component = new Component();
if (RestApiServer.useHttps) {
Server server;
if (restHost == null) {
server = component.getServers().add(Protocol.HTTPS, Integer.valueOf(RestApiServer.httpsPort));
} else {
server = component.getServers().add(Protocol.HTTPS, restHost, Integer.valueOf(RestApiServer.httpsPort));
}
Series<Parameter> parameters = server.getContext().getParameters();
//parameters.add("sslContextFactory", "org.restlet.ext.jsslutils.PkixSslContextFactory");
parameters.add("sslContextFactory", "org.restlet.engine.ssl.DefaultSslContextFactory");
parameters.add("keystorePath", RestApiServer.keyStore);
parameters.add("keystorePassword", RestApiServer.keyStorePassword);
parameters.add("keyPassword", RestApiServer.keyStorePassword);
parameters.add("keystoreType", "JKS");
parameters.add("truststorePath", RestApiServer.keyStore);
parameters.add("truststorePassword", RestApiServer.keyStorePassword);
parameters.add("trustPassword", RestApiServer.keyStorePassword);
parameters.add("truststoreType", "JKS");
parameters.add("needClientAuthentication", RestApiServer.httpsNeedClientAuth);
}
if (RestApiServer.useHttp) {
if (restHost == null) {
component.getServers().add(Protocol.HTTP, Integer.valueOf(RestApiServer.httpPort));
} else {
component.getServers().add(Protocol.HTTP, restHost, Integer.valueOf(RestApiServer.httpPort));
}
}
component.getClients().add(Protocol.CLAP);
component.getDefaultHost().attach(this);
component.start();
} catch (Exception e) {
throw new RuntimeException(e);
}
}Example 51
| Project: dyson-master File: DysonServer.java View source code |
/**
* initializes dyson's REST server instance with port specified
* under {@link DysonConfig#REST_SERVER_PORT} and registers as new
* instance of {@link DysonConfig#REST_SERVER_ROOT_RESTLET_CLASS}.
*/
protected void initRestServer() {
assert this.config != null;
int port = this.getConfiguration().get(REST_SERVER_PORT).getIntValue();
DysonRestApp app = this.newDysonPart(REST_APPLICATION_CLASS, DysonRestApp.class);
// this.restServer = new Server( Protocol.HTTP, port, app );
Component component = new Component();
component.getServers().add(Protocol.HTTP, port);
component.getClients().add(Protocol.FILE);
component.getDefaultHost().attach(app);
this.restComponent = component;
}Example 52
| Project: seqware-master File: SeqWareWebServiceApplication.java View source code |
/**
* Creates a root Restlet that will receive all incoming calls.
*
* @return a {@link org.restlet.Restlet} object.
*/
@Override
public synchronized Restlet createInboundRoot() {
final Component component = new Component();
component.getClients().add(Protocol.CLAP);
ChallengeAuthenticator guard = getGuard();
// String rootURL = "";
// if (EnvUtil.getProperty("urlhack") != null) { rootURL = EnvUtil.getProperty("urlhack"); }
// We don't want to use CGLIB since it is a huge memory hog
// see for more information: http://beanlib.svn.sourceforge.net/viewvc/beanlib/trunk/beanlib-doc/faq.html
UnEnhancer.setDefaultCheckCGLib(false);
String version = "queryengine";
// if (EnvUtil.getProperty("version") != null) { rootURL = EnvUtil.getProperty("version"); }
// Create a router Restlet that routes each call to a
// new instance of HelloWorldResource.
Router router = new Router(getContext());
router.setDefaultMatchingQuery(false);
router.setRoutingMode(Router.MODE_LAST_MATCH);
// I don't know if this is needed anymore
getConnectorService().getClientProtocols().add(Protocol.FILE);
Restlet slashRedirect = new OptionalSlashRedirect(getContext());
router.attachDefault(EnvironmentResource.class);
/*
* New version of webservices
*/
router.attach("/SWA/", SeqwareAccessionResource.class);
router.attach("/SWA/{SWA}", SeqwareAccessionIDResource.class);
router.attach("/experiments", ExperimentResource.class);
router.attach("/experiments/", slashRedirect);
router.attach("/experiments/{experimentId}", ExperimentIDResource.class);
router.attach("/experiments/{experimentId}/samples", SampleIDFilter.class);
// router.attach("/experiments/{ID}/processes", Resource.class);
// router.attach("/experiments/{ID}/processes/{ID}", Resource.class);
//
// TODO: make sure sequencer run, lane, and IUS have post methods!
router.attach("/platforms", PlatformResource.class);
router.attach("/platforms/", slashRedirect);
router.attach("/studytypes", StudyTypeResource.class);
router.attach("/studytypes/", slashRedirect);
router.attach("/libraryselections", LibrarySelectionResource.class);
router.attach("/libraryselections/", slashRedirect);
router.attach("/librarysources", LibrarySourceResource.class);
router.attach("/librarysources/", slashRedirect);
router.attach("/librarystrategies", LibraryStrategyResource.class);
router.attach("/librarystrategies/", slashRedirect);
router.attach("/organisms", OrganismResource.class);
router.attach("/organisms/", slashRedirect);
router.attach("/experimentspotdesigns", ExperimentSpotDesignResource.class);
router.attach("/experimentspotdesigns/", slashRedirect);
router.attach("/experimentlibrarydesigns", ExperimentLibraryDesignResource.class);
router.attach("/experimentlibrarydesigns/", slashRedirect);
router.attach("/experimentspotdesignreadspecs", ExperimentSpotDesignReadSpecResource.class);
router.attach("/experimentspotdesignreadspecs/", slashRedirect);
router.attach("/files", FileResource.class);
router.attach("/files/", slashRedirect);
router.attach("/files/{fileId}", FileIDResource.class);
router.attach("/ius", IusResource.class);
router.attach("/ius/", slashRedirect);
router.attach("/ius/{iusId}", IusIDResource.class);
router.attach("/ius/{iusId}/lane", LaneIDFilter.class);
router.attach("/lanes", LaneResource.class);
router.attach("/lanes/", slashRedirect);
router.attach("/lanes/{laneId}", LaneIDResource.class);
router.attach("/lanes/{laneId}/ius", IUSIDFilter.class);
router.attach("/processes", ProcessResource.class);
router.attach("/processes/", slashRedirect);
router.attach("/processes/{processId}", ProcessIDResource.class);
router.attach("/processes/{processId}/parents", new ProcessIdProcessResource(getContext()));
// router.attach("/processes/{ID}/parents", Resource.class);
// router.attach("/processes/{ID}/parents/{ID}", Resource.class);
// router.attach("/processes/{ID}/children", Resource.class);
// router.attach("/processes/{ID}/children/{ID}", Resource.class);
//
router.attach("/samples", SampleResource.class);
router.attach("/samples/", slashRedirect);
router.attach("/samples/{sampleId}", SampleIDResource.class);
router.attach("/samples/{parentId}/children", SampleIDFilter.class);
router.attach("/samples/{childId}/parents", SampleIDFilter.class);
router.attach("/samples/{sampleId}/ius", IUSIDFilter.class);
router.attach("/samples/root", RootSampleResource.class);
router.attach("/samples/root/", slashRedirect);
// router.attach("/samples/{ID}/processes", Resource.class);
// router.attach("/samples/{ID}/processes/{ID}", Resource.class);
//
router.attach("/sequencerruns", SequencerRunResource.class);
router.attach("/sequencerruns/", slashRedirect);
router.attach("/sequencerruns/{sequencerRunId}", SequencerRunIDResource.class);
router.attach("/sequencerruns/{sequencerRunId}/lanes", LaneIDFilter.class);
// router.attach("/sequencer_runs/{ID}/lanes", Resource.class);
// router.attach("/sequencer_runs/{ID}/lanes/{ID}", Resource.class);
// router.attach("/sequencer_runs/{ID}/processes/", Resource.class);
// router.attach("/sequencer_runs/{ID}/processes/{ID}", Resource.class);
//
router.attach("/studies", StudyResource.class);
router.attach("/studies/", slashRedirect);
router.attach("/studies/{studyId}", StudyIDResource.class);
router.attach("/studies/{studyId}/experiments", ExperimentIDFilter.class);
//
router.attach("/workflowruns", WorkflowRunResource.class);
router.attach("/workflowruns/", slashRedirect);
router.attach("/workflowruns/{workflowRunId}", WorkflowRunIDResource.class);
router.attach("/workflowruns/{workflowRunId}/files", new WorkflowRunIdFilesResource(getContext()));
router.attach("/workflowruns/{workflowRunId}/processings", new WorkflowRunIDProcessingsResource(getContext()));
router.attach("/workflowruns/{workflowRunId}/workflow", new WorkflowRunIDWorkflowResource(getContext()));
router.attach("/workflows", WorkflowResource.class);
router.attach("/workflows/", slashRedirect);
router.attach("/workflows/{workflowId}", WorkflowIDResource.class);
router.attach("/workflows/{workflowId}/runs", new RunWorkflowResource(getContext()));
router.attach("/workflows/{workflowId}/runs/", slashRedirect);
router.attach("/workflowparams", WorkflowParamResource.class);
router.attach("/workflowparams/", slashRedirect);
router.attach("/workflowparams/{workflowParamId}", WorkflowParamIDResource.class);
router.attach("/workflowparamvalues", WorkflowParamValueResource.class);
router.attach("/workflowparamvalues/", slashRedirect);
router.attach("/workflowparamvalues/{workflowParamValueId}", WorkflowParamValueIDResource.class);
/*
* Reports
*/
router.attach("/reports/file-provenance", new FileProvenanceResource(getContext()));
router.attach("/reports/file-provenance/generate", new TriggerFileProvenanceResource(getContext()));
// the following collides with the non-variable paths.
// router.attach("/reports/studies/{studyId}", new CycleCheckResource(getContext()));
router.attach("/reports/workflows/{workflowId}", new WorkflowReportResource(getContext()));
WorkflowRunReportResource wrrr = new WorkflowRunReportResource(getContext());
router.attach("/reports/workflowruns/{workflowRunId}", wrrr);
router.attach("/reports/workflowruns", wrrr);
router.attach("/reports/workflows/{workflowId}/runs", wrrr);
router.attach("/reports/workflowruns/", slashRedirect);
router.attach("/reports/workflows/{workflowId}/runs/", slashRedirect);
router.attach("/reports/workflowruns/{workflowRunId}/stderr", wrrr);
router.attach("/reports/workflowruns/{workflowRunId}/stdout", wrrr);
router.attach("/reports/workflowruns/{workflowRunId}/stderr/", slashRedirect);
router.attach("/reports/workflowruns/{workflowRunId}/stdout/", slashRedirect);
// A report giving runtime info for workflows
router.attach("/reports/workflowruntimes", new WorkflowRuntimeResource(getContext()));
// A report giving workflow runs that are relevant for a group of files
router.attach("/reports/fileworkflowruns", FileChildWorkflowRunsResource.class);
router.attach("/reports/fileworkflowruns/", slashRedirect);
router.attach("/reports/fileworkflowruns/limit", FileChildLimitedWorkflowRunsResource.class);
router.attach("/reports/fileworkflowruns/limit/", slashRedirect);
// STATIC COMPONENTS
router.attach("/x/report/filelinkreport", FileLinkReportResource.class);
router.attach("/x/report/filelinkreport/{swas}", FileLinkReportResource.class);
router.attach("/x/report/reversehierarchy/{swa}", FileReverseHierarchyDisplayResource.class);
// Directory directory = new Directory(getContext(), "war:///WEB-INF/html");
// router.attachDefault(directory);
// router.attach("/" + version + "/static", directory);
router.attach("/processingstructure", new ProcessingStructureResource(getContext()));
router.attach("/sample/parents", new SampleHierarchyResource(getContext()));
guard.setNext(router);
return guard;
}Example 53
| Project: twitlogic-master File: TweetStore.java View source code |
public void startServer(final TwitterClient client) throws ServerException {
twitterClient = client;
try {
String internalBaseURI = TwitLogic.getConfiguration().getURI(TwitLogic.SERVER_BASEURI).toString();
String externalBaseURI = TwitLogic.BASE_URI;
final String datasetURI = TwitLogic.TWITLOGIC_DATASET;
int port = TwitLogic.getConfiguration().getInt(TwitLogic.SERVER_PORT, DEFAULT_PORT);
File staticContentDir = TwitLogic.getConfiguration().getFile(TwitLogic.SERVER_STATICCONTENTDIRECTORY);
LinkedDataServer server = new LinkedDataServer(this.getSail(), internalBaseURI, externalBaseURI, datasetURI);
Component component = new Component();
server.setInboundRoot(component);
component.getServers().add(Protocol.HTTP, port);
component.getServers().add(Protocol.FILE, port);
component.getDefaultHost().attach("/", new Directory(server.getContext(), "file://" + staticContentDir + "/"));
for (TwitLogic.ResourceType t : TwitLogic.ResourceType.values()) {
String p = t.getUriPath();
if (!p.equals("graph") && !p.equals("person")) {
component.getDefaultHost().attach("/" + p + "/", WebResource.class);
}
}
component.getDefaultHost().attach("/person/twitter/", PersonResource.class);
component.getDefaultHost().attach("/graph/", GraphResource.class);
component.getDefaultHost().attach("/sparql", new SparqlResource());
component.getDefaultHost().attach("/stream/relatedTweets", new RelatedTweetsResource());
component.getDefaultHost().attach("/stream/relatedTags", new RelatedHashtagsResource());
server.start();
} catch (Throwable e) {
throw new ServerException(e);
}
}Example 54
| Project: Heritrix-3-master File: Heritrix.java View source code |
public void instanceMain(String[] args) throws Exception {
System.out.println(System.getProperty("java.vendor") + ' ' + System.getProperty("java.runtime.name") + ' ' + System.getProperty("java.runtime.version"));
// ensure using java 1.6+ before hitting a later cryptic error
String version = System.getProperty("java.version");
float floatVersion = Float.valueOf(version.substring(0, version.indexOf('.', 2)));
if (floatVersion < 1.6) {
System.err.println("Heritrix (as of version 3) requires Java 1.6 or higher.");
System.err.println("You attempted to launch with: " + version);
System.err.println("Please try again with a later Java.");
System.exit(1);
}
// Set some system properties early.
// Can't use class names here without loading them.
String ignoredSchemes = "org.archive.net.UURIFactory.ignored-schemes";
if (System.getProperty(ignoredSchemes) == null) {
System.setProperty(ignoredSchemes, "mailto, clsid, res, file, rtsp, about");
}
String maxFormSize = "org.mortbay.jetty.Request.maxFormContentSize";
if (System.getProperty(maxFormSize) == null) {
System.setProperty(maxFormSize, "52428800");
}
BufferedOutputStream startupOutStream = new BufferedOutputStream(new FileOutputStream(new File(getHeritrixHome(), STARTLOG)), 16384);
PrintStream startupOut = new PrintStream(new TeeOutputStream(System.out, startupOutStream));
CommandLine cl = getCommandLine(startupOut, args);
if (cl == null)
return;
if (cl.hasOption('h')) {
usage(startupOut, args);
return;
}
// DEFAULTS until changed by cmd-line options
int port = 8443;
Set<String> bindHosts = new HashSet<String>();
String authLogin = "admin";
String authPassword = null;
String keystorePath;
String keystorePassword;
String keyPassword;
File properties = getDefaultPropertiesFile();
String aOption = cl.getOptionValue('a');
if (cl.hasOption('a')) {
String usernameColonPassword = aOption;
try {
if (aOption.startsWith("@")) {
usernameColonPassword = FileUtils.readFileToString(new File(aOption.substring(1))).trim();
}
int colonIndex = usernameColonPassword.indexOf(':');
if (colonIndex > -1) {
authLogin = usernameColonPassword.substring(0, colonIndex);
authPassword = usernameColonPassword.substring(colonIndex + 1);
} else {
authPassword = usernameColonPassword;
}
} catch (IOException e) {
System.err.println("Unable to read [username:]password from " + aOption);
}
}
if (authPassword == null) {
System.err.println("You must specify a valid [username:]password for the web interface using -a.");
System.exit(1);
// suppresses uninitialized warning
authPassword = "";
}
File jobsDir = null;
if (cl.hasOption('j')) {
jobsDir = new File(cl.getOptionValue('j'));
} else {
jobsDir = new File("./jobs");
}
if (cl.hasOption('l')) {
properties = new File(cl.getOptionValue('l'));
}
if (cl.hasOption('b')) {
String hosts = cl.getOptionValue('b');
List<String> list;
if ("/".equals(hosts)) {
// '/' means all, signified by empty-list
list = new ArrayList<String>();
} else {
list = Arrays.asList(hosts.split(","));
}
bindHosts.addAll(list);
} else {
// default: only localhost
bindHosts.add("localhost");
}
if (cl.hasOption('p')) {
port = Integer.parseInt(cl.getOptionValue('p'));
}
// is created or reused
if (cl.hasOption('s')) {
String[] sslParams = cl.getOptionValue('s').split(",");
keystorePath = sslParams[0];
keystorePassword = sslParams[1];
keyPassword = sslParams[2];
} else {
// use ad hoc keystore, creating if necessary
keystorePath = ADHOC_KEYSTORE;
keystorePassword = ADHOC_PASSWORD;
keyPassword = ADHOC_PASSWORD;
useAdhocKeystore(startupOut);
}
if (properties.exists()) {
FileInputStream finp = new FileInputStream(properties);
LogManager.getLogManager().readConfiguration(finp);
finp.close();
}
// Set timezone here. Would be problematic doing it if we're running
// inside in a container.
TimeZone.setDefault(TimeZone.getTimeZone("GMT"));
setupGlobalProperties(port);
// Start Heritrix.
try {
engine = new Engine(jobsDir);
component = new Component();
if (bindHosts.isEmpty()) {
// listen all addresses
setupServer(port, null, keystorePath, keystorePassword, keyPassword);
} else {
// bind only to declared addresses, or just 'localhost'
for (String address : bindHosts) {
setupServer(port, address, keystorePath, keystorePassword, keyPassword);
}
}
component.getClients().add(Protocol.FILE);
component.getClients().add(Protocol.CLAP);
Guard guard = new RateLimitGuard(null, ChallengeScheme.HTTP_DIGEST, "Authentication Required");
guard.getSecrets().put(authLogin, authPassword.toCharArray());
component.getDefaultHost().attach(guard);
guard.setNext(new EngineApplication(engine));
component.start();
startupOut.println("engine listening at port " + port);
startupOut.println("operator login set per " + ((aOption.startsWith("@")) ? "file " + aOption : "command-line"));
if (authPassword.length() < 8 || authPassword.matches("[a-zA-Z]{0,10}") || authPassword.matches("\\d{0,10}")) {
startupOut.println("NOTE: We recommend a longer, stronger password, especially if your web \n" + "interface will be internet-accessible.");
}
if (cl.hasOption('r')) {
engine.requestLaunch(cl.getOptionValue('r'));
}
} catch (Exception e) {
e.printStackTrace(startupOut);
if (component != null) {
component.stop();
}
throw e;
} finally {
startupOut.flush();
// stop writing to side startup file
startupOutStream.close();
System.out.println("Heritrix version: " + ArchiveUtils.VERSION);
}
}Example 55
| Project: heritrix3-master File: Heritrix.java View source code |
public void instanceMain(String[] args) throws Exception {
System.out.println(System.getProperty("java.vendor") + ' ' + System.getProperty("java.runtime.name") + ' ' + System.getProperty("java.runtime.version"));
// ensure using java 1.6+ before hitting a later cryptic error
String version = System.getProperty("java.version");
float floatVersion = Float.valueOf(version.substring(0, version.indexOf('.', 2)));
if (floatVersion < 1.6) {
System.err.println("Heritrix (as of version 3) requires Java 1.6 or higher.");
System.err.println("You attempted to launch with: " + version);
System.err.println("Please try again with a later Java.");
System.exit(1);
}
// Set some system properties early.
// Can't use class names here without loading them.
String ignoredSchemes = "org.archive.net.UURIFactory.ignored-schemes";
if (System.getProperty(ignoredSchemes) == null) {
System.setProperty(ignoredSchemes, "mailto, clsid, res, file, rtsp, about");
}
String maxFormSize = "org.mortbay.jetty.Request.maxFormContentSize";
if (System.getProperty(maxFormSize) == null) {
System.setProperty(maxFormSize, "52428800");
}
BufferedOutputStream startupOutStream = new BufferedOutputStream(new FileOutputStream(new File(getHeritrixHome(), STARTLOG)), 16384);
PrintStream startupOut = new PrintStream(new TeeOutputStream(System.out, startupOutStream));
CommandLine cl = getCommandLine(startupOut, args);
if (cl == null)
return;
if (cl.hasOption('h')) {
usage(startupOut, args);
return;
}
// DEFAULTS until changed by cmd-line options
int port = 8443;
Set<String> bindHosts = new HashSet<String>();
String authLogin = "admin";
String authPassword = null;
String keystorePath;
String keystorePassword;
String keyPassword;
File properties = getDefaultPropertiesFile();
String aOption = cl.getOptionValue('a');
if (cl.hasOption('a')) {
String usernameColonPassword = aOption;
try {
if (aOption.startsWith("@")) {
usernameColonPassword = FileUtils.readFileToString(new File(aOption.substring(1))).trim();
}
int colonIndex = usernameColonPassword.indexOf(':');
if (colonIndex > -1) {
authLogin = usernameColonPassword.substring(0, colonIndex);
authPassword = usernameColonPassword.substring(colonIndex + 1);
} else {
authPassword = usernameColonPassword;
}
} catch (IOException e) {
System.err.println("Unable to read [username:]password from " + aOption);
}
}
if (authPassword == null) {
System.err.println("You must specify a valid [username:]password for the web interface using -a.");
System.exit(1);
// suppresses uninitialized warning
authPassword = "";
}
File jobsDir = null;
if (cl.hasOption('j')) {
jobsDir = new File(cl.getOptionValue('j'));
} else {
jobsDir = new File("./jobs");
}
if (cl.hasOption('l')) {
properties = new File(cl.getOptionValue('l'));
}
if (cl.hasOption('b')) {
String hosts = cl.getOptionValue('b');
List<String> list;
if ("/".equals(hosts)) {
// '/' means all, signified by empty-list
list = new ArrayList<String>();
} else {
list = Arrays.asList(hosts.split(","));
}
bindHosts.addAll(list);
} else {
// default: only localhost
bindHosts.add("localhost");
}
if (cl.hasOption('p')) {
port = Integer.parseInt(cl.getOptionValue('p'));
}
// is created or reused
if (cl.hasOption('s')) {
String[] sslParams = cl.getOptionValue('s').split(",");
keystorePath = sslParams[0];
keystorePassword = sslParams[1];
keyPassword = sslParams[2];
} else {
// use ad hoc keystore, creating if necessary
keystorePath = ADHOC_KEYSTORE;
keystorePassword = ADHOC_PASSWORD;
keyPassword = ADHOC_PASSWORD;
useAdhocKeystore(startupOut);
}
if (properties.exists()) {
FileInputStream finp = new FileInputStream(properties);
LogManager.getLogManager().readConfiguration(finp);
finp.close();
}
// Set timezone here. Would be problematic doing it if we're running
// inside in a container.
TimeZone.setDefault(TimeZone.getTimeZone("GMT"));
setupGlobalProperties(port);
// Start Heritrix.
try {
engine = new Engine(jobsDir);
component = new Component();
if (bindHosts.isEmpty()) {
// listen all addresses
setupServer(port, null, keystorePath, keystorePassword, keyPassword);
} else {
// bind only to declared addresses, or just 'localhost'
for (String address : bindHosts) {
setupServer(port, address, keystorePath, keystorePassword, keyPassword);
}
}
component.getClients().add(Protocol.FILE);
component.getClients().add(Protocol.CLAP);
Guard guard = new RateLimitGuard(null, ChallengeScheme.HTTP_DIGEST, "Authentication Required");
guard.getSecrets().put(authLogin, authPassword.toCharArray());
component.getDefaultHost().attach(guard);
guard.setNext(new EngineApplication(engine));
component.start();
startupOut.println("engine listening at port " + port);
startupOut.println("operator login set per " + ((aOption.startsWith("@")) ? "file " + aOption : "command-line"));
if (authPassword.length() < 8 || authPassword.matches("[a-zA-Z]{0,10}") || authPassword.matches("\\d{0,10}")) {
startupOut.println("NOTE: We recommend a longer, stronger password, especially if your web \n" + "interface will be internet-accessible.");
}
if (cl.hasOption('r')) {
engine.requestLaunch(cl.getOptionValue('r'));
}
} catch (Exception e) {
e.printStackTrace(startupOut);
if (component != null) {
component.stop();
}
throw e;
} finally {
startupOut.flush();
// stop writing to side startup file
startupOutStream.close();
System.out.println("Heritrix version: " + ArchiveUtils.VERSION);
}
}Example 56
| Project: opencirm-master File: StartUp.java View source code |
static void commandLineStart(Component server) {
try {
BufferedReader stdReader = new BufferedReader(new InputStreamReader(System.in));
while (true) {
System.out.print("\n>");
String line = stdReader.readLine();
System.out.println("Command: " + line);
if ("stop".equals(line.trim())) {
server.stop();
} else if ("start".equals(line.trim()))
server.start();
else if ("exit".equals(line.trim())) {
server.stop();
}
}
} catch (Exception ex) {
ex.printStackTrace(System.err);
System.exit(-1);
}
}Example 57
| Project: podd-redesign-master File: AbstractResourceImplTest.java View source code |
/**
* Create a new server for each test.
*
* State will only be shared when they use a common database.
*
* @throws Exception
*/
@Before
public void setUp() throws Exception {
this.component = new Component();
this.testPort = AbstractResourceImplTest.getFreePort();
final Server httpServer = new Server(this.component.getContext().createChildContext(), Protocol.HTTP, this.testPort);
AbstractResourceImplTest.setupThreading(httpServer.getContext());
// Add a new HTTP server listening on the given TEST_PORT.
this.component.getServers().add(httpServer);
this.component.getClients().add(Protocol.CLAP);
this.component.getClients().add(Protocol.HTTP);
this.poddApplication = new PoddWebServiceApplicationImpl();
// Attach the sample application.
this.component.getDefaultHost().attach("/podd/", this.poddApplication);
this.poddApplication.setDataRepositoryConfig(this.getTestAliases());
// The application cannot be setup properly until it is attached, as it
// requires Application.getContext() to not return null
ApplicationUtils.setupApplication(this.poddApplication, this.poddApplication.getContext());
TestUtils.setupTestUser(this.poddApplication);
// Start the component.
this.component.start();
AbstractResourceImplTest.setupThreading(this.poddApplication.getContext());
AbstractResourceImplTest.setupThreading(this.component.getContext());
for (final Client nextClient : this.component.getClients()) {
AbstractResourceImplTest.setupThreading(nextClient.getContext());
}
this.testDir = this.tempDirectory.newFolder(this.getClass().getSimpleName()).toPath();
}Example 58
| Project: vorburgers-blueprints-master File: EmbeddedServerLauncher.java View source code |
private static Component startServer() throws Exception { Component component = new Component(); component.getServers().add(Protocol.HTTP, 8182); // component.getClients().add(Protocol.FILE); component.getDefaultHost().attach(new MyFirstRestletApplication()); component.start(); return component; }
Example 59
| Project: concierge-master File: Activator.java View source code |
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();
}Example 60
| Project: FoxBPM-master File: FoxbpmRestServer.java View source code |
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 ...");
}Example 61
| Project: gundog-engine-master File: Main.java View source code |
public static void main(String[] args) throws Exception {
NATPuncher.init();
GameMatcher.init();
Component component = new Component();
component.setLogService(new LogService(false));
component.getServers().add(Protocol.HTTP, Constants.RESTLET_PORT);
component.getDefaultHost().attach(new Main());
component.start();
}Example 62
| Project: HuisKluis-master File: Main.java View source code |
/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
Component component = new Component();
component.getClients().add(Protocol.WAR);
component.getServers().add(Protocol.HTTP, 8080);
component.getDefaultHost().attach(new Main());
component.start();
}Example 63
| Project: qi4j-sdk-master File: RestServerMixin.java View source code |
@Override
public void startServer() throws Exception {
component = new Component();
component.getServers().add(Protocol.HTTP, 8182);
RestApplication application = module.newObject(RestApplication.class, component.getContext());
component.getDefaultHost().attach(application);
component.start();
}Example 64
| Project: distributed_loadgen-master File: ClusterManager.java View source code |
public static void main(String args[]) {
ClusterManager.getManager();
try {
Component component = new Component();
component.getServers().add(Protocol.HTTP, 8182);
component.getDefaultHost().attach("/cluster", new ClusterRest());
component.start();
} catch (Exception e) {
}
}Example 65
| Project: jenkow-plugin-master File: BaseRestTestCase.java View source code |
protected void initializeRestServer() throws Exception {
component = new Component();
// Add a new HTTP server listening on port 8182.
component.getServers().add(Protocol.HTTP, 8182);
component.getDefaultHost().attach(new ActivitiRestApplication());
component.start();
}