Java Code Examples for org.restlet.resource.ResourceException

The following are top voted examples for showing how to use org.restlet.resource.ResourceException. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: bigstreams   File: CountCommand.java   Source Code and License 6 votes vote down vote up
/**
 * Helper method that will call the Rest server via localhost only at
 * http://localhost:$monitor.port/files/count/$status
 * 
 * @param status may be null or not
 * @return
 * @throws ResourceException
 * @throws IOException
 */
private long getFilesHttp(FileTrackingStatus.STATUS status) throws ResourceException, IOException {

	int clientPort = configuration.getInt(AgentProperties.MONITORING_PORT,
			8040);

	LOG.info("Connecting client to " + clientPort);

	String querySuffix = (status == null ) ? "/files/count" : "/files/count/" + status.toString().toUpperCase(); 
	ClientResource clientResource = new ClientResource("http://localhost:"
			+ clientPort + querySuffix);

	StringWriter writer = new StringWriter();
	Long count = 0L;
	
	try {
		clientResource.get(MediaType.APPLICATION_JSON).write(writer);
		count = Long.valueOf(writer.toString());
	} finally {
		clientResource.release();
	}

	return count;
}
 
Example 2
Project: bigstreams   File: CountCommand.java   Source Code and License 6 votes vote down vote up
/**
 * Helper method that will call the Rest server via localhost only at
 * 
 * @param querySuffix
 * @return
 * @throws ResourceException
 * @throws IOException
 */
private long getFilesHttp(String querySuffix) throws ResourceException,
		IOException {

	int clientPort = configuration.getInt(
			CoordinationProperties.PROP.COORDINATION_PORT.toString(),
			(Integer) CoordinationProperties.PROP.COORDINATION_PORT
					.getDefaultValue());

	LOG.info("Connecting client to " + clientPort);

	ClientResource clientResource = new ClientResource("http://localhost:"
			+ clientPort + querySuffix);

	StringWriter writer = new StringWriter();

	try {
		clientResource.get(MediaType.APPLICATION_JSON).write(writer);
	} finally {
		clientResource.release();
	}

	return Long.valueOf(writer.toString());
}
 
Example 3
Project: restlet-framework   File: DirectoryServerResource.java   Source Code and License 6 votes vote down vote up
@Override
public Representation put(Representation entity) throws ResourceException {
    if (!this.directory.isModifiable()) {
        setStatus(Status.CLIENT_ERROR_METHOD_NOT_ALLOWED, "The directory is not modifiable.");
        return null;
    }

    // Transfer of PUT calls is only allowed if the readOnly flag is not set.
    Request contextRequest = new Request(Method.PUT, this.targetUri);

    // Add support of partial PUT calls.
    contextRequest.getRanges().addAll(getRanges());
    contextRequest.setEntity(entity);
    Response contextResponse = new Response(contextRequest);
    contextRequest.setResourceRef(this.targetUri);
    getClientDispatcher().handle(contextRequest, contextResponse);
    setStatus(contextResponse.getStatus());

    return null;
}
 
Example 4
Project: search   File: RestManager.java   Source Code and License 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 5
Project: polygene-java   File: ResourceValidity.java   Source Code and License 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 6
Project: polygene-java   File: EntityResource.java   Source Code and License 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 7
Project: polygene-java   File: EntityResource.java   Source Code and License 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 8
Project: polygene-java   File: EntitiesResource.java   Source Code and License 6 votes vote down vote up
@Override
protected Representation get( Variant variant )
    throws ResourceException
{
    // Generate the right representation according to its media type.
    if( MediaType.APPLICATION_JSON.equals( variant.getMediaType() ) )
    {
        return representJson();
    }
    else if( MediaType.APPLICATION_RDF_XML.equals( variant.getMediaType() ) )
    {
        return representRdf();
    }
    else if( MediaType.TEXT_HTML.equals( variant.getMediaType() ) )
    {
        return representHtml();
    }
    else if( MediaType.APPLICATION_ATOM.equals( variant.getMediaType() ) )
    {
        return representAtom();
    }

    throw new ResourceException( Status.CLIENT_ERROR_NOT_FOUND );
}
 
