Java Code Examples for org.restlet.representation.StringRepresentation

The following examples show how to use org.restlet.representation.StringRepresentation. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
@Override
public Representation doRepresent(){
	String key = (String) getRequest().getAttributes().get("key");
	
	System.out.println("Get platform properties by key ...");
	
	Properties properties = new Properties();
	ProjectRepository projectRepo = platform.getProjectRepositoryManager().getProjectRepository();
	for (Properties prop : projectRepo.getProperties()) {
		if (prop.getKey().equals(key))
			properties = prop;
	}
	
	StringRepresentation rep = new StringRepresentation(properties.getDbObject().toString());
	rep.setMediaType(MediaType.APPLICATION_JSON);
	getResponse().setStatus(Status.SUCCESS_OK);
	return rep;
}
 
Example 2
Source Project: scava   Source File: FactoidListResource.java    License: Eclipse Public License 2.0 6 votes vote down vote up
public Representation doRepresent() {
	ArrayNode node = mapper.createArrayNode();
	
	for (IMetricProvider imp : platform.getMetricProviderManager().getMetricProviders()) {
		if (imp instanceof AbstractFactoidMetricProvider) {
			ObjectNode factoid = mapper.createObjectNode();
			factoid.put("id", imp.getIdentifier());
			factoid.put("name", imp.getFriendlyName());
			factoid.put("summary", imp.getSummaryInformation());
			ArrayNode uses = mapper.createArrayNode();
			if (imp.getIdentifiersOfUses() != null && imp.getIdentifiersOfUses().size() > 0) {
				for (String use : imp.getIdentifiersOfUses()) {
					uses.add(use);
				}
			}
			factoid.put("dependencies", uses);
			
			node.add(factoid);
		}
	}
	
	getResponse().setStatus(Status.SUCCESS_OK);
	StringRepresentation resp = new StringRepresentation(node.toString());
	resp.setMediaType(MediaType.APPLICATION_JSON);
	return resp;
}
 
Example 3
@Override
public Representation doRepresent() {
	AnalysisTaskService service = platform.getAnalysisRepositoryManager().getTaskService();
	
	String analysisTaskId = getQueryValue("analysisTaskId");

	AnalysisTask analysisTask = service.getTaskByAnalysisTaskId(analysisTaskId);
	analysisTask.getDbObject().put("projectId", analysisTask.getProject().getProjectId());

	List<Object> metricExecutions = new ArrayList<>();
	for (MetricExecution metric : analysisTask.getMetricExecutions()) {
		Map<String, String> newMetric = new HashMap<>();
		newMetric.put("metricProviderId", metric.getDbObject().get("metricProviderId").toString());
		newMetric.put("projectId", metric.getDbObject().get("projectId").toString());
		newMetric.put("lastExecutionDate", metric.getDbObject().get("lastExecutionDate").toString());
		metricExecutions.add(newMetric);
	}
	analysisTask.getDbObject().put("metricExecutions", metricExecutions);

	StringRepresentation rep = new StringRepresentation(analysisTask.getDbObject().toString());
	rep.setMediaType(MediaType.APPLICATION_JSON);
	getResponse().setStatus(Status.SUCCESS_OK);
	return rep;
}
 
Example 4
@Delete
public Representation deletePlatformProperties() {
	Platform platform = Platform.getInstance();
	
	String key = (String) getRequest().getAttributes().get("key");
	
	System.out.println("Delete platform properties ...");
	
	ProjectRepository projectRepo = platform.getProjectRepositoryManager().getProjectRepository();
	
	Properties properties = projectRepo.getProperties().findOneByKey(key);
	if (properties != null) {
		projectRepo.getProperties().remove(properties);
		platform.getProjectRepositoryManager().getProjectRepository().getProperties().sync();
	}
	
	StringRepresentation rep = new StringRepresentation(properties.getDbObject().toString());
	rep.setMediaType(MediaType.APPLICATION_JSON);
	getResponse().setStatus(Status.SUCCESS_OK);
	return rep;
}
 
