Java Code Examples for org.restlet.data.Status

The following examples show how to use org.restlet.data.Status. 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
/**
 * Update the thing descriptions of objects registered under the Agent.
 * 
 * @param entity Representation of the incoming JSON.
 * 
 */
@Put("json")
public Representation store(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 heavyweightUpdate(entity, logger, config);
}
 
Example 2
@Put("json")
public Representation store(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 lightweightUpdate(entity, logger, config);
}
 
Example 3
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 4
/**
 * Cancel subscription to the channel.
 * 
 * @return statusMessage {@link StatusMessage StatusMessage} with the result of the operation.
 */
@Delete
public Representation remove(Representation entity) {
	String attrOid = getAttribute(ATTR_OID);
	String attrEid = getAttribute(ATTR_EID);
	String callerOid = getRequest().getChallengeResponse().getIdentifier();
	Map<String, String> queryParams = getQuery().getValuesMap();
	
	Logger logger = (Logger) getContext().getAttributes().get(Api.CONTEXT_LOGGER);
	
	if (attrEid == null){
		logger.info("EID: " + attrEid + " Given identifier does not exist.");
		throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, 
				"Invalid identifier.");
	}
	
	String body = getRequestBody(entity, logger);
	
	CommunicationManager communicationManager 
					= (CommunicationManager) getContext().getAttributes().get(Api.CONTEXT_COMMMANAGER);
	
	return new JsonRepresentation(communicationManager.unsubscribeFromEventChannel(callerOid, attrOid, attrEid, 
			queryParams, body).buildMessage().toString());
}
 
Example 5
/**
 * Gets the property value of an available IoT object.
 * 
 * @return Latest property value.
 */
@Get
public Representation represent(Representation entity) {
	String attrOid = getAttribute(ATTR_OID);
	String attrPid = getAttribute(ATTR_PID);
	String callerOid = getRequest().getChallengeResponse().getIdentifier();
	Map<String, String> queryParams = getQuery().getValuesMap();
	
	Logger logger = (Logger) getContext().getAttributes().get(Api.CONTEXT_LOGGER);
	
	if (attrOid == null || attrPid == null){
		logger.info("OID: " + attrOid + " PID: " + attrPid + " Invalid identifier.");
		throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, 
				"Invalid identifier.");
	}
	
	String body = getRequestBody(entity, logger);
	
	return getObjectProperty(callerOid, attrOid, attrPid, body, queryParams);
	
}
 
Example 6
@Test
public void getMethodReturnsSuccessStatus() throws Exception {

  // Rarely used Teapot Code to check.
  final Boolean successStatusIs200 = true;

  final ServiceEnabledCommand operation = mockedOperation(HttpMethod.GET, successStatusIs200);

  classUnderTest = new GeoWaveOperationServiceWrapper(operation, null);
  classUnderTest.setResponse(new Response(null));
  classUnderTest.setRequest(new Request(Method.GET, "foo.bar"));
  classUnderTest.restGet();
  Assert.assertEquals(
      successStatusIs200,
      classUnderTest.getResponse().getStatus().equals(Status.SUCCESS_OK));
}
 
Example 7
/**
 * 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 8
Source Project: FoxBPM   Source File: FoxbpmStatusService.java    License: Apache License 2.0 6 votes vote down vote up
public Status getStatus(Throwable throwable, Request request, Response response) {
	Status status = null;
	if (throwable instanceof JsonMappingException && throwable.getCause() != null) {
		status = getSpecificStatus(throwable.getCause(), request, response);
	}
	if (status == null) {
		Throwable causeThrowable = null;
		if (throwable.getCause() != null && throwable.getCause() instanceof FoxBPMException) {
			causeThrowable = throwable.getCause();
		} else {
			causeThrowable = throwable;
		}
		status = getSpecificStatus(causeThrowable, request, response);
	}
	return status != null ? status : Status.SERVER_ERROR_INTERNAL;
}
 
Example 9
/**
 * Performs an action on an available IoT object.
 * 
 * @param entity Representation of the incoming JSON.
 * @return A task to perform an action was submitted.
 */
