org.rapidoid.http.Req Java Examples

The following examples show how to use org.rapidoid.http.Req. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: JolokiaController.java    From apollo with Apache License 2.0 6 votes vote down vote up
private void genericJolokiaProxy(int environmentId, String podName, String path, Req req) {
    Environment environment = environmentDao.getEnvironment(environmentId);

    if (environment == null) {
        ControllerCommon.assignJsonResponseToReq(req, HttpStatus.BAD_REQUEST, "Environment " + environmentId + " does not exists");
        return;
    }

    Optional<Response> response = kubernetesHandlerStore.getOrCreateKubernetesHandler(environment).proxyJolokia(podName, path, req);

    if (response.isPresent()) {
        try (ResponseBody body = response.get().body()) {
            ControllerCommon.assignJsonBytesToReq(req, response.get().code(), body.bytes());
        } catch (IOException e) {
            ControllerCommon.assignJsonResponseToReq(req, HttpStatus.INTERNAL_SERVER_ERROR, "Could not read response from jolokia");
        }
    } else {
        ControllerCommon.assignJsonResponseToReq(req, HttpStatus.BAD_REQUEST, "Could not find jolokia");
    }
}
 
Example #2
Source File: StatusController.java    From apollo with Apache License 2.0 6 votes vote down vote up
@LoggedIn
@GET("/status/environment/{environmentId}/service/{serviceId}/latestpod")
public String getLatestPodName(int environmentId, int serviceId, Req req) {
    Environment environment = environmentDao.getEnvironment(environmentId);
    Service service = serviceDao.getService(serviceId);

    if (service.getIsPartOfGroup()) {
        ControllerCommon.assignJsonResponseToReq(req, HttpStatus.NOT_ACCEPTABLE, "Missing group ID for service " + service.getId());
        return "";
    }

    KubernetesHandler kubernetesHandler = kubernetesHandlerStore.getOrCreateKubernetesHandler(environment);

    Optional<String> serviceLatestCreatedPodName = kubernetesHandler.getServiceLatestCreatedPodName(service);
    if (serviceLatestCreatedPodName.isPresent()) {
        return serviceLatestCreatedPodName.get();
    } else {
        ControllerCommon.assignJsonResponseToReq(req, HttpStatus.NOT_FOUND, "Can't find pod");
        return "";
    }
}
 
Example #3
Source File: StatusController.java    From apollo with Apache License 2.0 6 votes vote down vote up
@LoggedIn
@GET("/status/environment/{environmentId}/service/{serviceId}/group/{groupName}/latestpod")
public String getLatestPodName(int environmentId, int serviceId, String groupName, Req req) {
    Environment environment = environmentDao.getEnvironment(environmentId);
    Service service = serviceDao.getService(serviceId);

    if (!service.getIsPartOfGroup()) {
        ControllerCommon.assignJsonResponseToReq(req, HttpStatus.NOT_ACCEPTABLE, "Service " + service.getId() + " can't have group ID");
        return "";
    }

    KubernetesHandler kubernetesHandler = kubernetesHandlerStore.getOrCreateKubernetesHandler(environment);

    Optional<String> serviceLatestCreatedPodName = kubernetesHandler.getServiceLatestCreatedPodName(service, Optional.of(groupName));
    if (serviceLatestCreatedPodName.isPresent()) {
        return serviceLatestCreatedPodName.get();
    } else {
        ControllerCommon.assignJsonResponseToReq(req, HttpStatus.NOT_FOUND, "Can't find pod");
        return "";
    }
}
 
Example #4
Source File: DefaultPageDecorator.java    From rapidoid with Apache License 2.0 6 votes vote down vote up
@Override
public void renderPage(Req req, String content, OutputStream out) {
	U.notNull(content, "page content");

	Resp resp = req.response();

	if (isFullPage(req, content)) {
		WritableUtils.writeUTF8(new WritableOutputStream(out), content);
		return;
	}

	Screen screen = resp.screen();
	screen.content(GUI.hardcoded(content));

	screen.render(out);
}
 