Example 9
Project: polygene-java   File: EntitiesResource.java   Source Code and License 6 votes vote down vote up
private Representation representJson()
    throws ResourceException
{
    try
    {
        final Iterable<EntityReference> query = entityFinder.findEntities( EntityComposite.class, null, null, null, null, Collections.emptyMap() )
                                                            .collect( toList() );
        return new OutputRepresentation( MediaType.APPLICATION_JSON )
        {
            @Override
            public void write( OutputStream outputStream )
                throws IOException
            {
                stateSerialization.serialize( new OutputStreamWriter( outputStream ), query );
            }
        };
    }
    catch( Exception e )
    {
        throw new ResourceException( e );
    }
}
 
Example 10
Project: polygene-java   File: EntitiesResource.java   Source Code and License 6 votes vote down vote up
@Override
protected Representation post( Representation entity, Variant variant )
    throws ResourceException
{
    try
    {
        /*
         * InputStream in = entity.getStream(); ObjectInputStream oin = new ObjectInputStream( in ); String reference
         * = oin.readUTF(); Usecase usecase = (Usecase) oin.readUnshared(); MetaInfo unitofwork = (MetaInfo)
         * oin.readUnshared(); Iterable<UnitOfWorkEvent> events = (Iterable<UnitOfWorkEvent>) oin.readUnshared();
         *
         * // Store state try { entityStore.apply( reference, events, usecase, unitofwork ).commit(); } catch(
         * ConcurrentEntityStateModificationException e ) { throw new ResourceException(
         * Status.CLIENT_ERROR_CONFLICT ); }
         */
    }
    catch( Exception e )
    {
        throw new ResourceException( e );
    }

    return new EmptyRepresentation();
}
 
Example 11
Project: polygene-java   File: IndexResource.java   Source Code and License 6 votes vote down vote up
@Override
public Representation get( Variant variant )
    throws ResourceException
{
    if( variant.getMediaType().equals( MediaType.APPLICATION_RDF_XML ) )
    {
        return new RdfXmlOutputRepresentation();
    }
    else if( variant.getMediaType().equals( MediaType.APPLICATION_RDF_TRIG ) )
    {
        return new RdfTrigOutputRepresentation( MediaType.APPLICATION_RDF_TRIG );
    }
    else if( variant.getMediaType().equals( MediaType.TEXT_PLAIN ) )
    {
        return new RdfTrigOutputRepresentation( MediaType.TEXT_PLAIN );
    }

    return null;
}
 
Example 12
Project: polygene-java   File: FormRequestWriter.java   Source Code and License 6 votes vote down vote up
@Override
public boolean writeRequest(Object requestObject, Request request) throws ResourceException
{
   if (requestObject instanceof Form)
   {
      // Form as query parameters
      if (request.getMethod().equals(Method.GET))
         request.getResourceRef().setQuery(((Form)requestObject).getQueryString());
      else
         request.setEntity(((Form)requestObject).getWebRepresentation(CharacterSet.UTF_8));

      return true;
   }

   return false;
}
 
Example 13
Project: polygene-java   File: DefaultResponseReader.java   Source Code and License 6 votes vote down vote up
@Override
public Object readResponse( Response response, Class<?> resultType ) throws ResourceException
{
    if( MediaType.APPLICATION_JSON.equals( response.getEntity().getMediaType() ) )
    {
        if( resultType.equals( String.class ) || Number.class.isAssignableFrom( resultType ) )
        {
            try
            {
                return jsonDeserializer.deserialize( module, resultType, response.getEntityAsText() );
            }
            catch( Exception e )
            {
                throw new ResourceException( e );
            }
        }
    }
    return null;
}
 