@Post("json")
public Representation accept(Representation entity) {
	String attrOid = getAttribute(ATTR_OID);
	String attrAid = getAttribute(ATTR_AID);
	String callerOid = getRequest().getChallengeResponse().getIdentifier();
	Map<String, String> queryParams = getQuery().getValuesMap();
	
	Logger logger = (Logger) getContext().getAttributes().get(Api.CONTEXT_LOGGER);
	
	if (attrOid == null || attrAid == null){
		logger.info("OID: " + attrOid + " AID: " + attrAid + " Given identifier does not exist.");
		throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, 
				"Given identifier does not exist.");
	}

	String body = getRequestBody(entity, logger);

	return startAction(callerOid, attrOid, attrAid, body, queryParams);
}
 
Example 10
Source Project: container   Source File: ExceptionProcessor.java    License: 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 11
@Test
@Ignore
public void asyncMethodReturnsSuccessStatus() throws Exception {

  // Rarely used Teapot Code to check.
  final Boolean successStatusIs200 = true;

  final ServiceEnabledCommand operation =
      mockedOperation(HttpMethod.POST, successStatusIs200, true);

  classUnderTest = new GeoWaveOperationServiceWrapper(operation, null);
  classUnderTest.setResponse(new Response(null));
  classUnderTest.restPost(null);

  // TODO: Returns 500. Error Caught at
  // "final Context appContext = Application.getCurrent().getContext();"
  Assert.assertEquals(
      successStatusIs200,
      classUnderTest.getResponse().getStatus().equals(Status.SUCCESS_OK));
}
 
Example 12
Source Project: attic-polygene-java   Source File: EntityResource.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected Representation delete( Variant variant )
    throws ResourceException
{
    Usecase usecase = UsecaseBuilder.newUsecase( "Remove entity" );
    EntityStoreUnitOfWork uow = entityStore.newUnitOfWork( module, usecase, SystemTime.now() );
    try
    {
        EntityReference reference = EntityReference.create( identity );
        uow.entityStateOf( module, reference ).remove();
        uow.applyChanges().commit();
        getResponse().setStatus( Status.SUCCESS_NO_CONTENT );
    }
    catch( EntityNotFoundException e )
    {
        uow.discard();
        getResponse().setStatus( Status.CLIENT_ERROR_NOT_FOUND );
    }

    return new EmptyRepresentation();
}
 
Example 13
Source Project: attic-polygene-java   Source File: ResourceValidity.java    License: Apache License 2.0 6 votes vote down vote up
void checkRequest()
    throws ResourceException
{
    // Check command rules
    Instant unmodifiedSince = request.getConditions().getUnmodifiedSince().toInstant();
    EntityState state = spi.entityStateOf( entity );
    Instant lastModifiedSeconds = state.lastModified().with(ChronoField.NANO_OF_SECOND, 0 );
    if( unmodifiedSince != null )
    {
        if( lastModifiedSeconds.isAfter( unmodifiedSince ) )
        {
            throw new ResourceException( Status.CLIENT_ERROR_CONFLICT );
        }
    }

    // Check query rules
    Instant modifiedSince = request.getConditions().getModifiedSince().toInstant();
    if( modifiedSince != null )
    {
        if( !lastModifiedSeconds.isAfter( modifiedSince ) )
        {
            throw new ResourceException( Status.REDIRECTION_NOT_MODIFIED );
        }
    }
}
 
Example 14
@Override
public Representation put(final Representation r,
		final Variant variant) {
	try {
		final FrameworkStartLevelPojo sl = fromRepresentation(r, r.getMediaType());
		final FrameworkStartLevel fsl = getFrameworkStartLevel();

		if (sl.getStartLevel() != 0) {
			fsl.setStartLevel(sl.getStartLevel());
		}
		if (sl.getInitialBundleStartLevel() != 0) {
			fsl.setInitialBundleStartLevel(sl.getInitialBundleStartLevel());
		}

		return SUCCESS(Status.SUCCESS_NO_CONTENT);
	} catch (final Exception e) {
		return ERROR(e, variant);
	}
}
 