Example #5
Source File: DeployableVersionController.java    From apollo with Apache License 2.0 6 votes vote down vote up
@LoggedIn
@GET("/deployable-version/latest/branch/{branchName}/repofrom/{deployableVersionId}")
public DeployableVersion getLatestDeployableVersionOnBranchBasedOnOtherDeployableVersion(String branchName, int deployableVersionId, Req req) {
    DeployableVersion referenceDeployableVersion = deployableVersionDao.getDeployableVersion(deployableVersionId);
    String actualRepo = getRepoNameFromRepositoryUrl(referenceDeployableVersion.getGithubRepositoryUrl());

    Optional<String> latestSha = githubConnector.getLatestCommitShaOnBranch(actualRepo, branchName);

    if (!latestSha.isPresent()) {
        assignJsonResponseToReq(req, HttpStatus.BAD_REQUEST, "Did not found latest commit on that branch");
        throw new RuntimeException();
    }

    DeployableVersion deployableVersionFromSha = deployableVersionDao.getDeployableVersionFromSha(latestSha.get(),
            referenceDeployableVersion.getServiceId());

    if (deployableVersionFromSha == null) {
        assignJsonResponseToReq(req, HttpStatus.BAD_REQUEST, "Did not found deployable version matching the sha " + latestSha);
        throw new RuntimeException();
    } else {
        return deployableVersionFromSha;
    }
}
 
Example #6
Source File: HttpAuthWrapper.java    From rapidoid with Apache License 2.0 6 votes vote down vote up
@Override
public Object wrap(final Req req, final HandlerInvocation invocation) throws Exception {
	TokenAuthData auth = HttpUtils.getAuth(req);

	String username = auth != null ? auth.user : null;

	if (U.isEmpty(username)) {
		HttpUtils.clearUserData(req);
	}

	Set<String> roles = userRoles(req, username);
	Set<String> scope = auth != null ? auth.scope : null;

	if (U.notEmpty(requiredRoles) && !Secure.hasAnyRole(username, roles, requiredRoles)) {
		throw new SecurityException("The user doesn't have the required roles!");
	}

	Ctx ctx = Ctxs.required();
	ctx.setUser(new UserInfo(username, roles, scope));

	return invocation.invoke();
}
 
Example #7
Source File: EnvironmentController.java    From apollo with Apache License 2.0 6 votes vote down vote up
@LoggedIn
@POST("/environment")
public void addEnvironment(String name, String geoRegion, String availability, String kubernetesMaster,
                           String kubernetesToken, String kubernetesCaCert, String kubernetesNamespace, Integer servicePortCoefficient,
                           Boolean requireDeploymentMessage, Boolean requireHealthCheck, Integer concurrencyLimit,
                           String additionalParams, Boolean isActive, Req req) {
    Environment newEnvironment = new Environment();
    newEnvironment.setName(name);
    newEnvironment.setGeoRegion(geoRegion);
    newEnvironment.setAvailability(availability);
    newEnvironment.setKubernetesMaster(kubernetesMaster);
    newEnvironment.setKubernetesToken(kubernetesToken);
    newEnvironment.setKubernetesCaCert(kubernetesCaCert);
    newEnvironment.setKubernetesNamespace(kubernetesNamespace);
    newEnvironment.setServicePortCoefficient(servicePortCoefficient);
    newEnvironment.setRequireDeploymentMessage(requireDeploymentMessage);
    newEnvironment.setRequireHealthCheck(requireHealthCheck);
    newEnvironment.setConcurrencyLimit(concurrencyLimit);
    newEnvironment.setAdditionalParams(additionalParams);
    newEnvironment.setIsActive(isActive);

    environmentDao.addEnvironment(newEnvironment);
    assignJsonResponseToReq(req, HttpStatus.CREATED, newEnvironment);
}
 