Example 5
Source Project: uReplicator   Source File: AdminRestletResource.java    License: Apache License 2.0 6 votes vote down vote up
@Override
@Get
public Representation get() {
  final String opt = (String) getRequest().getAttributes().get("opt");
  JSONObject responseJson = new JSONObject();
  if ("autoscaling_status".equalsIgnoreCase(opt)) {
    responseJson.put(opt, _helixMirrorMakerManager.isAutoScalingEnabled());
  } else if ("autobalancing_status".equalsIgnoreCase(opt)) {
    responseJson.put(opt, _helixMirrorMakerManager.isAutoBalancingEnabled());
  } else if ("controller_autobalancing".equalsIgnoreCase(opt)) {
    AdminHelper helper = new AdminHelper(_helixMirrorMakerManager);
    return new StringRepresentation(helper.getControllerAutobalancingStatus(null, null)
        .toJSONString());
  } else if ("worker_number_override".equalsIgnoreCase(opt)) {
    responseJson.put("worker_number_override", _helixMirrorMakerManager.getRouteWorkerOverride());
  } else {
    LOGGER.info("No valid input!");
    responseJson.put("opt", "No valid input!");
  }
  return new StringRepresentation(responseJson.toJSONString());
}
 
Example 6
@Override
@Put("json")
public Representation put(Representation entity) {
  try {
    String jsonRequest = entity.getText();
    TopicPartition topicPartitionInfo = TopicPartition.init(jsonRequest);
    if (_autoTopicWhitelistingManager != null) {
      _autoTopicWhitelistingManager.removeFromBlacklist(topicPartitionInfo.getTopic());
    }
    if (_helixMirrorMakerManager.isTopicExisted(topicPartitionInfo.getTopic())) {
      _helixMirrorMakerManager.expandTopicInMirrorMaker(topicPartitionInfo);
      return new StringRepresentation(
          String.format("Successfully expand topic: %s", topicPartitionInfo));
    } else {
      getResponse().setStatus(Status.CLIENT_ERROR_NOT_FOUND);
      return new StringRepresentation(String.format(
          "Failed to expand topic, topic: %s is not existed!", topicPartitionInfo.getTopic()));
    }
  } catch (Exception e) {
    LOGGER.error("Got error during processing Put request", e);
    getResponse().setStatus(Status.SERVER_ERROR_INTERNAL);
    return new StringRepresentation(
        String.format("Failed to expand topic, with exception: %s", e));
  }
}
 
Example 7
Source Project: uReplicator   Source File: AdminRestletResource.java    License: Apache License 2.0 6 votes vote down vote up
@Post
public Representation post() {
  final String opt = (String) getRequest().getAttributes().get("opt");
  JSONObject responseJson = new JSONObject();
  if ("disable_autobalancing".equalsIgnoreCase(opt)) {
    _helixMirrorMakerManager.disableAutoBalancing();
    LOGGER.info("Disabled autobalancing!");
    responseJson.put("opt", "disable_autobalancing");
    responseJson.put("auto_balancing", _helixMirrorMakerManager.isAutoBalancingEnabled());
  } else if ("enable_autobalancing".equalsIgnoreCase(opt)) {
    _helixMirrorMakerManager.enableAutoBalancing();
    LOGGER.info("Enabled autobalancing!");
    responseJson.put("opt", "enable_autobalancing");
    responseJson.put("auto_balancing", _helixMirrorMakerManager.isAutoBalancingEnabled());
  } else {
    LOGGER.info("No valid input!");
    responseJson.put("opt", "No valid input!");
  }
  return new StringRepresentation(responseJson.toJSONString());
}
 
Example 8
@Override
@Delete
public Representation delete() {
  final String instanceName = (String) getRequest().getAttributes().get("instanceName");
  if (instanceName == null) {
    return new StringRepresentation("Instance name is required to blacklist");
  }
  // blacklist a worker
  try {
    _helixMirrorMakerManager.blacklistInstance(instanceName);
    return new StringRepresentation(String.format("Instance %s is blacklisted", instanceName));
  } catch (Exception e) {
    LOGGER.error("Got error during processing Delete request", e);
    getResponse().setStatus(Status.SERVER_ERROR_INTERNAL);
    return new StringRepresentation(String
        .format("Failed to blacklist instance %s, with exception: %s", instanceName, e));
  }
}
 
