org.restlet.data.MediaType Java Examples

The following examples show how to use org.restlet.data.MediaType. 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: AdminTestHelper.java    From helix with Apache License 2.0 7 votes vote down vote up
public static ZNRecord post(Client client, String url, String body)
    throws IOException {
  Reference resourceRef = new Reference(url);
  Request request = new Request(Method.POST, resourceRef);

  request.setEntity(body, MediaType.APPLICATION_ALL);

  Response response = client.handle(request);
  Assert.assertEquals(response.getStatus(), Status.SUCCESS_OK);
  Representation result = response.getEntity();
  StringWriter sw = new StringWriter();

  if (result != null) {
    result.write(sw);
  }
  String responseStr = sw.toString();
  Assert.assertTrue(responseStr.toLowerCase().indexOf("error") == -1);
  Assert.assertTrue(responseStr.toLowerCase().indexOf("exception") == -1);

  ObjectMapper mapper = new ObjectMapper();
  ZNRecord record = mapper.readValue(new StringReader(responseStr), ZNRecord.class);
  return record;
}
 
Example #2
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 #3
Source File: ZkPathResource.java    From helix with Apache License 2.0 6 votes vote down vote up
@Override
public Representation delete() {
  String zkPath = getZKPath();
  try {
    ZkClient zkClient =
        (ZkClient) getContext().getAttributes().get(RestAdminApplication.ZKCLIENT);
    zkClient.deleteRecursively(zkPath);

    getResponse().setStatus(Status.SUCCESS_OK);
  } catch (Exception e) {
    getResponse().setEntity(ClusterRepresentationUtil.getErrorAsJsonStringFromException(e),
        MediaType.APPLICATION_JSON);
    getResponse().setStatus(Status.SUCCESS_OK);
    LOG.error("Error in delete zkPath: " + zkPath, e);
  }
  return null;
}
 
Example #4
Source File: ExceptionProcessor.java    From container with Apache License 2.0 6 votes vote down vote up
@Override
public void process(final Exchange exchange) throws Exception {

    ExceptionProcessor.LOG.debug("Exception handling...");

    final Response response = exchange.getIn().getHeader(RestletConstants.RESTLET_RESPONSE, Response.class);

    if (exchange.getIn().getBody() instanceof ParseException) {
        response.setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
        response.setEntity("JSON is not valid: " + exchange.getIn().getBody(String.class), MediaType.TEXT_ALL);
    } else if (exchange.getIn().getBody() instanceof NullPointerException) {
        response.setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
        response.setEntity("Needed information not specified.", MediaType.TEXT_ALL);
    } else if (exchange.getIn().getBody() instanceof ApplicationBusExternalException) {
        response.setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
        response.setEntity(exchange.getIn().getBody(String.class), MediaType.TEXT_ALL);
    } else if (exchange.getIn().getBody() instanceof ApplicationBusInternalException) {
        response.setStatus(Status.SERVER_ERROR_INTERNAL);
        response.setEntity(exchange.getIn().getBody(String.class), MediaType.TEXT_ALL);
    }

    exchange.getOut().setBody(response);
}
 
Example #5
Source File: NeighbourhoodManagerConnector.java    From vicinity-gateway-api with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Retrieves the thing descriptions of list IoT objects from the Neighborhood Manager. 
 * 
 * @param Representation of the incoming JSON. List of OIDs
 * @return Thing descriptions of objects specified in payload.
 */
public synchronized Representation getThingDescriptions(Representation json){
	
	String endpointUrl = SERVER_PROTOCOL + neighbourhoodManagerServer + ":" + port + API_PATH + TD_SERVICE;
	
	ClientResource clientResource = createRequest(endpointUrl);
	
	Representation responseRepresentation = clientResource.post(json, MediaType.APPLICATION_JSON);
	
	return responseRepresentation;
	
	/*
	String ret;
	
	try {
		ret = representation.getText();
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
		ret = null;
	}

	return ret;
	*/
}
 
Example #6
Source File: LinksResponseWriter.java    From attic-polygene-java with Apache License 2.0 6 votes vote down vote up
private Representation createTextHtmlRepresentation( final Object result, final Response response )
{
    return new WriterRepresentation( MediaType.TEXT_HTML )
                {
                    @Override
                    public void write( Writer writer )
                        throws IOException
                    {
                        Map<String, Object> context = new HashMap<>();
                        context.put( "request", response.getRequest() );
                        context.put( "response", response );
                        context.put( "result", result );
                        try
                        {
                            cfg.getTemplate( "links.htm" ).process( context, writer );
                        }
                        catch( TemplateException e )
                        {
                            throw new IOException( e );
                        }
                    }
                };
}
 