Example #8
Source File: ServiceController.java    From apollo with Apache License 2.0 6 votes vote down vote up
@LoggedIn
@PUT("/service/{id}")
public void updateService(int id, String name, String deploymentYaml, String serviceYaml, String ingressYaml, Boolean isPartOfGroup, Req req) {
    Service service = serviceDao.getService(id);

    if (service == null) {
        Map<String, String> message = ImmutableMap.of("message", "Service not found");
        assignJsonResponseToReq(req, HttpStatus.NOT_FOUND, message);
        return;
    }

    service.setName(name);
    service.setDeploymentYaml(deploymentYaml);
    service.setServiceYaml(serviceYaml);
    service.setIngressYaml(ingressYaml);
    service.setIsPartOfGroup(isPartOfGroup);

    serviceDao.updateService(service);
    assignJsonResponseToReq(req, HttpStatus.OK, service);
}
 
Example #9
Source File: BeanParamRetriever.java    From rapidoid with Apache License 2.0 6 votes vote down vote up
@Override
public Object getParamValue(Req req) {
	Object bean;

	try {
		bean = customization.beanParameterFactory().getParamValue(req, type, name, req.data());
	} catch (Exception e) {
		throw U.rte(e);
	}

	if (validate) {
		customization.validator().validate(req, bean);
	}

	return bean;
}
 
Example #10
Source File: HealthController.java    From apollo with Apache License 2.0 6 votes vote down vote up
@GET("/health")
public void getHealth(Req req) {
    Set<Integer> scopedEnvironments = slaveService.getScopedEnvironments();
    Map<Integer, Boolean> environmentsHealthMap = kubernetesHealth.getEnvironmentsHealthMap();

    Map<Integer, Boolean> scopedEnvironmentsHealthMap = new HashMap<>(environmentsHealthMap);

    environmentsHealthMap.keySet()
                         .stream()
                         .filter(envId -> !scopedEnvironments.contains(envId))
                         .forEach(scopedEnvironmentsHealthMap::remove);

    if (scopedEnvironmentsHealthMap.containsValue(false)) {
        scopedEnvironmentsHealthMap.entrySet()
                             .stream()
                             .filter(environment -> !environment.getValue())
                             .forEach(environment -> {
                                 MDC.put("environmentId", String.valueOf(environment.getKey()));
                                 MDC.put("environmentName", String.valueOf(environmentDao.getEnvironment(environment.getKey()).getName()));
                                 logger.error("Unhealthy environment, environmentId: {}, environmentName: {}.", environment.getKey(), environmentDao.getEnvironment(environment.getKey()).getName());
                             });
        assignJsonResponseToReq(req, HttpStatus.INTERNAL_SERVER_ERROR, scopedEnvironmentsHealthMap);
    } else {
        assignJsonResponseToReq(req, HttpStatus.OK, scopedEnvironmentsHealthMap);
    }
}
 
Example #11
Source File: KubernetesActionsController.java    From apollo with Apache License 2.0 6 votes vote down vote up
@LoggedIn
@POST("/k8s/pod/restart")
public void restartPod(int environmentId, String podName, Req req) {
    Environment environment = environmentDao.getEnvironment(environmentId);

    if (environment == null) {
        ControllerCommon.assignJsonResponseToReq(req, HttpStatus.BAD_REQUEST, "Environment " + environmentId + " does not exists");
        return;
    }

    try {
        kubernetesHandlerStore.getOrCreateKubernetesHandler(environment).restartPod(podName);
    } catch (ApolloKubernetesException e) {
        ControllerCommon.assignJsonResponseToReq(req, HttpStatus.INTERNAL_SERVER_ERROR, e.getMessage());
        return;
    }
    ControllerCommon.assignJsonResponseToReq(req, HttpStatus.OK, "Ok");
}
 