Example 14
Project: polygene-java   File: RequestWriterDelegator.java   Source Code and License 6 votes vote down vote up
@Override
public boolean writeRequest(Object requestObject, Request request) throws ResourceException
{
   if (requestObject == null)
   {
      if (!Method.GET.equals(request.getMethod()))
         request.setEntity(new EmptyRepresentation());

      return true;
   }

   if (requestObject instanceof Representation)
   {
      request.setEntity((Representation) requestObject);
      return true;
   }

   for (RequestWriter requestWriter : requestWriters)
   {
      if (requestWriter.writeRequest(requestObject, request))
         return true;
   }

   return false;
}
 
Example 15
Project: search   File: RestManager.java   Source Code and License 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 16
Project: cyclops-udr   File: CloudStackUsage.java   Source Code and License 6 votes vote down vote up
@Get
public String getUsageRecordsForUser() {
    counter.increment(endpoint);

    // check whether we have userid
    if (userId == null || userId.isEmpty()) {
        logger.error("Trying to get Usage Records for user, but userid is not provided");
        throw new ResourceException(500);
    } else {
        logger.trace("Accessing usage records for user: " + userId);
    }

    // first step is to know which meters are selected
    List<String> meterSelection = getEnabledMeterList();

    // now load all usage records for selected user
    UsageList data = retrieveUsageRecordsForUser(userId, getQueryValue("from"), getQueryValue("to"), meterSelection);

    // finally, return JSON representation of data object
    return new Gson().toJson(data);
}
 
Example 17
Project: fiware-iot-discovery-ngsi9   File: Resource03_AvailabilitySubscription.java   Source Code and License 6 votes vote down vote up
public Representation subscribeDescription(Representation entity, String acceptType) throws ResourceException, IOException, JAXBException {

        //read NGSI description
        InputStream description = new ByteArrayInputStream(entity.getText().getBytes());
//        String contentType = entity.getMediaType().getSubType();
//        System.out.println("Content-Type is: " + contentType);
//        System.out.println("Accept: " + acceptType);

        //register description
        StringRepresentation subRespMsg = null;
//        if (contentType.equalsIgnoreCase(MediaType.APPLICATION_JSON.getSubType())) {
            //if request payload is JSON
            subRespMsg = subscribeJsonHandler(description, acceptType);
//        } else {
//            //request payload is XML
//            subRespMsg = subscribeXmlHandler(description, acceptType);
//        }

//        System.out.println("Respose To Send: \n" + regRespMsg.getText() + "\n");
        return subRespMsg;
    }
 
Example 18
Project: fiware-iot-discovery-ngsi9   File: Resource05_AvailabilitySubscriptionDeletion.java   Source Code and License 6 votes vote down vote up
public Representation unsubscribeToDescription(Representation entity, String acceptType) throws ResourceException, IOException, JAXBException {

        //read NGSI description
        InputStream description = new ByteArrayInputStream(entity.getText().getBytes());
        String contentType = entity.getMediaType().getSubType();
//        System.out.println("Content-Type is: " + contentType);
//        System.out.println("Accept: " + acceptType);

        //update subscription
        StringRepresentation updSubRespMsg = null;
//        if (contentType.equalsIgnoreCase(MediaType.APPLICATION_JSON.getSubType())) {
            //if request payload is JSON
            updSubRespMsg = unsubscribeJsonHandler(description, acceptType);
//        } else {
//            //request payload is XML
//            updSubRespMsg = unsubscribeXmlHandler(description, acceptType);
//        }

//        System.out.println("Respose To Send: \n" + regRespMsg.getText() + "\n");
        return updSubRespMsg;
    }
 
Example 19
Project: fiware-iot-discovery-ngsi9   File: Resource02_Discovery.java   Source Code and License 6 votes vote down vote up
@Post
public Representation handlePost(Representation entity) throws ResourceException, IOException {

    String acceptType = "";
    int atSize = 0;
    try {
        atSize = getClientInfo().getAcceptedMediaTypes().size();
    } catch (NullPointerException npe) {
        npe.printStackTrace();
    }
    if (atSize > 0) {
        acceptType = getClientInfo().getAcceptedMediaTypes().get(0).getMetadata().getSubType();
    }
    Representation rt = discoverDescription(entity, acceptType);
    return rt;
}
 