Example 9
Source Project: uReplicator   Source File: ValidationRestletResource.java    License: Apache License 2.0 6 votes vote down vote up
@Override
@Get
public Representation get() {
  final String option = (String) getRequest().getAttributes().get("option");
  if ("srcKafka".equals(option)) {
    if (_srcKafkaValidationManager == null) {
      LOGGER.warn("SourceKafkaClusterValidationManager is null!");
      return new StringRepresentation("SrcKafkaValidationManager is not been initialized!");
    }
    LOGGER.info("Trying to call validation on source kafka cluster!");
    return new StringRepresentation(_srcKafkaValidationManager.validateSourceKafkaCluster());
  } else {
    LOGGER.info("Trying to call validation on current cluster!");
    return new StringRepresentation(_validationManager.validateExternalView());
  }
}
 
Example 10
Source Project: uReplicator   Source File: RateLimiterResource.java    License: Apache License 2.0 6 votes vote down vote up
@Override
@Put
public Representation put(Representation entity) {
  Form params = getRequest().getResourceRef().getQueryAsForm();
  String rate = params.getFirstValue("messagerate");
  if (StringUtils.isEmpty(rate)) {
    getResponse().setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
    return new StringRepresentation(
        String.format("Failed to add new rate limit due to missing parameter messagerate%n"));
  }
  try {
    workerInstance.setMessageRatePerSecond(Double.parseDouble(rate));
    LOGGER.info("Set messageRate to {} finished", rate);
  } catch (Exception e) {
    getResponse().setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
    LOGGER.error("Set messageRate to {} failed", rate, e);
    return new StringRepresentation(
        String.format("Failed to add new topic, with exception: %s%n", e));
  }
  return new StringRepresentation(
      String.format("Successfully set rate: %s%n", rate));
}
 
Example 11
Source Project: DeviceConnect-Android   Source File: ReferenceList.java    License: MIT License 6 votes vote down vote up
/**
 * Returns a representation of the list in "text/html" format.
 * 
 * @return A representation of the list in "text/html" format.
 */
public Representation getWebRepresentation() {
    // Create a simple HTML list
    final StringBuilder sb = new StringBuilder();
    sb.append("<html><body style=\"font-family: sans-serif;\">\n");

    if (getIdentifier() != null) {
        sb.append("<h2>Listing of \"" + getIdentifier().getPath()
                + "\"</h2>\n");
        final Reference parentRef = getIdentifier().getParentRef();

        if (!parentRef.equals(getIdentifier())) {
            sb.append("<a href=\"" + parentRef + "\">..</a><br>\n");
        }
    } else {
        sb.append("<h2>List of references</h2>\n");
    }

    for (final Reference ref : this) {
        sb.append("<a href=\"" + ref.toString() + "\">"
                + ref.getRelativeRef(getIdentifier()) + "</a><br>\n");
    }
    sb.append("</body></html>\n");

    return new StringRepresentation(sb.toString(), MediaType.TEXT_HTML);
}
 
Example 12
Source Project: attic-polygene-java   Source File: DefaultResponseWriter.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public boolean writeResponse( final Object result, final Response response )
    throws ResourceException
{
    MediaType type = getVariant( response.getRequest(), ENGLISH, supportedMediaTypes ).getMediaType();
    if( MediaType.APPLICATION_JSON.equals( type ) )
    {
        if( result instanceof String || result instanceof Number || result instanceof Boolean )
        {
            StringRepresentation representation = new StringRepresentation( result.toString(),
                                                                            MediaType.APPLICATION_JSON );

            response.setEntity( representation );

            return true;
        }
    }

    return false;
}
 
Example 13
Source Project: helix   Source File: ErrorsResource.java    License: Apache License 2.0 6 votes vote down vote up
StringRepresentation getInstanceErrorsRepresentation(String clusterName, String instanceName)
    throws JsonGenerationException, JsonMappingException, IOException {
  ZkClient zkClient = (ZkClient) getContext().getAttributes().get(RestAdminApplication.ZKCLIENT);
  ;

  String instanceSessionId =
      ClusterRepresentationUtil.getInstanceSessionId(zkClient, clusterName, instanceName);

  String message =
      ClusterRepresentationUtil
          .getInstancePropertyNameListAsString(zkClient, clusterName, instanceName,
              PropertyType.CURRENTSTATES, instanceSessionId, MediaType.APPLICATION_JSON);

  StringRepresentation representation =
      new StringRepresentation(message, MediaType.APPLICATION_JSON);

  return representation;
}
 