Example #12
Source File: GroupController.java    From apollo with Apache License 2.0 6 votes vote down vote up
@LoggedIn
@PUT("/group/{id}")
public void updateGroup(int id, String name, int serviceId, int environmentId, int scalingFactor, String jsonParams, Req req) {
    Group group = groupDao.getGroup(id);

    if (group == null) {
        Map<String, String> message = ImmutableMap.of("message", "Group not found");
        assignJsonResponseToReq(req, HttpStatus.NOT_FOUND, message);
        return;
    }

    group.setName(name);
    group.setServiceId(serviceId);
    group.setEnvironmentId(environmentId);
    group.setScalingFactor(scalingFactor);
    group.setJsonParams(jsonParams);

    groupDao.updateGroup(group);
    assignJsonResponseToReq(req, HttpStatus.OK, group);
}
 
Example #13
Source File: ScalingController.java    From apollo with Apache License 2.0 6 votes vote down vote up
@LoggedIn
@PUT("/scaling/{groupId}")
public void updateScalingFactor(int groupId, int scalingFactor, Req req) {
    Group group = groupDao.getGroup(groupId);

    if (group == null) {
        assignJsonResponseToReq(req, HttpStatus.NOT_FOUND, groupId);
        return;
    }

    if (group.getScalingStatus() == Group.ScalingStatus.BLOCKED) {
        assignJsonResponseToReq(req, HttpStatus.FORBIDDEN, groupId);
        return;
    }

    group.setScalingFactor(scalingFactor);
    group.setScalingStatus(Group.ScalingStatus.PENDING);
    groupDao.updateGroup(group);

    assignJsonResponseToReq(req, HttpStatus.OK, group);
}
 
Example #14
Source File: EnvironmentsStackController.java    From apollo with Apache License 2.0 5 votes vote down vote up
@LoggedIn
@Transactional
@POST("/environments-stack")
public void addEnvironmentsStack(String name, boolean isEnabled, String environmentsCsv, Req req) {
    List<Integer> environmentsIds = StringParser.splitCsvToIntegerList(environmentsCsv);
    EnvironmentsStack environmentsStack = new EnvironmentsStack(name, isEnabled);
    stackDao.addStack(environmentsStack);
    if (environmentsIds.size() > 0) {
        environmentsStackDao.addEnvironmentsToStack(environmentsIds, environmentsStack.getId());
    }
    assignJsonResponseToReq(req, HttpStatus.CREATED, getEnvironmentsStack(environmentsStack.getId()));
}
 
Example #15
Source File: GroupController.java    From apollo with Apache License 2.0 5 votes vote down vote up
@LoggedIn
@POST("/group")
public void addGroup(String name, int serviceId, int environmentId, int scalingFactor, String jsonParams, Req req) {

    Group newGroup = new Group();

    newGroup.setName(name);
    newGroup.setServiceId(serviceId);
    newGroup.setEnvironmentId(environmentId);
    newGroup.setScalingFactor(scalingFactor);
    newGroup.setJsonParams(jsonParams);

    groupDao.addGroup(newGroup);
    assignJsonResponseToReq(req, HttpStatus.CREATED, newGroup);
}
 
Example #16
Source File: LambdaHandlerTest.java    From rapidoid with Apache License 2.0 5 votes vote down vote up
@Test
public void testLambdaHandlerWithAnonymousClass() {
	TwoParamLambda<Resp, Req, Integer> oneParamLambda = new TwoParamLambda<Resp, Req, Integer>() {
		@Override
		public Resp execute(Req param, Integer x) {
			return param.response().result("x=" + x);
		}
	};

	On.get("/test").json(oneParamLambda);

	onlyGet("/test?x=123");
}
 
Example #17
Source File: Main.java    From rapidoid with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {

		/* The handler for [/msg] returns the model */
		/* The default view name is [msg] */
		/* So the corresponding template is [templates/msg.html] */

		On.page("/msg").mvc(() -> U.map("count", 12, "oki", GUI.btn("OK")));

		/* A custom view name can be assigned. */
		/* In this case the default view name is [abc], */
		/* but a custom view name [msg] was specified */

		On.get("/abc").view("msg").mvc((Req req, Resp resp) -> U.map("count", 100, "oki", ""));
	}
 
