Java Code Examples for org.restlet.data.Protocol

The following are top voted examples for showing how to use org.restlet.data.Protocol. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: spring-restlet   File: AbstractResourceTest.java   View source code 7 votes vote down vote up
@BeforeClass
public static void startServer() throws Exception {
	// Creating restlet component
	component = new Component();

	// The status service is disabled by default.
	component.getStatusService().setEnabled(false);

	component.getClients().add(Protocol.HTTP);
	component.getClients().add(Protocol.FILE);
	component.getClients().add(Protocol.WAR);
	component.getClients().add(Protocol.RIAP);

	component.getServers().add(Protocol.HTTP, portNumber);

	component.start();
}
 
Example 2
Project: spring-restlet   File: ShindigServer.java   View source code 7 votes vote down vote up
public static void main(String[] args) throws Exception {
    // Create a new Component.
    Component component = new Component();

    // Add a new HTTP server listening on port 8182.
    Server server = component.getServers().add(Protocol.HTTP, 8182);
    server.getContext().getParameters().add("useForwardedForHeader", "true");

    ShindigApplication application = new ShindigApplication(server.getContext());
    // Attach the sample application.
    component.getDefaultHost().attach("/shindig", application);

    server.getContext().getAttributes().put(Constants.CONTEXT_PATH_KEY, "/shindig");
    server.getContext().getAttributes().put(Constants.BASE_URL_KEY, "http://localhost:8182");

    // Start the component.
    component.start();

}
 
Example 3
Project: spring-restlet   File: Server.java   View source code 7 votes vote down vote up
public static void main(String[] args) throws Exception {
    // Create a new Component.
    Component component = new Component();

    // Add a new HTTP server listening on port 8182.
    org.restlet.Server server =  component.getServers().add(Protocol.HTTP, 8182);
    server.getContext().getParameters().add("useForwardedForHeader", "true");


    RestletSpringApplication application = new RestletSpringApplication();
    // Attach the sample application.
    component.getDefaultHost().attach( application);

    // Start the component.
    component.start();
}
 
Example 4
Project: unitimes   File: XEStudentEnrollment.java   View source code 6 votes vote down vote up
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();
	}
}
 
Example 5
Project: unitimes   File: DegreeWorksCourseRequests.java   View source code 6 votes vote down vote up
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();
	}
}
 
Example 6
Project: unitimes   File: DegreeWorksPlanScraper.java   View source code 6 votes vote down vote up
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();
	}
}
 
Example 7
Project: bigstreams   File: TestFileTrackerStatusResource.java   View source code 6 votes vote down vote up
@Test
public void testListPaging() throws Exception {
	Component component = new Component();
	component.getServers().add(Protocol.HTTP, port);
	component.getDefaultHost().attach(setupAppPaging());
	component.start();

	try {
		Client client = new Client(Protocol.HTTP);

		long count = getCount(client, "READY");
		assertEquals(pagingTotal, count);

		Collection<FileTrackingStatus> statusObjColl = getStatusObject(
				client, "READY", 0, 30);

		assertEquals(30, statusObjColl.size());
	} finally {
		component.stop();
	}

}
 
Example 8
Project: bigstreams   File: TestFileTrackerStatusPathResource.java   View source code 6 votes vote down vote up
@Test
public void testGetsStatus() throws Exception {
	Component component = new Component();
	component.getServers().add(Protocol.HTTP, port);
	component.getDefaultHost().attach(setupApp());
	component.start();

	try {
		Client client = new Client(Protocol.HTTP);
		
		for(File file: Arrays.asList(new File("test1.txt"), new File("test2.txt"), new File("test3.txt"))){
		
			FileTrackingStatus status = getStatusObject(client, file.getAbsolutePath());
			
			assertNotNull(status);
			assertEquals(file.getAbsolutePath(), status.getPath());
			
		}
		
	} finally {
		component.stop();
	}

}
 