Example 14
Source Project: helix   Source File: CurrentStatesResource.java    License: Apache License 2.0 6 votes vote down vote up
StringRepresentation getInstanceCurrentStatesRepresentation(String clusterName,
    String instanceName) throws JsonGenerationException, JsonMappingException, IOException {
  ZkClient zkClient = (ZkClient) getContext().getAttributes().get(RestAdminApplication.ZKCLIENT);
  ;
  String instanceSessionId =
      ClusterRepresentationUtil.getInstanceSessionId(zkClient, clusterName, instanceName);

  String message =
      ClusterRepresentationUtil
          .getInstancePropertyNameListAsString(zkClient, clusterName, instanceName,
              PropertyType.CURRENTSTATES, instanceSessionId, MediaType.APPLICATION_JSON);

  StringRepresentation representation =
      new StringRepresentation(message, MediaType.APPLICATION_JSON);

  return representation;
}
 
Example 15
Source Project: helix   Source File: StatusUpdatesResource.java    License: Apache License 2.0 6 votes vote down vote up
StringRepresentation getInstanceErrorsRepresentation(String clusterName, String instanceName)
    throws JsonGenerationException, JsonMappingException, IOException {
  ZkClient zkClient = (ZkClient) getContext().getAttributes().get(RestAdminApplication.ZKCLIENT);
  String instanceSessionId =
      ClusterRepresentationUtil.getInstanceSessionId(zkClient, clusterName, instanceName);

  String message =
      ClusterRepresentationUtil
          .getInstancePropertyNameListAsString(zkClient, clusterName, instanceName,
              PropertyType.CURRENTSTATES, instanceSessionId, MediaType.APPLICATION_JSON);

  StringRepresentation representation =
      new StringRepresentation(message, MediaType.APPLICATION_JSON);

  return representation;
}
 
Example 16
Source Project: helix   Source File: CurrentStateResource.java    License: Apache License 2.0 6 votes vote down vote up
StringRepresentation getInstanceCurrentStateRepresentation(String clusterName,
    String instanceName, String resourceGroup) throws JsonGenerationException,
    JsonMappingException, IOException {
  ZkClient zkClient = (ZkClient) getRequest().getAttributes().get(RestAdminApplication.ZKCLIENT);
  String instanceSessionId =
      ClusterRepresentationUtil.getInstanceSessionId(zkClient, clusterName, instanceName);
  Builder keyBuilder = new PropertyKey.Builder(clusterName);

  String message =
      ClusterRepresentationUtil.getInstancePropertyAsString(zkClient, clusterName,
          keyBuilder.currentState(instanceName, instanceSessionId, resourceGroup),
          MediaType.APPLICATION_JSON);
  StringRepresentation representation =
      new StringRepresentation(message, MediaType.APPLICATION_JSON);
  return representation;
}
 
Example 17
Source Project: helix   Source File: ErrorResource.java    License: Apache License 2.0 6 votes vote down vote up
StringRepresentation getInstanceErrorsRepresentation(String clusterName, String instanceName,
    String resourceGroup) throws JsonGenerationException, JsonMappingException, IOException {
  ZkClient zkClient = (ZkClient) getContext().getAttributes().get(RestAdminApplication.ZKCLIENT);
  String instanceSessionId =
      ClusterRepresentationUtil.getInstanceSessionId(zkClient, clusterName, instanceName);
  Builder keyBuilder = new PropertyKey.Builder(clusterName);
  String message =
      ClusterRepresentationUtil.getInstancePropertiesAsString(zkClient, clusterName,
          keyBuilder.stateTransitionErrors(instanceName, instanceSessionId, resourceGroup),
          // instanceSessionId
          // + "__"
          // + resourceGroup,
          MediaType.APPLICATION_JSON);
  StringRepresentation representation =
      new StringRepresentation(message, MediaType.APPLICATION_JSON);
  return representation;
}
 