Example 15
Source Project: ontopia   Source File: IndexResource.java    License: Apache License 2.0 6 votes vote down vote up
protected Collection<?> getOccurrences(String value, String datatype) {
	OccurrenceIndexIF index = getIndex(OccurrenceIndexIF.class);
	
	try {
		switch (getAttribute("type").toUpperCase()) {
			case "VALUE":
				if (datatype == null) return index.getOccurrences(value);
				else return index.getOccurrences(value, new URILocator(datatype));
			case "PREFIX":
				if (value == null) throw OntopiaRestErrors.MANDATORY_ATTRIBUTE_IS_NULL.build("value", "String");
				if (datatype == null) return index.getOccurrencesByPrefix(value);
				else return index.getOccurrencesByPrefix(value, new URILocator(datatype));
			case "GTE": return IteratorUtils.toList(index.getValuesGreaterThanOrEqual(value));
			case "LTE": return IteratorUtils.toList(index.getValuesSmallerThanOrEqual(value));

			default: 
				setStatus(Status.CLIENT_ERROR_NOT_FOUND, TYPE_ERROR_MESSAGE);
				return null;
		}
	} catch (MalformedURLException mufe) {
		throw OntopiaRestErrors.MALFORMED_LOCATOR.build(mufe, datatype);
	}
}
 
Example 16
Source Project: ontopia   Source File: ScopesResource.java    License: Apache License 2.0 6 votes vote down vote up
@Get
public Collection<TopicIF> getScopes() {
	addMixInAnnotations(TopicIF.class, MFlatTopic.class);

	ScopeIndexIF index = getIndex(ScopeIndexIF.class);

	switch (getAttribute("type").toUpperCase()) {
		case "ASSOCIATIONS": return index.getAssociationThemes();
		case "OCCURRENCES": return index.getOccurrenceThemes();
		case "NAMES": return index.getTopicNameThemes();
		case "VARIANTS": return index.getVariantThemes();
		default:
			setStatus(Status.CLIENT_ERROR_NOT_FOUND, "Expected type one of associations, occurrences, names, variants");
			return null;
	}
}
 
Example 17
Source Project: FoxBPM   Source File: DeploymentResource.java    License: Apache License 2.0 6 votes vote down vote up
@Put
public String update(Representation entity){
	
	String deploymentId = getAttribute("deploymentId");
	InputStream input = null;
	try {
		input = entity.getStream();
		if(input == null){
			throw new FoxbpmPluginException("请求中必须包含文件流", "Rest服务");
		}
		ModelService modelService = FoxBpmUtil.getProcessEngine().getModelService();
		DeploymentBuilder deploymentBuilder = modelService.createDeployment();
		ZipInputStream zip = new ZipInputStream(input);
		deploymentBuilder.updateDeploymentId(deploymentId);
		deploymentBuilder.addZipInputStream(zip);
		deploymentBuilder.deploy();
		setStatus(Status.SUCCESS_OK);
	} catch (Exception e) {
		if (e instanceof FoxBPMException) {
			throw (FoxBPMException) e;
		}
		throw new FoxBPMException(e.getMessage(), e);
	}
	
	return "SUCCESS";
}
 
Example 18
@Get
public Map<String, Map<String, OFFlowMod>> ListStaticFlowEntries() {
    IStaticFlowEntryPusherService sfpService =
            (IStaticFlowEntryPusherService)getContext().getAttributes().
                get(IStaticFlowEntryPusherService.class.getCanonicalName());
    
    String param = (String) getRequestAttributes().get("switch");
    if (log.isDebugEnabled())
        log.debug("Listing all static flow entires for switch: " + param);
    
    if (param.toLowerCase().equals("all")) {
        return sfpService.getFlows();
    } else {
        try {
            Map<String, Map<String, OFFlowMod>> retMap = 
                    new HashMap<String, Map<String, OFFlowMod>>();
            retMap.put(param, sfpService.getFlows(param));
            return retMap;
            
        } catch (NumberFormatException e){
            setStatus(Status.CLIENT_ERROR_BAD_REQUEST, 
                      ControllerSwitchesResource.DPID_ERROR);
        }
    }
    return null;
}
 