Example 9
Project: sync-android-p2p   File: Application.java   View source code 6 votes vote down vote up
public static void main(String[] args) throws Exception {
	
	final int port = 8182;

    createDevelopmentDatabase();

    // Set up a Restlet service
    final Router router = new Router();
    router.attachDefault(HttpListener.class);

    org.restlet.Application myApp = new org.restlet.Application() {
        @Override
        public org.restlet.Restlet createInboundRoot() {
        	Context ctx = getContext();
ctx.getParameters().add("databaseDir", databaseDir);
ctx.getParameters().add("port", Integer.toString(port));
router.setContext(ctx);
            return router;
        };
    };
    Component component = new Component();
    component.getDefaultHost().attach("/", myApp);

    new Server(Protocol.HTTP, port, component).start();
}
 
Example 10
Project: polygene-java   File: Main.java   View source code 6 votes vote down vote up
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();
}
 
Example 11
Project: ocnrm   File: OcnRMServ.java   View source code 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    logger.info("main() Start");

    if (args.length == 0) {
        loadProperties("");
    } else {
        loadProperties(args[0]);
    }

    Component component = new Component();
    component.getServers().add(Protocol.HTTP, SERVER_PORT);
    component.getDefaultHost().attach(SERVER_PATH, new RMrouterApplication());
    component.start();

    logger.info("main() End");
}
 
Example 12
Project: ocnrm   File: OcnRMServTest.java   View source code 6 votes vote down vote up
@Before
public void setUp() throws Exception {
    component = PowerMockito.mock(Component.class, RETURNS_DEEP_STUBS);

    ServerList list = PowerMockito.mock(ServerList.class);
    PowerMockito.doReturn(list).when(component).getServers();
    PowerMockito.doReturn(mock(Server.class)).when(list).add(any(Protocol.class), anyInt());

    VirtualHost host = PowerMockito.mock(VirtualHost.class);
    PowerMockito.doReturn(host).when(component).getDefaultHost();
    PowerMockito.doReturn(mock(TemplateRoute.class))
            .when(host).attach(anyString(), any(RMrouterApplication.class));

    PowerMockito.doNothing().when(component).start();

    PowerMockito.whenNew(Component.class).withNoArguments().thenReturn(component);

    OdenOsPropertyLoader loader = PowerMockito.spy(OdenOsPropertyLoader.getInstance());
    Whitebox.setInternalState(OcnRMServ.class, "loader", loader);

    dummyLogger = mock(Logger.class);
    Whitebox.setInternalState(OcnRMServ.class, "logger", dummyLogger);
}
 
Example 13
Project: cyclops-udr   File: CloudStackDownloader.java   View source code 6 votes vote down vote up
/**
 * Pulls data from CloudStack API
 *
 * @return JSON string
 * @throws IOException
 */
private String pullData() throws IOException {
    logger.trace("Starting to pull data from provided URL");

    // create connection
    Client client = new Client(Protocol.HTTP);
    ClientResource cr = new ClientResource(url);
    Request req = cr.getRequest();

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

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

    logger.trace("Successfully pulled data from provided URL");

    // and return response data
    return output.getText();
}
 
Example 14
Project: prudence   File: PrudenceRouter.java   View source code 6 votes vote down vote up
@Override
public void handle( Request request, Response response )
{
	// RIAP ignores hide
	if( request.getProtocol() != Protocol.RIAP )
	{
		String remainingPart = request.getResourceRef().getRemainingPart();
		for( Template hiddenUriTemplate : hiddenUriTemplates )
		{
			if( hiddenUriTemplate.match( remainingPart ) != -1 )
			{
				response.setStatus( Status.CLIENT_ERROR_NOT_FOUND );
				return;
			}
		}
	}

	super.handle( request, response );
}
 