Example #18
Source File: AbstractHttpHandlerDecorator.java    From rapidoid with Apache License 2.0 5 votes vote down vote up
Object handleReqAndPostProcess(Channel ctx, boolean isKeepAlive, Req req) {
	Object result;

	try {
		result = handler.handleReq(ctx, isKeepAlive, req);

	} catch (Throwable e) {
		result = e;
	}

	return HandlerResultProcessor.INSTANCE.postProcessResult(req, result);
}
 
Example #19
Source File: BlockerDefinitionController.java    From apollo with Apache License 2.0 5 votes vote down vote up
@Administrator
@DELETE("/blocker-definition/{id}")
public void deleteBlockerDefinition(int id, Req req) {
    String userEmail = req.token().get("_user").toString();
    logger.info("User: {} has just deleted blocker, id:{}", userEmail, id);

    blockerDefinitionDao.deleteBlockerDefinition(id);
    assignJsonResponseToReq(req, HttpStatus.OK, "deleted");
}
 
Example #20
Source File: AuthController.java    From apollo with Apache License 2.0 5 votes vote down vote up
@Administrator
@POST("/deployment-roles")
public void addDeploymentRole(String name, Req req) {
    DeploymentRole newDeploymentRole = new DeploymentRole();
    newDeploymentRole.setName(name);

    deploymentRoleDao.addDeploymentRole(newDeploymentRole);
    assignJsonResponseToReq(req, HttpStatus.CREATED, newDeploymentRole);
}
 
Example #21
Source File: MethodReqHandler.java    From rapidoid with Apache License 2.0 5 votes vote down vote up
@Override
protected Object handleReq(Channel channel, boolean isKeepAlive, Req req) throws Throwable {
	Object[] args = args(req);

	Object result = Cls.invokeRethrowing(method, instance, args);

	if (method.getReturnType() == void.class) {
		U.must(result == null);
		result = req;
	}

	return result;
}
 
Example #22
Source File: LambdaParamNamesTest.java    From rapidoid with Apache License 2.0 5 votes vote down vote up
@Test
public void testHandlerLambdaParams() {
	int a = 100;
	int b = 200;

	On.get("/").json((Req req, Integer x, Resp resp) -> U.join(":", a, b, x));

	onlyGet("/?x=10&b=33");
}
 
Example #23
Source File: ServicesStackController.java    From apollo with Apache License 2.0 5 votes vote down vote up
@LoggedIn
@Transactional
@POST("/services-stack/service")
public void addServiceToStack(int serviceId, int stackId, Req req) {
    if (serviceDao.getService(serviceId).getIsPartOfGroup()) {
        assignJsonResponseToReq(req, HttpStatus.BAD_REQUEST, "Can't add to stack service that is part of a group");
        return;
    }
    servicesStackDao.addServiceToStack(serviceId, stackId);
    assignJsonResponseToReq(req, HttpStatus.CREATED, getServicesStack(stackId));
}
 
Example #24
Source File: RoundRobinLoadBalancer.java    From rapidoid with Apache License 2.0 5 votes vote down vote up
@Override
public ProxyUpstream pickUpstream(Req req, List<ProxyUpstream> candidates) {
	long n = counter.getAndIncrement();

	int index = (int) (n % candidates.size());

	return candidates.get(index);
}
 
Example #25
Source File: ServiceController.java    From apollo with Apache License 2.0 5 votes vote down vote up
@LoggedIn
@POST("/service")
public void addService(String name, String deploymentYaml, String serviceYaml, String ingressYaml, Boolean isPartOfGroup, Req req) {
    Service newService = new Service();

    newService.setName(name);
    newService.setDeploymentYaml(deploymentYaml);
    newService.setServiceYaml(serviceYaml);
    newService.setIngressYaml(ingressYaml);
    newService.setIsPartOfGroup(isPartOfGroup);

    serviceDao.addService(newService);
    assignJsonResponseToReq(req, HttpStatus.CREATED, newService);
}
 