Example 19
@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 20
@Get
public void ClearStaticFlowEntries() {
    IStaticFlowEntryPusherService sfpService =
            (IStaticFlowEntryPusherService)getContext().getAttributes().
                get(IStaticFlowEntryPusherService.class.getCanonicalName());
    
    String param = (String) getRequestAttributes().get("switch");
    if (log.isDebugEnabled())
        log.debug("Clearing all static flow entires for switch: " + param);
    
    if (param.toLowerCase().equals("all")) {
        sfpService.deleteAllFlows();
    } else {
        try {
            sfpService.deleteFlowsForSwitch(HexString.toLong(param));
        } catch (NumberFormatException e){
            setStatus(Status.CLIENT_ERROR_BAD_REQUEST, 
                      ControllerSwitchesResource.DPID_ERROR);
            return;
        }
    }
}
 
Example 21
@Get("json")
public String retrieve() {
    IPktInProcessingTimeService pktinProcTime = 
            (IPktInProcessingTimeService)getContext().getAttributes().
                get(IPktInProcessingTimeService.class.getCanonicalName());
    
    String param = ((String)getRequestAttributes().get("perfmonstate")).toLowerCase();
    if (param.equals("reset")) {
    	// We cannot reset something that is disabled, so enable it first.
    	if(!pktinProcTime.isEnabled()){
    		pktinProcTime.setEnabled(true);
    	}
        pktinProcTime.getCtb().reset();
    } else {
        if (param.equals("enable") || param.equals("true")) {
            pktinProcTime.setEnabled(true);
        } else if (param.equals("disable") || param.equals("false")) {
            pktinProcTime.setEnabled(false);
        }
    }
    setStatus(Status.SUCCESS_OK, "OK");
    return "{ \"enabled\" : " + pktinProcTime.isEnabled() + " }";
}
 
Example 22
Source Project: attic-polygene-java   Source File: RootResource.java    License: Apache License 2.0 6 votes vote down vote up
@SubResource
public void administration()
{
    ChallengeResponse challenge = Request.getCurrent().getChallengeResponse();
    if( challenge == null )
    {
        Response.getCurrent()
            .setChallengeRequests( Collections.singletonList( new ChallengeRequest( ChallengeScheme.HTTP_BASIC, "Forum" ) ) );
        throw new ResourceException( Status.CLIENT_ERROR_UNAUTHORIZED );
    }

    User user = select( Users.class, Users.USERS_ID ).userNamed( challenge.getIdentifier() );
    if( user == null || !user.isCorrectPassword( new String( challenge.getSecret() ) ) )
    {
        throw new ResourceException( Status.CLIENT_ERROR_UNAUTHORIZED );
    }

    current().select( user );

    subResource( AdministrationResource.class );
}
 
Example 23
Source Project: lucene-solr   Source File: RestManager.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Locates the RestManager using ThreadLocal SolrRequestInfo.
 */
public static RestManager getRestManager(SolrRequestInfo solrRequestInfo) {
  if (solrRequestInfo == null)
    throw new ResourceException(Status.SERVER_ERROR_INTERNAL, 
        "No SolrRequestInfo in this Thread!");

  SolrQueryRequest req = solrRequestInfo.getReq();
  RestManager restManager = 
      (req != null) ? req.getCore().getRestManager() : null;
  
  if (restManager == null)
    throw new ResourceException(Status.SERVER_ERROR_INTERNAL, 
        "No RestManager found!");
  
  return restManager;
}
 