Example 15
Project: z_sync-android-p2p-example.deprecated   File: MainActivity.java   View source code 6 votes vote down vote up
@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 16
Project: MCRest   File: ServerStatusTest.java   View source code 6 votes vote down vote up
@Before
public void setUp() {
    ServerManager.getInstance().setServer(new StubMCServer());
    component = new Component();
    client =  new Client(Protocol.HTTP);
    // Add a new HTTP server listening on port 8182.
    component.getServers().add(Protocol.HTTP, port);
    // Attach the sample application.
    component.getDefaultHost().attach("/mcrest", new RestApplication());
    try {
        component.start();
    } catch (Exception e) {
        e.printStackTrace();
    }
    serverUrl = "http://127.0.0.1:"+port+"/mcrest";
}
 
Example 17
Project: MCRest   File: AuthResourceTest.java   View source code 6 votes vote down vote up
@Test
public void authDisableTest(){
    AuthPara auth = new AuthPara(USER,PASSWORD,false);
    Component component = new Component();
    component.getServers().add(Protocol.HTTP, port);
    component.getDefaultHost().attach("/mcrest", new RestApplication(auth));
    try {
        component.start();
    } catch (Exception e) {
        e.printStackTrace();
        Assert.fail();
    }
    String responseString = getRequestResult("/").getEntityAsText();
    Assert.assertTrue(responseString.contains("MCStub"));
    String worldResult = getRequestResult("/world").getEntityAsText();
    Assert.assertTrue(worldResult.contains("testWorld"));
}
 
Example 18
Project: MCRest   File: AuthResourceTest.java   View source code 6 votes vote down vote up
@Test
public void authEnableAllResource(){
    AuthPara auth = new AuthPara(USER,PASSWORD,genAllResoureceList(),true);
    component = new Component();
    component.getServers().add(Protocol.HTTP, port);
    component.getDefaultHost().attach("/mcrest", new RestApplication(auth));
    try {
        component.start();
    } catch (Exception e) {
        e.printStackTrace();
        Assert.fail();
    }
    int statusCode = getRequestResult("/").getStatus().getCode();
    Assert.assertEquals(statusCode, 401);
    statusCode = getRequestResult("/player").getStatus().getCode();
    Assert.assertEquals(statusCode, 401);
    statusCode = getRequestResult("/world").getStatus().getCode();
    Assert.assertEquals(statusCode, 401);
}
 
Example 19
Project: microservices-comparison   File: RemoteCarService.java   View source code 6 votes vote down vote up
@Override
public List<Car> list() {
    Client client = new Client(new Context(), Protocol.HTTPS);
    Series<Parameter> parameters = client.getContext().getParameters();
    parameters.add("truststorePath", System.getProperty("javax.net.ssl.trustStore"));

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

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

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

    // return null or received text
    return (output == null) ? "" : output.getText();
}
 
Example 21
Project: cyclops-rc   File: TNovaPuller.java   View source code 6 votes vote down vote up
/**
 * Pull data from provided URL
 * @param url
 * @return output string or empty string
 */
private String pullData(String url) throws IOException {
    Client client = new Client(Protocol.HTTP);
    ClientResource cr = new ClientResource(url);
    Request req = cr.getRequest();

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

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

    // return null or received text
    return (output == null) ? "" : output.getText();
}
 
Example 22
Project: cyclops-rc   File: AccountingClient.java   View source code 6 votes vote down vote up
/**
 * Pull data from provided URL
 *
 * @param url
 * @return output string
 */
private String pullData(String url) throws IOException {
    Client client = new Client(Protocol.HTTP);
    ClientResource cr = new ClientResource(url);
    Request req = cr.getRequest();

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

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

    // and return response data
    return output.getText();
}
 
Example 23
Project: pseudoMF   File: PseudoMfMain.java   View source code 6 votes vote down vote up
public static void main(String[] args) throws Exception {

        logger.debug("main() Start");

        // プロパティファイル呼び出し
        if (args.length == 0) {
            loadProperties(null);
        } else {
            loadProperties(args[0]);
        }

        Component component = new Component();
        component.getServers().add(Protocol.HTTP, loader.getServicePort());
        component.getDefaultHost().attach(loader.getCommonPath(), new PseudoMfRouter());
        component.getDefaultHost().attach("/ui/", new PseudoMfGuiRouter());
        component.getContext().getParameters().add("maxThreads", "10");
        component.start();

        logger.debug("CurrentDir:{}", System.getProperty("user.dir"));

        logger.info("## dummyMC GUI URI: http://<HOST>:{}/ui/index.html", loader.getServicePort());
        logger.debug("main() End");
    }
 