Example 18
Source Project: helix   Source File: StatusUpdateResource.java    License: Apache License 2.0 6 votes vote down vote up
StringRepresentation getInstanceStatusUpdateRepresentation(String clusterName,
    String instanceName, String resourceGroup) throws JsonGenerationException,
    JsonMappingException, IOException {
  ZkClient zkClient = (ZkClient) getContext().getAttributes().get(RestAdminApplication.ZKCLIENT);

  String instanceSessionId =
      ClusterRepresentationUtil.getInstanceSessionId(zkClient, clusterName, instanceName);

  Builder keyBuilder = new PropertyKey.Builder(clusterName);
  String message =
      ClusterRepresentationUtil.getInstancePropertiesAsString(zkClient, clusterName,
          keyBuilder.stateTransitionStatus(instanceName, instanceSessionId, resourceGroup),
          // instanceSessionId
          // + "__"
          // + resourceGroup,
          MediaType.APPLICATION_JSON);
  StringRepresentation representation =
      new StringRepresentation(message, MediaType.APPLICATION_JSON);
  return representation;
}
 
Example 19
Source Project: helix   Source File: SchedulerTasksResource.java    License: Apache License 2.0 6 votes vote down vote up
StringRepresentation getSchedulerTasksRepresentation() throws JsonGenerationException,
    JsonMappingException, IOException {
  String clusterName = (String) getRequest().getAttributes().get("clusterName");
  String instanceName = (String) getRequest().getAttributes().get("instanceName");
  ZkClient zkClient = (ZkClient) getContext().getAttributes().get(RestAdminApplication.ZKCLIENT);
  ClusterSetup setupTool = new ClusterSetup(zkClient);
  List<String> instances =
      setupTool.getClusterManagementTool().getInstancesInCluster(clusterName);

  HelixDataAccessor accessor =
      ClusterRepresentationUtil.getClusterDataAccessor(zkClient, clusterName);
  LiveInstance liveInstance =
      accessor.getProperty(accessor.keyBuilder().liveInstance(instanceName));
  String sessionId = liveInstance.getEphemeralOwner();

  StringRepresentation representation = new StringRepresentation("");// (ClusterRepresentationUtil.ObjectToJson(instanceConfigs),
                                                                     // MediaType.APPLICATION_JSON);

  return representation;
}
 
Example 20
Source Project: helix   Source File: StateModelsResource.java    License: Apache License 2.0 6 votes vote down vote up
StringRepresentation getStateModelsRepresentation() throws JsonGenerationException,
    JsonMappingException, IOException {
  String clusterName = (String) getRequest().getAttributes().get("clusterName");
  ZkClient zkClient = (ZkClient) getContext().getAttributes().get(RestAdminApplication.ZKCLIENT);
  ClusterSetup setupTool = new ClusterSetup(zkClient);

  List<String> models = setupTool.getClusterManagementTool().getStateModelDefs(clusterName);

  ZNRecord modelDefinitions = new ZNRecord("modelDefinitions");
  modelDefinitions.setListField("models", models);

  StringRepresentation representation =
      new StringRepresentation(ClusterRepresentationUtil.ZNRecordToJson(modelDefinitions),
          MediaType.APPLICATION_JSON);

  return representation;
}
 
Example 21
Source Project: helix   Source File: InstanceResource.java    License: Apache License 2.0 6 votes vote down vote up
StringRepresentation getInstanceRepresentation() throws JsonGenerationException,
    JsonMappingException, IOException {
  String clusterName =
      ResourceUtil.getAttributeFromRequest(getRequest(), ResourceUtil.RequestKey.CLUSTER_NAME);
  String instanceName =
      ResourceUtil.getAttributeFromRequest(getRequest(), ResourceUtil.RequestKey.INSTANCE_NAME);
  Builder keyBuilder = new PropertyKey.Builder(clusterName);
  ZkClient zkclient =
      ResourceUtil.getAttributeFromCtx(getContext(), ResourceUtil.ContextKey.RAW_ZKCLIENT);

  String instanceCfgStr =
      ResourceUtil.readZkAsBytes(zkclient, keyBuilder.instanceConfig(instanceName));
  StringRepresentation representation =
      new StringRepresentation(instanceCfgStr, MediaType.APPLICATION_JSON);

  return representation;
}
 