Example 20
Project: fiware-iot-discovery-ngsi9   File: Resource02_Discovery.java   Source Code and License 6 votes vote down vote up
public Representation discoverDescription(Representation entity, String acceptType) throws ResourceException, IOException {

        //get NGSI discovery request
        InputStream discoveryReq = new ByteArrayInputStream(entity.getText().getBytes());

        StringRepresentation discRespMsg;//= null;
//        String contentType = entity.getMediaType().getSubType();
//        System.out.println("Content-Type is: " + contentType);
//        System.out.println("Accept: " + acceptType);
//        if (contentType.equalsIgnoreCase(MediaType.APPLICATION_JSON.getSubType())) {
            //if request payload is JSON
            discRespMsg = discoveryJsonHandler(discoveryReq, acceptType);
//        } else {
//            discRespMsg = discoveryJsonHandler(discoveryReq, acceptType);
//        }

//        System.out.println("Respose To Send: \n" + discRespMsg.getText() + "\n");
        return discRespMsg;
    }
 
Example 21
Project: search   File: BaseFieldResource.java   Source Code and License 6 votes vote down vote up
/**
 * Pulls the "fl" param from the request and splits it to get the
 * requested list of fields.  The (Dynamic)FieldCollectionResource classes
 * will then restrict the fields sent back in the response to those
 * on this list.  The (Dynamic)FieldResource classes ignore this list, 
 * since the (dynamic) field is specified in the URL path, rather than
 * in a query parameter.
 * <p/>
 * Also pulls the "showDefaults" param from the request, for use by all
 * subclasses to include default values from the associated field type
 * in the response.  By default this param is off.
 */
@Override
public void doInit() throws ResourceException {
  super.doInit();
  if (isExisting()) {
    String flParam = getSolrRequest().getParams().get(CommonParams.FL);
    if (null != flParam) {
      String[] fields = flParam.trim().split("[,\\s]+");
      if (fields.length > 0) {
        requestedFields = new LinkedHashSet<>();
        for (String field : fields) {
          if ( ! field.trim().isEmpty()) {
            requestedFields.add(field.trim());
          }
        }
      }
    }
    showDefaults = getSolrRequest().getParams().getBool(SHOW_DEFAULTS, false);
  }
}
 
Example 22
Project: prudence   File: ResolvingRedirector.java   Source Code and License 6 votes vote down vote up
/**
 * Throw an exception if there is a recursive server-side redirect.
 * 
 * @param targetRef
 *        The target reference
 * @param request
 *        The request
 * @param response
 *        The response
 */
private void validateNotRecursiveServerRedirect( Reference targetRef, Request request, Response response )
{
	@SuppressWarnings("unchecked")
	Set<String> serverRedirectHistory = (Set<String>) request.getAttributes().get( SERVER_REDIRECT_HISTORY_ATTRIBUTE );
	if( serverRedirectHistory == null )
	{
		serverRedirectHistory = new HashSet<String>();
		@SuppressWarnings("unchecked")
		Set<String> existing = (Set<String>) request.getAttributes().putIfAbsent( SERVER_REDIRECT_HISTORY_ATTRIBUTE, serverRedirectHistory );
		if( existing != null )
			serverRedirectHistory = existing;
	}

	String targetRefString = targetRef.toString();
	if( serverRedirectHistory.contains( targetRefString ) )
	{
		String message = "Recursive server redirection to " + targetRef;
		getLogger().warning( message );
		throw new ResourceException( Status.SERVER_ERROR_INTERNAL, message );
	}

	serverRedirectHistory.add( targetRefString );
}
 