Example #7
Source File: InstanceResource.java    From helix with Apache License 2.0 6 votes vote down vote up
@Override
public Representation delete() {
  try {
    String clusterName =
        ResourceUtil.getAttributeFromRequest(getRequest(), ResourceUtil.RequestKey.CLUSTER_NAME);
    String instanceName =
        ResourceUtil.getAttributeFromRequest(getRequest(), ResourceUtil.RequestKey.INSTANCE_NAME);
    ZkClient zkclient =
        ResourceUtil.getAttributeFromCtx(getContext(), ResourceUtil.ContextKey.ZKCLIENT);
    ClusterSetup setupTool = new ClusterSetup(zkclient);
    setupTool.dropInstanceFromCluster(clusterName, instanceName);
    getResponse().setStatus(Status.SUCCESS_OK);
  } catch (Exception e) {
    getResponse().setEntity(ClusterRepresentationUtil.getErrorAsJsonStringFromException(e),
        MediaType.APPLICATION_JSON);
    getResponse().setStatus(Status.SUCCESS_OK);
    LOG.error("Error in delete instance", e);
  }
  return null;
}
 
Example #8
Source File: EntityResource.java    From attic-polygene-java with Apache License 2.0 6 votes vote down vote up
private Representation representRdfXml( final EntityState entity )
    throws ResourceException
{
    Representation representation = new WriterRepresentation( MediaType.APPLICATION_RDF_XML )
    {
        @Override
        public void write( Writer writer )
            throws IOException
        {
            try
            {
                Iterable<Statement> statements = entitySerializer.serialize( entity );
                new RdfXmlSerializer().serialize( statements, writer );
            }
            catch( RDFHandlerException e )
            {
                throw new IOException( e );
            }
        }
    };
    representation.setCharacterSet( CharacterSet.UTF_8 );
    return representation;
}
 
Example #9
Source File: ResourceGroupResource.java    From helix with Apache License 2.0 6 votes vote down vote up
@Override
public Representation delete() {
  try {
    String clusterName =
        ResourceUtil.getAttributeFromRequest(getRequest(), ResourceUtil.RequestKey.CLUSTER_NAME);
    String resourceName =
        ResourceUtil.getAttributeFromRequest(getRequest(), ResourceUtil.RequestKey.RESOURCE_NAME);
    ZkClient zkclient =
        ResourceUtil.getAttributeFromCtx(getContext(), ResourceUtil.ContextKey.ZKCLIENT);

    ClusterSetup setupTool = new ClusterSetup(zkclient);
    setupTool.dropResourceFromCluster(clusterName, resourceName);
    getResponse().setStatus(Status.SUCCESS_OK);
  } catch (Exception e) {
    getResponse().setEntity(ClusterRepresentationUtil.getErrorAsJsonStringFromException(e),
        MediaType.APPLICATION_JSON);
    getResponse().setStatus(Status.SUCCESS_OK);
    LOG.error("", e);
  }
  return null;
}
 
Example #10
Source File: AgentsAgidObjectsDelete.java    From vicinity-gateway-api with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Deletes - unregisters the IoT object(s).
 * 
 * @param entity Representation of the incoming JSON. List of IoT thing descriptions that are to be removed 
 * (taken from request).
 * @return Notification of success or failure.
 * 
 */
@Post("json")
public Representation accept(Representation entity) {
	
	String attrAgid = getAttribute(ATTR_AGID);
	
	Logger logger = (Logger) getContext().getAttributes().get(Api.CONTEXT_LOGGER);
	XMLConfiguration config = (XMLConfiguration) getContext().getAttributes().get(Api.CONTEXT_CONFIG);
	
	if (attrAgid == null){
		logger.info("AGID: " + attrAgid + " Invalid Agent ID.");
		throw new ResourceException(Status.CLIENT_ERROR_NOT_FOUND, 
				"Invalid Agent ID.");
	}
	
	if (!entity.getMediaType().equals(MediaType.APPLICATION_JSON)){
		logger.info("AGID: " + attrAgid + " Invalid object descriptions.");
		
		throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, 
				"Invalid object descriptions");
	}
	
	return deleteObjects(entity, logger, config);
}
 