Example 22
Source Project: helix   Source File: ClustersResource.java    License: Apache License 2.0 6 votes vote down vote up
StringRepresentation getClustersRepresentation() throws JsonGenerationException,
    JsonMappingException, IOException {
  ZkClient zkClient =
      ResourceUtil.getAttributeFromCtx(getContext(), ResourceUtil.ContextKey.ZKCLIENT);

  ClusterSetup setupTool = new ClusterSetup(zkClient);
  List<String> clusters = setupTool.getClusterManagementTool().getClusters();

  ZNRecord clustersRecord = new ZNRecord("Clusters Summary");
  clustersRecord.setListField("clusters", clusters);
  StringRepresentation representation =
      new StringRepresentation(ClusterRepresentationUtil.ZNRecordToJson(clustersRecord),
          MediaType.APPLICATION_JSON);

  return representation;
}
 
Example 23
Source Project: scava   Source File: AnalysisPromoteTaskResource.java    License: Eclipse Public License 2.0 5 votes vote down vote up
@Override
public Representation doRepresent() {
	AnalysisTaskService service = platform.getAnalysisRepositoryManager().getTaskService();
	
	String analysisTaskId = getQueryValue("analysisTaskId");

	AnalysisTask task = service.promoteTask(analysisTaskId);

	StringRepresentation rep = new StringRepresentation(task.getDbObject().toString());
	rep.setMediaType(MediaType.APPLICATION_JSON);
	getResponse().setStatus(Status.SUCCESS_OK);
	return rep;
}
 
Example 24
Source Project: scava   Source File: ProjectResource.java    License: Eclipse Public License 2.0 5 votes vote down vote up
public Representation doRepresent() {
	String projectId = (String) getRequest().getAttributes().get("projectid");
	
	ProjectRepository projectRepo = platform.getProjectRepositoryManager().getProjectRepository();
	
	// FIXME: This exclusion list needs to be somewhere... 
	BasicDBObject ex = new BasicDBObject("executionInformation", 0);
	ex.put("storage", 0);
	ex.put("metricProviderData", 0);
	ex.put("_superTypes", 0);
	ex.put("_id", 0);
	
	// FIXME: Temporary solution to DBRefs not being expanded
	// How can we auto-expand and DBRefs when serialising?
	ex.put("licenses", 0);
	ex.put("persons", 0);
	ex.put("companies", 0);
	
	BasicDBObject query = new BasicDBObject("shortName", projectId);
	
	DBObject p = projectRepo.getProjects().getDbCollection().findOne(query, ex);

	if (p == null) {
		getResponse().setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
		return Util.generateErrorMessageRepresentation(generateRequestJson(mapper, projectId), "No project was found with the requested name.");
	}
	
	try {
		StringRepresentation resp = new StringRepresentation(p.toString());
		resp.setMediaType(MediaType.APPLICATION_JSON);
		return resp;
	} catch (Exception e) {
		e.printStackTrace();
		getResponse().setStatus(Status.SERVER_ERROR_INTERNAL);
		return Util.generateErrorMessageRepresentation(generateRequestJson(mapper, projectId), "An error occurred when converting the project to JSON: " + e.getMessage());
	}
}
 
Example 25
@Override
public Representation doRepresent() {
	String globalStatus;
	AnalysisTaskService service = platform.getAnalysisRepositoryManager().getTaskService();
	String projectId = (String) getRequest().getAttributes().get("projectid");
	
	List<AnalysisTask> tasks = service.getAnalysisTasksByProject(projectId);
	
	String stat = "none";
	for (AnalysisTask analysisTask : tasks) {
		if (analysisTask.getScheduling().getStatus().equals(AnalysisTaskStatus.COMPLETED.name()) || analysisTask.getScheduling().getStatus().equals(AnalysisTaskStatus.STOP.name())) {
			stat = "up-to-date";
		} else if (analysisTask.getScheduling().getStatus().equals(AnalysisTaskStatus.ERROR.name())) {
			stat = "error";
			break;
		}
		else {
			stat = "in-progress";
			break;
		}
	}
	if (stat.equals("up-to-date")) {
		globalStatus = "{\"value\":\"up-to-date\"}";
	} else if (stat.equals("in-progress")){
		globalStatus = "{\"value\":\"in-progress\"}";
	} else if (stat.equals("error")){
		globalStatus = "{\"value\":\"error\"}";
	} else {
		globalStatus = "{\"value\":\"none\"}";
	}
	
	StringRepresentation rep = new StringRepresentation(globalStatus);
	rep.setMediaType(MediaType.APPLICATION_JSON);
	getResponse().setStatus(Status.SUCCESS_OK);
	return rep;
}
 