Example 23
Project: ontopia   File: AbstractResourceTest.java   Source Code and License 6 votes vote down vote up
protected void assertRequestFails(String url, Method method, MediaType preferred, Object object, OntopiaRestErrors expected) {
	OntopiaTestResource cr = new OntopiaTestResource(method, getUrl(url), preferred);
	try {
		cr.request(object, Object.class);
		Assert.fail("Expected Ontopia error " + expected.name() + ", but request succeeded");
	} catch (OntopiaTestResourceException e) {
		Error result = e.getError();
		try {
			Assert.assertNotNull("Expected error, found null", result);
			Assert.assertEquals("Ontopia error code mismatch", expected.getCode(), result.getCode());
			Assert.assertEquals("HTTP status code mismatch", expected.getStatus().getCode(), result.getHttpcode());
			Assert.assertNotNull("Error message is empty", result.getMessage());
		} catch (AssertionError ae) {
			Assert.fail("Expected ontopia error " + expected.name() + 
					", but received [" + result.getHttpcode() + ":" + result.getCode() + ", " + result.getMessage() + "]");
		}
	} catch (ResourceException re) {
		Assert.fail("Expected ontopia error " + expected.name() + 
				", but received [" + re.getStatus().getCode() + ":" + re.getStatus().getDescription() + "]");
	}
}
 
Example 24
Project: prudence   File: ContextualAttributes.java   Source Code and License 6 votes vote down vote up
/**
 * Throws an exception if the document name is invalid. Uses the default
 * given document name if no name is given, and respects
 * {@link #isTrailingSlashRequired()}.
 * 
 * @param documentName
 *        The document name
 * @param defaultDocumentName
 *        The default document name
 * @return The valid document name
 * @throws ResourceException
 */
public String validateDocumentName( String documentName, String defaultDocumentName ) throws ResourceException
{
	if( isTrailingSlashRequired() )
		if( ( documentName != null ) && ( documentName.length() != 0 ) && !documentName.endsWith( "/" ) )
			throw new ResourceException( Status.CLIENT_ERROR_NOT_FOUND );

	if( ( documentName == null ) || ( documentName.length() == 0 ) || ( documentName.equals( "/" ) ) )
	{
		documentName = defaultDocumentName;
		if( isTrailingSlashRequired() && !documentName.endsWith( "/" ) )
			documentName += "/";
	}

	return documentName;
}
 
Example 25
Project: open-rmbt   File: ServerResource.java   Source Code and License 5 votes vote down vote up
@Override
protected void doRelease() throws ResourceException
{
    try
    {
        if (conn != null)
            conn.close();
    }
    catch (final SQLException e)
    {
        e.printStackTrace();
    }
}
 
Example 26
Project: open-rmbt   File: ServerResource.java   Source Code and License 5 votes vote down vote up
@Override
protected void doRelease() throws ResourceException
{
    try
    {
        if (conn != null)
            conn.close();
    }
    catch (final SQLException e)
    {
        e.printStackTrace();
    }
}
 
Example 27
Project: open-rmbt   File: ServerResource.java   Source Code and License 5 votes vote down vote up
@Override
protected void doRelease() throws ResourceException
{
    super.doRelease();
    try
    {
        conn.close();
    }
    catch (final SQLException e)
    {
        e.printStackTrace();
    }
}
 
Example 28
Project: bigstreams   File: FileTrackingStatusResource.java   Source Code and License 5 votes vote down vote up
/**
 * Returns a list of FileTrackingStatus based on the query
 * 
 * @param query
 *            should be a HSQL query URL encoded
 * @return
 * @throws UnsupportedEncodingException
 */
private Collection<FileTrackingStatus> getByQuery(String query)
		throws ResourceException {
	String decodedQuery = null;

	try {
		decodedQuery = URLDecoder.decode(query, "UTF-8");
	} catch (UnsupportedEncodingException e) {
		ResourceException exp = new ResourceException(e);
		exp.setStackTrace(e.getStackTrace());
		throw exp;
	}

	if (decodedQuery == null || decodedQuery.trim().length() < 1) {
		return new ArrayList<FileTrackingStatus>();
	}

	List<Range> ranges = getRanges();

	int from = 0, max = 1000;

	if (ranges != null && ranges.size() > 0) {
		Range range = ranges.get(0);
		from = (int) range.getIndex();
		max = (int) range.getSize();
	}

	return memory.getFiles(decodedQuery, from, max);
}
 