Example 24
Source Project: helix   Source File: InstanceResource.java    License: 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 25
Source Project: lucene-solr   Source File: RestManager.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void doGet(BaseSolrResource endpoint, String childId) {
  
  // filter results by /schema or /config
  String path = ManagedEndpoint.resolveResourceId(endpoint.getRequest());
  Matcher resourceIdMatcher = resourceIdRegex.matcher(path);
  if (!resourceIdMatcher.matches()) {
    // extremely unlikely but didn't want to squelch it either
    throw new ResourceException(Status.SERVER_ERROR_NOT_IMPLEMENTED, path);
  }
  
  String filter = resourceIdMatcher.group(1);
        
  List<Map<String,String>> regList = new ArrayList<>();
  for (ManagedResourceRegistration reg : restManager.registry.getRegistered()) {
    if (!reg.resourceId.startsWith(filter))
      continue; // doesn't match filter
    
    if (RestManagerManagedResource.class.isAssignableFrom(reg.implClass))
      continue; // internal, no need to expose to outside
    
    regList.add(reg.getInfo());          
  }
  
  endpoint.getSolrResponse().add("managedResources", regList);      
}
 
Example 26
@Get("json")
public CumulativeTimeBucket handleApiQuery() {        
    IPktInProcessingTimeService pktinProcTime = 
        (IPktInProcessingTimeService)getContext().getAttributes().
            get(IPktInProcessingTimeService.class.getCanonicalName());
    
    setStatus(Status.SUCCESS_OK, "OK");
    // If the user is requesting this they must think that it is enabled, 
    // so lets enable it to prevent from erroring out
    if (!pktinProcTime.isEnabled()){
    	pktinProcTime.setEnabled(true);
    	logger.warn("Requesting performance monitor data when performance monitor is disabled. Turning it on");
    }
    // Allocate output object
    if (pktinProcTime.isEnabled()) {
        CumulativeTimeBucket ctb = pktinProcTime.getCtb();
        ctb.computeAverages();
        return ctb;
    }
    
    return null;
}
 
Example 27
@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 28
Source Project: attic-polygene-java   Source File: ContextResource.java    License: Apache License 2.0 5 votes vote down vote up
protected void selectFromList( List<?> list, String indexString )
{
    Integer index = Integer.decode( indexString );

    if( index < 0 || index >= list.size() )
    {
        throw new ResourceException( Status.CLIENT_ERROR_NOT_FOUND );
    }

    current().select( index );

    Object value = list.get( index );
    current().select( value );
}
 
Example 29
Source Project: lucene-solr   Source File: RestManager.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new ManagedResource in the RestManager.
 */
@SuppressWarnings("unchecked")
@Override
public synchronized void doPut(BaseSolrResource endpoint, Representation entity, Object json) {      
  if (json instanceof Map) {
    String resourceId = ManagedEndpoint.resolveResourceId(endpoint.getRequest());
    Map<String,String> info = (Map<String,String>)json;
    info.put("resourceId", resourceId);
    storeManagedData(applyUpdatesToManagedData(json));
  } else {
    throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, 
        "Expected Map to create a new ManagedResource but received a "+json.getClass().getName());
  }          
  // PUT just returns success status code with an empty body
}
 
Example 30
Source Project: concierge   Source File: BundleStateResource.java    License: Eclipse Public License 1.0 5 votes vote down vote up
@Override
public Representation put(final Representation value,
		final Variant variant) {
	try {
		final Bundle bundle = getBundleFromKeys(RestService.BUNDLE_ID_KEY);
		if (bundle == null) {
			setStatus(Status.CLIENT_ERROR_NOT_FOUND);
			return null;
		}

		final BundleStatePojo targetState = fromRepresentation(value,
				value.getMediaType());

		if (bundle.getState() == Bundle.UNINSTALLED) {
			return ERROR(Status.CLIENT_ERROR_PRECONDITION_FAILED, "target state "
					+ targetState.getState() + " not reachable from the current state");
		} else if (targetState.getState() == Bundle.ACTIVE) {
			bundle.start(targetState.getOptions());
			return getRepresentation(
					new BundleStatePojo(bundle.getState()), variant);
		} else if (targetState.getState() == Bundle.RESOLVED) {
			bundle.stop(targetState.getOptions());
			return getRepresentation(
					new BundleStatePojo(bundle.getState()), variant);
		} else {
			return ERROR(Status.CLIENT_ERROR_BAD_REQUEST, "target state "
					+ targetState.getState() + " not supported");
		}
	} catch (final Exception e) {
		return ERROR(e, variant);
	}
}