org.restlet.representation.StringRepresentation Java Examples

The following examples show how to use org.restlet.representation.StringRepresentation. 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: RateLimiterResource.java    From uReplicator with 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 #2
Source File: ReferenceList.java    From DeviceConnect-Android with 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 #3
Source File: CurrentStateResource.java    From helix with 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 #4
Source File: TopicManagementRestletResource.java    From uReplicator with Apache License 2.0 6 votes vote down vote up
@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 #5
Source File: AdminRestletResource.java    From uReplicator with 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
Source File: StatusUpdatesResource.java    From helix with 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 #7
Source File: DefaultResponseWriter.java    From attic-polygene-java with 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 #8
Source File: AdminRestletResource.java    From uReplicator with 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 #9
Source File: SchedulerTasksResource.java    From helix with 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 #10
Source File: PlatformDeletePropertiesResource.java    From scava with Eclipse Public License 2.0 6 votes vote down vote up
@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 #11
Source File: StateModelsResource.java    From helix with 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 #12
Source File: MirrorMakerManagerRestletResource.java    From uReplicator with Apache License 2.0 6 votes vote down vote up
@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 #13
Source File: AnalysisTaskByAnalysisTaskResource.java    From scava with Eclipse Public License 2.0 6 votes vote down vote up
@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 #14
Source File: ClustersResource.java    From helix with 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 #15
Source File: CurrentStatesResource.java    From helix with 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 #16
Source File: ValidationRestletResource.java    From uReplicator with 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 #17
Source File: PlatformPropertiesByKeyResource.java    From scava with Eclipse Public License 2.0 6 votes vote down vote up
@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 #18
Source File: StatusUpdateResource.java    From helix with 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 File: InstanceResource.java    From helix with 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 #20
Source File: ErrorsResource.java    From helix with 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 #21
Source File: FactoidListResource.java    From scava with 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 #22
Source File: ErrorResource.java    From helix with 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 #23
Source File: ReferenceList.java    From DeviceConnect-Android with MIT License 5 votes vote down vote up
/**
 * Returns a representation of the list in the "text/uri-list" format.
 * 
 * @return A representation of the list in the "text/uri-list" format.
 */
public Representation getTextRepresentation() {
    final StringBuilder sb = new StringBuilder();

    if (getIdentifier() != null) {
        sb.append("# ").append(getIdentifier().toString()).append("\r\n");
    }

    for (final Reference ref : this) {
        sb.append(ref.toString()).append("\r\n");
    }

    return new StringRepresentation(sb.toString(), MediaType.TEXT_URI_LIST);
}
 
Example #24
Source File: LocalOAuth2Main.java    From DeviceConnect-Android with MIT License 5 votes vote down vote up
/**
 * 認可コードを渡してアクセストークンを取得する.
 * 
 * @param client クライアント
 * @param authCode 認可コード(TokenManager.sessionsに存在するキー値を設定する)
 * @param applicationName アプリケーション名
 * @return not null: アクセストークン / null: アクセストークン取得失敗
 */
private String callAccessTokenServerResource(final Client client, final String authCode,
        final String applicationName) {

    Request request = new Request();
    ClientInfo clientInfo = new ClientInfo();
    org.restlet.security.User user = new org.restlet.security.User(client.getClientId());
    clientInfo.setUser(user);
    request.setClientInfo(clientInfo);

    Response response = new Response(request);
    AccessTokenServerResource.init(request, response);

    // 入力値(アプリケーション名はbase64エンコードする)
    String base64ApplicationName = Base64.encodeToString(applicationName.getBytes(), Base64.URL_SAFE|Base64.NO_WRAP);
    StringRepresentation input = new StringRepresentation("grant_type=authorization_code&code=" + authCode + "&"
            + AccessTokenServerResource.REDIR_URI + "=" + DUMMY_REDIRECT_URI + "&"
            + AccessTokenServerResource.APPLICATION_NAME + "=" + base64ApplicationName);
    try {
        ResultRepresentation resultRepresentation = (ResultRepresentation) AccessTokenServerResource
                .requestToken(input);
        if (resultRepresentation.getResult()) {
            return resultRepresentation.getText();
        }
    } catch (JSONException | OAuthException e) {
        e.printStackTrace();
    }
    return null;
}
 
Example #25
Source File: IdealStateResource.java    From helix with Apache License 2.0 5 votes vote down vote up
StringRepresentation getIdealStateRepresentation(String clusterName, String resourceName)
    throws JsonGenerationException, JsonMappingException, IOException {
  Builder keyBuilder = new PropertyKey.Builder(clusterName);
  ZkClient zkclient =
      ResourceUtil.getAttributeFromCtx(getContext(), ResourceUtil.ContextKey.RAW_ZKCLIENT);
  String idealStateStr =
      ResourceUtil.readZkAsBytes(zkclient, keyBuilder.idealStates(resourceName));

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

  return representation;
}
 
Example #26
Source File: ControllerResource.java    From helix with Apache License 2.0 5 votes vote down vote up
StringRepresentation getControllerRepresentation(String clusterName)
    throws JsonGenerationException, JsonMappingException, IOException {
  Builder keyBuilder = new PropertyKey.Builder(clusterName);
  ZkClient zkClient =
      ResourceUtil.getAttributeFromCtx(getContext(), ResourceUtil.ContextKey.ZKCLIENT);

  ZKHelixDataAccessor accessor =
      new ZKHelixDataAccessor(clusterName, new ZkBaseDataAccessor<ZNRecord>(zkClient));

  ZNRecord record = null;
  LiveInstance leader = accessor.getProperty(keyBuilder.controllerLeader());
  if (leader != null) {
    record = leader.getRecord();
  } else {
    record = new ZNRecord("");
    DateFormat formatter = new SimpleDateFormat("yyyyMMdd-HHmmss.SSSSSS");
    String time = formatter.format(new Date());
    Map<String, String> contentMap = new TreeMap<String, String>();
    contentMap.put("AdditionalInfo", "No leader exists");
    record.setMapField(Level.HELIX_INFO + "-" + time, contentMap);
  }

  boolean paused = (accessor.getProperty(keyBuilder.pause()) == null ? false : true);
  record.setSimpleField(PropertyType.PAUSE.toString(), "" + paused);

  String retVal = ClusterRepresentationUtil.ZNRecordToJson(record);
  StringRepresentation representation =
      new StringRepresentation(retVal, MediaType.APPLICATION_JSON);

  return representation;
}
 