Example 29
Project: bigstreams   File: StatusCommand.java   Source Code and License 5 votes vote down vote up
/**
 * calls the Rest service registerd at localhost:[port]/files/status/{path}
 * 
 * @param path
 * @return
 * @throws ResourceException
 * @throws IOException
 */
private FileTrackingStatus getFileStatusHttp(String path)
		throws ResourceException, IOException {
	int clientPort = configuration.getInt(AgentProperties.MONITORING_PORT,
			8040);

	LOG.info("Connecting client to " + clientPort);

	String absolutePath = path;

	if (!path.startsWith("/")) {
		absolutePath = "/" + path;
	}

	// query the list resource path query for the path
	ClientResource clientResource = new ClientResource("http://localhost:"
			+ clientPort + "/files/status" + absolutePath);

	StringWriter writer = new StringWriter();

	try {
		clientResource.get(MediaType.APPLICATION_JSON).write(writer);
	} finally {
		clientResource.release();
	}

	String content = writer.toString();

	return (content == null || content.trim().length() < 1) ? null
			: fileFormatter.read(FORMAT.JSON, content);

}
 
Example 30
Project: bigstreams   File: LSCommand.java   Source Code and License 5 votes vote down vote up
/**
 * Helper method that will call the Rest server via localhost only at
 * http://localhost:$monitor.port/files/list/$attribute
 * 
 * @param attribute
 * @param from
 * @param max
 * @return
 * @throws ResourceException
 * @throws IOException
 */
private Collection<FileTrackingStatus> getFilesHttp(String attribute,
		int from, int max) throws ResourceException, IOException {

	int clientPort = configuration.getInt(AgentProperties.MONITORING_PORT,
			8040);

	LOG.info("Connecting client to " + clientPort);

	String suffix = "/files/list";
	
	if(attribute != null && attribute.length() > 0){
		
		suffix += "/" + attribute;
		
	}

	ClientResource clientResource = new ClientResource("http://localhost:"
			+ clientPort + suffix);

	
	
	StringWriter writer = new StringWriter();
	if (from > -1) {
		clientResource.setRanges(Arrays.asList(new Range(from, max)));
	}
	try {
		clientResource.get(MediaType.APPLICATION_JSON).write(writer);
	} finally {
		clientResource.release();
	}

	return formatter.readList(FORMAT.JSON,
			new StringReader(writer.toString()));
}
 
Example 31
Project: bigstreams   File: CollectorStatusCommand.java   Source Code and License 5 votes vote down vote up
/**
 * 
 * @return
 * @throws ResourceException
 * @throws IOException
 */
private String getStatusHttp() throws ResourceException, IOException {

	int clientPort = configuration.getInt(
			CollectorProperties.WRITER.COLLECTOR_MON_PORT.toString(),
			(Integer) CollectorProperties.WRITER.COLLECTOR_MON_PORT
					.getDefaultValue());

	LOG.info("Connecting client to " + clientPort);

	ClientResource clientResource = new ClientResource("http://localhost:"
			+ clientPort + "/view/collector/status");

	StringWriter writer = new StringWriter();

	try {
		clientResource.get(MediaType.APPLICATION_JSON).write(writer);
	} catch (ResourceException rexp) {

		rexp.printStackTrace(System.err);

		CollectorStatus status = new CollectorStatusImpl();
		status.setStatus(CollectorStatus.STATUS.SHUTDOWN, rexp.getStatus()
				.toString());

		objMapper.writeValue(writer, status);

	} finally {
		clientResource.release();
	}

	return writer.toString();
}
 
Example 32
Project: bigstreams   File: LSCommand.java   Source Code and License 5 votes vote down vote up
/**
 * Helper method that will call the Rest server via localhost only at
 * and expect a list of string.
 * @param addressPath e.g. /agents/list 
 * @param from
 * @param max
 * @return
 * @throws ResourceExceptionstatus
 * @throws IOException
 */