Example 26
Source Project: scava   Source File: AnalysisDemoteTaskResource.java    License: Eclipse Public License 2.0 5 votes vote down vote up
@Override
public Representation doRepresent() {
	AnalysisTaskService service = platform.getAnalysisRepositoryManager().getTaskService();
	
	String analysisTaskId = getQueryValue("analysisTaskId");

	AnalysisTask task = service.demoteTask(analysisTaskId);

	StringRepresentation rep = new StringRepresentation(task.getDbObject().toString());
	rep.setMediaType(MediaType.APPLICATION_JSON);
	getResponse().setStatus(Status.SUCCESS_OK);
	return rep;
}
 
Example 27
@Override
public Representation doRepresent() {
	AnalysisTaskService service = platform.getAnalysisRepositoryManager().getTaskService();
	
	String analysisTaskId = getQueryValue("analysisTaskId");
	String workerId = getQueryValue("workerId");
	
	AnalysisTask task =  service.executeTaskOnWorker(analysisTaskId, workerId);

	StringRepresentation rep = new StringRepresentation(task.getDbObject().toString());
	rep.setMediaType(MediaType.APPLICATION_JSON);
	getResponse().setStatus(Status.SUCCESS_OK);
	return rep;
}
 
Example 28
Source Project: scava   Source File: ProjectEditionResource.java    License: Eclipse Public License 2.0 5 votes vote down vote up
@Put
public Representation editProject(Representation entity) {
	try {
		Platform platform = Platform.getInstance();
		ObjectMapper mapper = new ObjectMapper();

		String j = entity.getText();

		JsonNode json = mapper.readTree(j);
		String sortName = json.get("shortName").asText();

		// Retrieve the older project
		ProjectRepository projectRepo = platform.getProjectRepositoryManager().getProjectRepository();
		Project project = projectRepo.getProjects().findOneByShortName(sortName);
		
		if (project instanceof GitHubRepository) {
			this.editGithubProject(json, project);
		} else if (project instanceof GitLabRepository) {
			this.editGitlabProject(json, project);
		} else if (project instanceof EclipseProject) {
			this.editEclipseProject(json, project);
		} else {
			this.editProject(json, project);
		}

		platform.getProjectRepositoryManager().getProjectRepository().getProjects().sync();

		getResponse().setStatus(Status.SUCCESS_CREATED);
		return new StringRepresentation(project.getDbObject().toString());

	} catch (IOException e) {
		e.printStackTrace(); // TODO
		StringRepresentation rep = new StringRepresentation(
				"{\"status\":\"error\", \"message\" : \"" + e.getMessage() + "\"}");
		rep.setMediaType(MediaType.APPLICATION_JSON);
		getResponse().setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
		return rep;
	}
}
 
Example 29
Source Project: scava   Source File: AnalysisDeleteTaskResource.java    License: Eclipse Public License 2.0 5 votes vote down vote up
@Delete
public Representation deleteAnalysisTask() {
	Platform platform = Platform.getInstance();
	AnalysisTaskService service = platform.getAnalysisRepositoryManager().getTaskService();
	
	String analysisTaskId = getQueryValue("analysisTaskId");

	AnalysisTask task = service.deleteAnalysisTask(analysisTaskId);

	StringRepresentation rep = new StringRepresentation(task.getDbObject().toString());
	rep.setMediaType(MediaType.APPLICATION_JSON);
	getResponse().setStatus(Status.SUCCESS_OK);
	return rep;
}
 
Example 30
private StringRepresentation getResponseJsonStringRepresentation(Status status, Object message) {
  JSONObject responseJson = new JSONObject();
  responseJson.put("status", status.getCode());
  responseJson.put("message", message);
  getResponse().setStatus(status);
  return new StringRepresentation(responseJson.toJSONString());
}