Example 24
Project: unitime   File: XEStudentEnrollment.java   View source code 6 votes vote down vote up
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();
	}
}
 
Example 25
Project: unitime   File: DegreeWorksCourseRequests.java   View source code 6 votes vote down vote up
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();
	}
}
 
Example 26
Project: unitime   File: DegreeWorksPlanScraper.java   View source code 6 votes vote down vote up
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();
	}
}
 
Example 27
Project: leanbean   File: LeanBeanApplication.java   View source code 6 votes vote down vote up
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 LeanBeanApplication());

    // Start the component.
    component.start();
  } catch (Exception e) {
    // Something is wrong.
    e.printStackTrace();
  }
}
 
Example 28
Project: LicenseRecognition   File: LRSystemComponent.java   View source code 6 votes vote down vote up
/**
 * Constructor.
 * 
 * @throws Exception
 */
public LRSystemComponent() throws Exception {
	// Set basic properties
	setName("License Recognition Server");
	setDescription("License Recognition");
	setOwner("Software college");
	setAuthor("Justin Yang");

	// Add connectors
	getClients().add(new Client(Protocol.CLAP));
	getClients().add(new Client(Protocol.FILE));

	Server server = new Server(new Context(), Protocol.HTTP, 8183);
	
	// Tracing
	getServers().add(server);

	LRSystemApplication app = new LRSystemApplication();
	
	// Configure the default virtual host
	VirtualHost host = getDefaultHost();

	// Attach the application to the default virtual host
	host.attachDefault(app);
}
 
Example 29
Project: helix   File: AdminTestBase.java   View source code 6 votes vote down vote up
@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_CONNECTION_TIMEOUT,
          ZkClient.DEFAULT_SESSION_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);
}
 
Example 30
Project: xproclet   File: ConfigurationTest.java   View source code 6 votes vote down vote up
@Test
public void testLoad() {
   for (int i=0; i<tests.length; i++) {
      Configuration conf = new Configuration();
      try {
         URI uri = getClass().getResource(tests[i]).toURI();
         LOG.info("Loading: "+uri);
         conf.load(uri);
         for (Protocol client : conf.getClients()) {
            LOG.info("Client: "+client);
         }
         for (Server server : conf.getServers()) {
            LOG.info("Server: "+server.getProtocol()+" at "+server.getAddress()+":"+server.getPort());
            for (Host host : server.getHosts().values()) {
               LOG.info("Host: "+host.getName());
               Context context = new Context();
               Router router = new Router(context);
               host.attach(router);
            }
         }
      } catch (Exception ex) {
         ex.printStackTrace();
         org.junit.Assert.fail();
      }
   }
}
 
Example 31
Project: spring-open   File: TestRestApiServer.java   View source code 6 votes vote down vote up
/**
 * 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) {
        //  Web server did not start.
        throw new IllegalStateException(e);
    }
}
 
Example 32
Project: spring-restlet   File: SpringComponent.java   View source code 6 votes vote down vote up
/**
 * Sets the list of clients, either as protocol names, Protocol instances or
 * Client instances.
 *
 * @param clients
 *            The list of clients.
 */
public synchronized void setClientsList(List<Object> clients) {
    for (final Object client : clients) {
        if (client instanceof String) {
            getClients().add(Protocol.valueOf((String) client));
        } else if (client instanceof Protocol) {
            getClients().add((Protocol) client);
        } else if (client instanceof Client) {
            getClients().add((Client) client);
        } else {
            getLogger()
                    .warning(
                            "Unknown object found in the clients list. Only instances of String, org.restlet.data.Protocol and org.restlet.Client are allowed.");
        }
    }
}
 