private <T> Collection<T> getItemNamesHttp(Class<T> cls, String addressPath, int from, int max)
		throws ResourceException, IOException {

	int clientPort = configuration.getInt(
			CoordinationProperties.PROP.COORDINATION_PORT.toString(),
			(Integer) CoordinationProperties.PROP.COORDINATION_PORT
					.getDefaultValue());

	LOG.info("Connecting client to " + clientPort);

	ClientResource clientResource = new ClientResource("http://localhost:"
			+ clientPort + addressPath);

	StringWriter writer = new StringWriter();
	if (from > -1) {
		clientResource.setRanges(Arrays.asList(new Range(from, max)));
	}
	try {
		clientResource.get().write(writer);
	} finally {
		clientResource.release();
	}

	Collection<T> coll = objectMapper.readValue(writer.toString(),
			new TypeReference<Collection<T>>() {
			});

	return coll;
}
 
Example 33
Project: bigstreams   File: LSCommand.java   Source Code and License 5 votes vote down vote up
/**
 * Helper method that will call the Rest server via localhost only at
 * http://localhost:$monitor.port/files/list/$attribute
 * 
 * @param attribute
 * @param from
 * @param max
 * @return
 * @throws ResourceExceptionstatus
 * @throws IOException
 */
private Collection<FileTrackingStatus> getFilesHttp(String attribute,
		int from, int max) throws ResourceException, IOException {

	int clientPort = configuration.getInt(
			CoordinationProperties.PROP.COORDINATION_PORT.toString(),
			(Integer) CoordinationProperties.PROP.COORDINATION_PORT
					.getDefaultValue());

	LOG.info("Connecting client to " + clientPort);

	ClientResource clientResource = new ClientResource("http://localhost:"
			+ clientPort + "/files/list" + attribute);

	StringWriter writer = new StringWriter();
	if (from > -1) {
		clientResource.setRanges(Arrays.asList(new Range(from, max)));
	}
	try {
		clientResource.get(MediaType.APPLICATION_JSON).write(writer);
	} finally {
		clientResource.release();
	}

	return formatter.readList(FORMAT.JSON,
			new StringReader(writer.toString()));
}
 
Example 34
Project: QoS-floodlight   File: CounterResourceBase.java   Source Code and License 5 votes vote down vote up
@Override
protected void doInit() throws ResourceException {
    super.doInit();
    counterStore = 
        (ICounterStoreService)getContext().getAttributes().
            get(ICounterStoreService.class.getCanonicalName());
}
 
Example 35
Project: restlet-framework   File: DirectoryServerResource.java   Source Code and License 5 votes vote down vote up
@Override
public Representation delete() throws ResourceException {
    if (!this.directory.isModifiable()) {
        setStatus(Status.CLIENT_ERROR_METHOD_NOT_ALLOWED, "The directory is not modifiable.");
        return null;
    }

    Request contextRequest = new Request(Method.DELETE, this.targetUri);
    Response contextResponse = new Response(contextRequest);

    if (this.directoryTarget && !this.indexTarget) {
        // let the client handle the directory's deletion
        contextRequest.setResourceRef(this.targetUri);
        getClientDispatcher().handle(contextRequest, contextResponse);

        setStatus(contextResponse.getStatus());
        return null;
    }

    ReferenceList references = getVariantsReferences();

    if (references.isEmpty()) {
        // no representation found
        setStatus(Status.CLIENT_ERROR_NOT_FOUND);
    } else if (this.uniqueReference != null) {
        // only one representation
        contextRequest.setResourceRef(this.uniqueReference);
        getClientDispatcher().handle(contextRequest, contextResponse);
        setStatus(contextResponse.getStatus());
    } else {
        // several variants found, but not the right one
        setStatus(Status.CLIENT_ERROR_NOT_ACCEPTABLE,
                "Unable to process properly the request. Several variants exist but none of them suits precisely. ");
    }

    return null;
}
 