Example #11
Source File: ExceptionProcessor.java    From container with Apache License 2.0 6 votes vote down vote up
@Override
public void process(final Exchange exchange) throws Exception {

    ExceptionProcessor.LOG.debug("Exception handling...");

    final Response response = exchange.getIn().getHeader(RestletConstants.RESTLET_RESPONSE, Response.class);

    if (exchange.getIn().getBody() instanceof ParseException) {
        response.setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
        final String body = exchange.getIn().getBody(String.class);
        response.setEntity("JSON is not valid: " + body, MediaType.TEXT_ALL);
        ExceptionProcessor.LOG.warn("JSON is not valid: {}", body);
    } else if (exchange.getIn().getBody() instanceof NullPointerException) {
        response.setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
        response.setEntity("Needed information not specified.", MediaType.TEXT_ALL);
        ExceptionProcessor.LOG.warn("Needed information not specified.");
    } else if (exchange.getIn().getBody() instanceof Exception) {
        response.setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
        response.setEntity("Invocation failed! " + exchange.getIn().getBody().toString(), MediaType.TEXT_ALL);
        ExceptionProcessor.LOG.warn("Invocation failed! " + exchange.getIn().getBody().toString());
    }

    exchange.getOut().setBody(response);
}
 
Example #12
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 #13
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 #14
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 #15
Source File: SwaggerResource.java    From geowave with Apache License 2.0 6 votes vote down vote up
/** This resource returns the swagger.json */
@Get("json")
public String listResources() {
  final ServletContext servlet =
      (ServletContext) getContext().getAttributes().get("org.restlet.ext.servlet.ServletContext");
  final String realPath = servlet.getRealPath("/");
  final JacksonRepresentation<ApiDeclaration> result =
      new JacksonRepresentation<>(
          new FileRepresentation(realPath + "swagger.json", MediaType.APPLICATION_JSON),
          ApiDeclaration.class);
  try {
    return result.getText();
  } catch (final IOException e) {
    LOGGER.warn("Error building swagger json", e);
  }
  return "Not Found: swagger.json";
}
 
Example #16
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 #17
Source File: TestClusterManagementWebapp.java    From helix with Apache License 2.0 5 votes vote down vote up
void verifyAddCluster() throws IOException, InterruptedException {
  String httpUrlBase = "http://localhost:" + ADMIN_PORT + "/clusters";
  Map<String, String> paraMap = new HashMap<String, String>();

  paraMap.put(JsonParameters.CLUSTER_NAME, clusterName);
  paraMap.put(JsonParameters.MANAGEMENT_COMMAND, ClusterSetup.addCluster);

  Reference resourceRef = new Reference(httpUrlBase);

  Request request = new Request(Method.POST, resourceRef);

  request.setEntity(
      JsonParameters.JSON_PARAMETERS + "=" + ClusterRepresentationUtil.ObjectToJson(paraMap),
      MediaType.APPLICATION_ALL);
  Response response = _gClient.handle(request);

  Representation result = response.getEntity();
  StringWriter sw = new StringWriter();
  result.write(sw);

  // System.out.println(sw.toString());

  ObjectMapper mapper = new ObjectMapper();
  ZNRecord zn = mapper.readValue(new StringReader(sw.toString()), ZNRecord.class);
  AssertJUnit.assertTrue(zn.getListField("clusters").contains(clusterName));

}
 
Example #18
Source File: ProjectResource.java    From scava with 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 #19
Source File: EntityResource.java    From attic-polygene-java with Apache License 2.0 5 votes vote down vote up
public EntityResource()
{
    // Define the supported variant.
    getVariants().addAll( Arrays.asList(
        new Variant( MediaType.TEXT_HTML ),
        new Variant( MediaType.APPLICATION_RDF_XML ),
        new Variant( MediaType.APPLICATION_JSON ) ) );
    setNegotiated( true );
    setAllowedMethods( Collections.singleton( Method.ALL ) );
}
 
Example #20
Source File: EntityResource.java    From attic-polygene-java with Apache License 2.0 5 votes vote down vote up
private Representation representJson( EntityState entityState )
{
    // TODO This guy needs to represent an Entity as JSON
    if( entityState instanceof JSONEntityState )
    {
        JSONEntityState jsonState = (JSONEntityState) entityState;
        return new StringRepresentation( jsonState.state().toString(), MediaType.APPLICATION_JSON );
    }
    else
    {
        throw new ResourceException( Status.CLIENT_ERROR_NOT_ACCEPTABLE );
    }
}
 