Example 33
Project: spring-restlet   File: RestletSpringApplication.java   View source code 6 votes vote down vote up
/**
 * Called when the app root needs to be created. Override it if you need
 * "old way" to attach resources, or need to use the isStarted flag.
 * 
 * @param root
 * @param isStarted
 */
protected void doCreateRoot(Router root, boolean isStarted) {
	if (!isStarted) {
		return;
	}
	// publish the WAR contents
	Directory rootDir = new WebAppDirectory(getContext(), "war:///");
	rootDir.setListingAllowed(false);
	rootDir.setModifiable(false);
	rootDir.setNegotiatingContent(true);

	attach(root, false, "/", rootDir);
	root.attach(FileServerResource.RESOURCE_PATH, FileServerResource.class, Template.MODE_STARTS_WITH);

	this.getConnectorService().setClientProtocols(
			Arrays.asList(Protocol.HTTP, Protocol.FILE, Protocol.WAR, Protocol.RIAP));
}
 
Example 34
Project: Xponents   File: XlayerServer.java   View source code 6 votes vote down vote up
public XlayerServer(int port) throws IOException {
    /* customize app before attaching */
    Context ctx = new Context();

    /*
     * If we had settings,...
     */
    Map<String, Object> settings = new HashMap<>();
    ctx.setAttributes(settings);
    XlayerRestlet service = new XlayerRestlet(ctx);
    /* 
     * Configure ports, protocols, security
     */
    getServers().add(Protocol.HTTP, port);

    /*
     * Configure URLs, endpoints.
     */
    getDefaultHost().attach("/xlayer/rest", service);
    this.getContext().setAttributes(settings);
}
 
Example 35
Project: AGDISTIS   File: RunApp.java   View source code 6 votes vote down vote up
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();
	}
}
 
Example 36
Project: restlet-jetty9   File: JettyClientCall.java   View source code 6 votes vote down vote up
/**
 * Constructor.
 * 
 * @param helper
 *        The parent HTTP client helper.
 * @param method
 *        The method name.
 * @param requestUri
 *        The request URI.
 * @throws IOException
 *         In case of an I/O error
 */
public JettyClientCall( JettyHttpClientHelper helper, final String method, final String requestUri ) throws IOException
{
	super( helper, method, requestUri );
	clientHelper = helper;

	if( requestUri.startsWith( "http:" ) || requestUri.startsWith( "https:" ) )
	{
		httpRequest = (HttpRequest) helper.getHttpClient().newRequest( requestUri );
		httpRequest.method( method );

		setConfidential( httpRequest.getURI().getScheme().equalsIgnoreCase( Protocol.HTTPS.getSchemeName() ) );
	}
	else
	{
		throw new IllegalArgumentException( "Only HTTP or HTTPS resource URIs are allowed here" );
	}
}
 
Example 37
Project: CadalWorkspace   File: RestletApplication.java   View source code 6 votes vote down vote up
public static void main(String[] args) {
    Server server = new Server(Protocol.HTTP, port, new RestletApplication());
    System.out.println("Start catalog search REST Server...");
    try {
        server.start();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 38
Project: freedomotic   File: FreedomRestServer.java   View source code 6 votes vote down vote up
public static void main(String[] args) throws Exception {
       
        Component 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, 8111);                     
        component.getServers().add(server);
        server.getContext().getParameters().add("maxTotalConnections", "50");
        //end TODO
        Engine.getInstance().getRegisteredServers().clear();
        Engine.getInstance().getRegisteredServers().add(new HttpServerHelper(server)); 
        component.getClients().add(Protocol.FILE);                
        component.getDefaultHost().attach(new FreedomRestServer());
        component.start();
}
 
Example 39
Project: SlipStreamServer   File: Main.java   View source code 6 votes vote down vote up
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 40
Project: open-rmbt   File: RestService.java   View source code 5 votes vote down vote up
@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);
			}  
		}
	}
}