Example 36
Project: restlet-framework   File: DirectoryServerResource.java   Source Code and License 5 votes vote down vote up
private ReferenceList tryToConvertAsReferenceList(Representation entity) throws ResourceException {
    try {
        return new ReferenceList(entity);
    } catch (IOException e) {
        throw new ResourceException(e);
    }
}
 
Example 37
Project: restlet-framework   File: DirectoryServerResource.java   Source Code and License 5 votes vote down vote up
/**
 * Prevent the client from accessing resources in upper directories
 */
public void preventUpperDirectoryAccess() {
    String targetUriPath = new Reference(Reference.decode(targetUri))
            .normalize()
            .toString();
    if (!targetUriPath.startsWith(directory.getRootRef().toString())) {
        throw new ResourceException(Status.CLIENT_ERROR_FORBIDDEN);
    }
}
 
Example 38
Project: restlet-framework   File: DirectoryServerResource.java   Source Code and License 5 votes vote down vote up
@Override
protected Representation get() throws ResourceException {
    // Content negotiation has been disabled
    // The variant that may need to meet the request conditions

    List<Variant> variants = getVariants(Method.GET);
    if ((variants == null) || (variants.isEmpty())) {
        // Resource not found
        throw new ResourceException(Status.CLIENT_ERROR_NOT_FOUND);
    }

    if (variants.size() == 1) {
        return (Representation) variants.get(0);
    }

    ReferenceList variantRefs = new ReferenceList();

    for (Variant variant : variants) {
        if (variant.getLocationRef() != null) {
            variantRefs.add(variant.getLocationRef());
        } else {
            getLogger()
                    .warn(
                            "A resource with multiple variants should provide a location for each variant when content negotiation is turned off");
        }
    }

    if (!variantRefs.isEmpty()) {
        // Return the list of variants
        setStatus(Status.REDIRECTION_MULTIPLE_CHOICES);
        return variantRefs.getTextRepresentation();
    }

    throw new ResourceException(Status.CLIENT_ERROR_NOT_FOUND);
}
 
Example 39
Project: restlet-framework   File: StatusService.java   Source Code and License 5 votes vote down vote up
/**
 * Returns a status for a given exception or error. By default it unwraps
 * the status of {@link ResourceException}. For other exceptions or errors,
 * it returns an {@link Status#SERVER_ERROR_INTERNAL} status.<br>
 * <br>
 * In order to customize the default behavior, this method can be
 * overridden.
 * 
 * @param throwable
 *            The exception or error caught.
 * @param request
 *            The request handled.
 * @param response
 *            The response updated.
 * @return The representation of the given status.
 */
public Status toStatus(Throwable throwable, Request request,
        Response response) {
    Status result;

    Status defaultStatus = Status.SERVER_ERROR_INTERNAL;
    Throwable t = throwable;

    // If throwable is a ResourceException, use its status and the cause.
    if (throwable instanceof ResourceException) {
        defaultStatus = ((ResourceException) throwable).getStatus();

        if (throwable.getCause() != null
                && throwable.getCause() != throwable) {
            t = throwable.getCause();
        }
    }

    // look for Status annotation
    org.restlet.engine.resource.ThrowableAnnotationInfo tai = org.restlet.engine.resource.AnnotationUtils
            .getInstance().getThrowableAnnotationInfo(t.getClass());

    if (tai != null) {
        result = new Status(tai.getStatus(), t);
    } else {
        result = new Status(defaultStatus, t);
    }

    return result;
}
 
Example 40
Project: polygene-java   File: ContextResource.java   Source Code and License 5 votes vote down vote up
@Override
public final void handle( Request request, Response response )
{
    ObjectSelection objectSelection = current();

    // Check constraints for this resource
    if( !constraints.isValid( getClass(), objectSelection, module ) )
    {
        throw new ResourceException( Status.CLIENT_ERROR_FORBIDDEN );
    }

    // Find remaining segments
    List<String> segments = getSegments();

    if( segments.size() > 0 )
    {
        String segment = segments.remove( 0 );

        if( segments.size() > 0 )
        {
            handleSubResource( segment );
        }
        else
        {
            handleResource( segment );
        }
    }
}