Example #26
Source File: EnvironmentController.java    From apollo with Apache License 2.0 5 votes vote down vote up
@LoggedIn
@Administrator
@PUT("/environment")
public void editEnvironment(Integer id, String name, String geoRegion, String availability, String kubernetesMaster,
                            String kubernetesToken, String kubernetesCaCert, String kubernetesNamespace, Integer servicePortCoefficient,
                            Boolean requireDeploymentMessage, Boolean requireHealthCheck, Integer concurrencyLimit,
                            String additionalParams, Boolean isActive, Req req) {
    Environment environment = environmentDao.getEnvironment(id);

    if (environment == null) {
        Map<String, String> message = ImmutableMap.of("message", "Environment not found");
        assignJsonResponseToReq(req, HttpStatus.NOT_FOUND, message);
        return;
    }

    environment.setName(name);
    environment.setGeoRegion(geoRegion);
    environment.setAvailability(availability);
    environment.setKubernetesMaster(kubernetesMaster);
    environment.setKubernetesToken(kubernetesToken);
    environment.setKubernetesCaCert(kubernetesCaCert);
    environment.setKubernetesNamespace(kubernetesNamespace);
    environment.setServicePortCoefficient(servicePortCoefficient);
    environment.setRequireDeploymentMessage(requireDeploymentMessage);
    environment.setRequireHealthCheck(requireHealthCheck);
    environment.setConcurrencyLimit(concurrencyLimit);
    environment.setAdditionalParams(additionalParams);
    environment.setIsActive(isActive);

    environmentDao.updateEnvironment(environment);
    Environment updatedEnvironment = maskCredentials(environment);
    assignJsonResponseToReq(req, HttpStatus.OK, updatedEnvironment);
}
 
Example #27
Source File: Customization.java    From rapidoid with Apache License 2.0 5 votes vote down vote up
private static boolean inValidContext(Req req) {
	Ctx ctx = Ctxs.get();
	Req ctxReq = ctx != null ? (Req) ctx.exchange() : null;

	U.must(ctx == null || !ctx.isClosed(), "The context for request (%s) is closed!");
	U.must(req == ctxReq, "The customization request (%s) doesn't match the context request (%s)!", req, ctxReq);

	return true;
}
 
Example #28
Source File: StaticResourcesHandler.java    From rapidoid with Apache License 2.0 5 votes vote down vote up
@Override
public HttpStatus handle(Channel ctx, boolean isKeepAlive, Req req) {

	if (!HttpUtils.isGetReq(req)) return HttpStatus.NOT_FOUND;

	try {
		String[] staticFilesLocations = customization.staticFilesPath();
		if (!U.isEmpty(staticFilesLocations)) {

			Res res = HttpUtils.staticResource(req, staticFilesLocations);
			if (res != null) {

				StaticFilesSecurity staticFilesSecurity = customization.staticFilesSecurity();

				if (staticFilesSecurity.canServe(req, res)) {
					byte[] bytes = res.getBytesOrNull();

					if (bytes != null) {
						MediaType contentType = U.or(MediaType.getByFileName(res.getName()), MediaType.BINARY);
						HttpIO.INSTANCE.write200(HttpUtils.maybe(req), ctx, isKeepAlive, contentType, bytes);
						return HttpStatus.DONE;
					}
				}
			}
		}

		return HttpStatus.NOT_FOUND;

	} catch (Exception e) {
		return HttpIO.INSTANCE.errorAndDone(req, e, LogLevel.ERROR);
	}
}
 
Example #29
Source File: HttpAuthWrapper.java    From rapidoid with Apache License 2.0 5 votes vote down vote up
private Set<String> userRoles(Req req, String username) {
	if (username != null) {
		try {
			return Customization.of(req).rolesProvider().getRolesForUser(req, username);
		} catch (Exception e) {
			throw U.rte(e);
		}
	} else {
		return Collections.emptySet();
	}
}
 
Example #30
Source File: Main.java    From rapidoid with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {

		/* Returning the request or response object means the response was constructed */

		On.get("/").html((Req req) -> {
			Resp resp = req.response();
			resp.contentType(MediaType.JSON);
			resp.result("hello");
			return resp;
		});
	}