Example #21
Source File: XEBatchSolverSaver.java    From unitime with Apache License 2.0 5 votes vote down vote up
protected XEInterface.RegisterResponse getSchedule(Student student, ClientResource resource) throws IOException {
	try {
		resource.get(MediaType.APPLICATION_JSON);
	} catch (ResourceException e) {
		handleError(resource, e);
	}
	
	List<XEInterface.RegisterResponse> current = new GsonRepresentation<List<XEInterface.RegisterResponse>>(resource.getResponseEntity(), XEInterface.RegisterResponse.TYPE_LIST).getObject();
	XEInterface.RegisterResponse original = null;
    if (current != null && !current.isEmpty())
    	original = current.get(0);
    
    if (original == null || !original.validStudent) {
    	String reason = null;
    	if (original != null && original.failureReasons != null) {
    		for (String m: original.failureReasons) {
    			if ("Holds prevent registration.".equals(m) && iHoldPassword != null && !iHoldPassword.isEmpty())
    				return getHoldSchedule(student, resource);
    			if ("Invalid or undefined Enrollment Status or date range invalid.".equals(m) && iRegistrationDate != null && !iRegistrationDate.isEmpty())
    				return getHoldSchedule(student, resource);
    			if (m != null) reason = m;
	    	}	
    	}
    	if (reason != null) throw new SectioningException(reason);
    	throw new SectioningException("Failed to check student registration status.");
    }
    
    return original;
}
 
Example #22
Source File: ProjectEditionResource.java    From scava with 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 #23
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 #24
Source File: TopicManagementRestletResource.java    From uReplicator with Apache License 2.0 5 votes vote down vote up
public TopicManagementRestletResource() {
  getVariants().add(new Variant(MediaType.TEXT_PLAIN));
  getVariants().add(new Variant(MediaType.APPLICATION_JSON));
  setNegotiated(false);

  _conf = (ManagerConf) getApplication().getContext().getAttributes()
      .get(ManagerConf.class.toString());
  _helixMirrorMakerManager = (ControllerHelixManager) getApplication().getContext()
      .getAttributes().get(ControllerHelixManager.class.toString());
  KafkaClusterValidationManager kafkaValidationManager = (KafkaClusterValidationManager) getApplication()
      .getContext().getAttributes().get(KafkaClusterValidationManager.class.toString());
  _clusterToObserverMap = kafkaValidationManager.getClusterToObserverMap();
}
 
Example #25
Source File: AnalysisTaskPushOnWorkerResource.java    From scava with Eclipse Public License 2.0 5 votes vote down vote up
@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 #26
Source File: ConstraintResource.java    From helix with Apache License 2.0 5 votes vote down vote up
/**
 * Set constraints
 * <p>
 * Usage:
 * <code>curl -d 'jsonParameters={"constraintAttributes":"RESOURCE={resource},CONSTRAINT_VALUE={1}"}'
 * -H "Content-Type: application/json" http://{host:port}/clusters/{cluster}/constraints/MESSAGE_CONSTRAINT/{constraintId}
 */
@Override
public Representation post(Representation entity) {
  String clusterName =
      ResourceUtil.getAttributeFromRequest(getRequest(), ResourceUtil.RequestKey.CLUSTER_NAME);
  String constraintTypeStr =
      ResourceUtil.getAttributeFromRequest(getRequest(), ResourceUtil.RequestKey.CONSTRAINT_TYPE);
  String constraintId =
      ResourceUtil.getAttributeFromRequest(getRequest(), ResourceUtil.RequestKey.CONSTRAINT_ID);

  try {
    ZkClient zkClient =
        ResourceUtil.getAttributeFromCtx(getContext(), ResourceUtil.ContextKey.ZKCLIENT);
    ClusterSetup setupTool = new ClusterSetup(zkClient);
    JsonParameters jsonParameters = new JsonParameters(entity);

    String constraintAttrStr = jsonParameters.getParameter(JsonParameters.CONSTRAINT_ATTRIBUTES);
    setupTool.setConstraint(clusterName, constraintTypeStr, constraintId, constraintAttrStr);

  } catch (Exception e) {
    LOG.error("Error in posting " + entity, e);
    getResponse().setEntity(ClusterRepresentationUtil.getErrorAsJsonStringFromException(e),
        MediaType.APPLICATION_JSON);
    getResponse().setStatus(Status.SUCCESS_OK);
  }
  return null;
}
 