Example #27
Source File: ExternalViewResource.java    From helix with Apache License 2.0 5 votes vote down vote up
StringRepresentation getExternalViewRepresentation(String clusterName, String resourceName)
    throws JsonGenerationException, JsonMappingException, IOException {
  Builder keyBuilder = new PropertyKey.Builder(clusterName);
  ZkClient zkclient =
      ResourceUtil.getAttributeFromCtx(getContext(), ResourceUtil.ContextKey.RAW_ZKCLIENT);

  String extViewStr =
      ResourceUtil.readZkAsBytes(zkclient, keyBuilder.externalView(resourceName));
  StringRepresentation representation =
      new StringRepresentation(extViewStr, MediaType.APPLICATION_JSON);

  return representation;
}
 
Example #28
Source File: JobQueuesResource.java    From helix with Apache License 2.0 5 votes vote down vote up
StringRepresentation getHostedEntitiesRepresentation(String clusterName)
    throws JsonGenerationException, JsonMappingException, IOException {
  // Get all resources
  ZkClient zkClient =
      ResourceUtil.getAttributeFromCtx(getContext(), ResourceUtil.ContextKey.ZKCLIENT);
  HelixDataAccessor accessor =
      ClusterRepresentationUtil.getClusterDataAccessor(zkClient, clusterName);
  PropertyKey.Builder keyBuilder = accessor.keyBuilder();
  Map<String, HelixProperty> resourceConfigMap =
      accessor.getChildValuesMap(keyBuilder.resourceConfigs());

  // Create the result
  ZNRecord hostedEntitiesRecord = new ZNRecord("JobQueues");

  // Filter out non-workflow resources
  Iterator<Map.Entry<String, HelixProperty>> it = resourceConfigMap.entrySet().iterator();
  while (it.hasNext()) {
    Map.Entry<String, HelixProperty> e = it.next();
    HelixProperty resource = e.getValue();
    Map<String, String> simpleFields = resource.getRecord().getSimpleFields();
    boolean isTerminable = resource.getRecord()
        .getBooleanField(WorkflowConfig.WorkflowConfigProperty.Terminable.name(), true);
    if (!simpleFields.containsKey(WorkflowConfig.WorkflowConfigProperty.TargetState.name())
        || !simpleFields.containsKey(WorkflowConfig.WorkflowConfigProperty.Dag.name())
        || isTerminable) {
      it.remove();
    }
  }

  // Populate the result
  List<String> allResources = Lists.newArrayList(resourceConfigMap.keySet());
  hostedEntitiesRecord.setListField("JobQueues", allResources);

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

  return representation;
}
 
Example #29
Source File: ClusterResource.java    From helix with Apache License 2.0 5 votes vote down vote up
StringRepresentation getClusterRepresentation(String clusterName) throws JsonGenerationException,
    JsonMappingException, IOException {
  ZkClient zkClient =
      ResourceUtil.getAttributeFromCtx(getContext(), ResourceUtil.ContextKey.ZKCLIENT);
  ClusterSetup setupTool = new ClusterSetup(zkClient);
  List<String> instances =
      setupTool.getClusterManagementTool().getInstancesInCluster(clusterName);

  ZNRecord clusterSummayRecord = new ZNRecord("Cluster Summary");
  clusterSummayRecord.setListField("participants", instances);

  List<String> resources =
      setupTool.getClusterManagementTool().getResourcesInCluster(clusterName);
  clusterSummayRecord.setListField("resources", resources);

  List<String> models = setupTool.getClusterManagementTool().getStateModelDefs(clusterName);
  clusterSummayRecord.setListField("stateModelDefs", models);

  HelixDataAccessor accessor =
      ClusterRepresentationUtil.getClusterDataAccessor(zkClient, clusterName);
  Builder keyBuilder = accessor.keyBuilder();

  LiveInstance leader = accessor.getProperty(keyBuilder.controllerLeader());
  if (leader != null) {
    clusterSummayRecord.setSimpleField("LEADER", leader.getInstanceName());
  } else {
    clusterSummayRecord.setSimpleField("LEADER", "");
  }
  StringRepresentation representation =
      new StringRepresentation(ClusterRepresentationUtil.ZNRecordToJson(clusterSummayRecord),
          MediaType.APPLICATION_JSON);

  return representation;
}
 
Example #30
Source File: StateModelResource.java    From helix with Apache License 2.0 5 votes vote down vote up
StringRepresentation getStateModelRepresentation(String clusterName, String modelName)
    throws JsonGenerationException, JsonMappingException, IOException {
  Builder keyBuilder = new PropertyKey.Builder(clusterName);
  ZkClient zkClient = (ZkClient) getContext().getAttributes().get(RestAdminApplication.ZKCLIENT);

  String message =
      ClusterRepresentationUtil.getClusterPropertyAsString(zkClient, clusterName,
          keyBuilder.stateModelDef(modelName), MediaType.APPLICATION_JSON);

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

  return representation;
}