Example #27
Source File: ControllerResource.java    From helix with Apache License 2.0 5 votes vote down vote up
/**
 * Enable/disable Helix controller
 * <p>
 * Usage:
 * <code>curl -d 'jsonParameters={"command":"enableCluster","enabled":"{true/false}"}'
 * -H "Content-Type: application/json" http://{host:port}/clusters/{cluster}/Controller
 */
@Override
public Representation post(Representation entity) {
  try {
    String clusterName =
        ResourceUtil.getAttributeFromRequest(getRequest(), ResourceUtil.RequestKey.CLUSTER_NAME);
    ZkClient zkClient =
        ResourceUtil.getAttributeFromCtx(getContext(), ResourceUtil.ContextKey.ZKCLIENT);
    ClusterSetup setupTool = new ClusterSetup(zkClient);

    JsonParameters jsonParameters = new JsonParameters(entity);
    String command = jsonParameters.getCommand();

    if (command == null) {
      throw new HelixException("Could NOT find 'command' in parameterMap: "
          + jsonParameters._parameterMap);
    } else if (command.equalsIgnoreCase(ClusterSetup.enableCluster)) {
      boolean enabled = Boolean.parseBoolean(jsonParameters.getParameter(JsonParameters.ENABLED));

      setupTool.getClusterManagementTool().enableCluster(clusterName, enabled);
    } else {
      throw new HelixException("Unsupported command: " + command + ". Should be one of ["
          + ClusterSetup.enableCluster + "]");
    }

    getResponse().setEntity(getControllerRepresentation(clusterName));
    getResponse().setStatus(Status.SUCCESS_OK);

  } catch (Exception e) {
    getResponse().setEntity(ClusterRepresentationUtil.getErrorAsJsonStringFromException(e),
        MediaType.APPLICATION_JSON);
    getResponse().setStatus(Status.SUCCESS_OK);
  }

  return null;
}
 
Example #28
Source File: JSONResponseReader.java    From attic-polygene-java with Apache License 2.0 5 votes vote down vote up
@Override
public Object readResponse( Response response, Class<?> resultType )
{
    if( response.getEntity().getMediaType().equals( MediaType.APPLICATION_JSON ) )
    {
        if( ValueComposite.class.isAssignableFrom( resultType ) )
        {
            String jsonValue = response.getEntityAsText();
            ValueCompositeType valueType = module.valueDescriptor( resultType.getName() ).valueType();
            return jsonDeserializer.deserialize( module, valueType, jsonValue );
        }
        else if( resultType.equals( Form.class ) )
        {
            try( JsonReader reader = jsonFactories.readerFactory()
                                                  .createReader( response.getEntity().getReader() ) )
            {
                JsonObject jsonObject = reader.readObject();
                Form form = new Form();
                jsonObject.forEach(
                    ( key, value ) ->
                    {
                        String valueString = value.getValueType() == JsonValue.ValueType.STRING
                                             ? ( (JsonString) value ).getString()
                                             : value.toString();
                        form.set( key, valueString );
                    } );
                return form;
            }
            catch( IOException | JsonException e )
            {
                throw new ResourceException( e );
            }
        }
    }
    return null;
}
 
Example #29
Source File: RestClientImpl.java    From concierge with Eclipse Public License 1.0 5 votes vote down vote up
protected RestClientImpl(final URI uri, final boolean useXml) {
	this.baseUri = uri.normalize().resolve("/");
	final String ext = useXml ? MT_XML_EXT : MT_JSON_EXT;
	FRAMEWORK_STARTLEVEL = new MediaType(MT_FRAMEWORK_STARTLEVEL + ext);
	BUNDLE = new MediaType(MT_BUNDLE + ext);
	BUNDLES = new MediaType(MT_BUNDLES + ext);
	BUNDLES_REPRESENTATIONS = new MediaType(MT_BUNDLES_REPRESENTATIONS + ext);
	BUNDLE_STATE = new MediaType(MT_BUNDLE_STATE + ext);
	BUNDLE_HEADER = new MediaType(MT_BUNDLE_HEADER + ext);
	BUNDLE_STARTLEVEL = new MediaType(MT_BUNDLE_STARTLEVEL + ext);
	SERVICE = new MediaType(MT_SERVICE + ext);
	SERVICES = new MediaType(MT_SERVICES + ext);
	SERVICES_REPRESENTATIONS = new MediaType(MT_SERVICES_REPRESENTATIONS + ext);

}
 
Example #30
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;
}