Java Code Examples for org.restlet.representation.Representation

The following are top voted examples for showing how to use org.restlet.representation.Representation. 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: restlet-framework   File: TemplateRepresentation.java   Source Code and License 6 votes vote down vote up
/**
 * Returns a FreeMarker template from a representation and a configuration.
 * 
 * @param config
 *            The FreeMarker configuration.
 * @param templateRepresentation
 *            The template representation.
 * @return The template or null if not found.
 */
public static Template getTemplate(Configuration config,
        Representation templateRepresentation) {
    try {
        // Instantiate the template with the character set of the template
        // representation if it has been set, otherwise use UTF-8.
        if (templateRepresentation.getCharacterSet() != null) {
            return new Template("template",
                    templateRepresentation.getReader(), config,
                    templateRepresentation.getCharacterSet().getName());
        }

        return new Template("template", templateRepresentation.getReader(),
                config, CharacterSet.UTF_8.getName());
    } catch (IOException e) {
        Context.getCurrentLogger().warn(
                "Unable to get the template from the representation " + templateRepresentation.getLocationRef(), e);
        return null;
    }
}
 
Example 2
Project: sync-android-p2p   File: HttpListener.java   Source Code and License 6 votes vote down vote up
@Get() // @Get is required for both GET and HEAD requests
public Representation handleHeadAndGet() {

    String path = getReference().getPath();
    String dbname = getDatabaseName(path);
    
    if (!dbNameExists(dbname)) {
        return databaseNotFound();
    }
    else if (path.contains("/_local/")) {
        return handleLocalGet(path, dbname);
    }
    else if (path.contains("/_changes/")) {
        return handleChangesGet(path);
    } else {
        if (Method.HEAD.equals(getMethod())) {
            return httpSuccess();
        } else {
            return lastSequence(dbname);
        }
    }
}
 
Example 3
Project: chaperone   File: TopicManagementRestletResource.java   Source Code and License 6 votes vote down vote up
@Override
@Put("json")
public Representation put(Representation entity) {
  try {
    String jsonRequest = entity.getText();
    TopicPartition topicPartitionInfo = TopicPartition.init(jsonRequest);
    if (_autoTopicWhitelistingManager != null) {
      _autoTopicWhitelistingManager.removeFromBlacklist(topicPartitionInfo.getTopic());
    }
    if (_helixMirrorMakerManager.isTopicExisted(topicPartitionInfo.getTopic())) {
      _helixMirrorMakerManager.expandTopicInMirrorMaker(topicPartitionInfo);
      return new StringRepresentation(
          String.format("Successfully expand topic: %s", topicPartitionInfo));
    } else {
      getResponse().setStatus(Status.CLIENT_ERROR_NOT_FOUND);
      return new StringRepresentation(String.format(
          "Failed to expand topic, topic: %s is not existed!", topicPartitionInfo.getTopic()));
    }
  } catch (IOException 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 4
Project: restlet-framework   File: DirectoryServerResource.java   Source Code and License 6 votes vote down vote up
/**
 * Allows to sort the list of representations set by the resource.
 * 
 * @return A Comparator instance imposing a sort order of representations or
 *         null if no special order is wanted.
 */
private Comparator<Representation> getRepresentationsComparator() {
    // Sort the list of representations by their identifier.
    Comparator<Representation> identifiersComparator = new Comparator<Representation>() {
        public int compare(Representation rep0, Representation rep1) {
            boolean bRep0Null = (rep0.getLocationRef() == null);
            boolean bRep1Null = (rep1.getLocationRef() == null);

            if (bRep0Null && bRep1Null) {
                return 0;
            }
            if (bRep0Null) {
                return -1;
            }
            if (bRep1Null) {
                return 1;
            }

            return rep0.getLocationRef().getLastSegment()
                    .compareTo(rep1.getLocationRef().getLastSegment());
        }
    };
    return identifiersComparator;
}
 
Example 5
Project: restlet-framework   File: ServerResource.java   Source Code and License 6 votes vote down vote up
/**
 * Indicates the communication options available for this resource. This
 * method is only invoked if content negotiation has been disabled as
 * indicated by the {@link #isNegotiated()}, otherwise the
 * {@link #options(Variant)} method is invoked.<br>
 * <br>
 * The default behavior is to set the response status to
 * {@link Status#CLIENT_ERROR_METHOD_NOT_ALLOWED}.
 * 
 * @return The optional response entity.
 */
protected Representation options() throws ResourceException {
    Representation result = null;
    MethodAnnotationInfo annotationInfo;

    try {
        annotationInfo = getAnnotation(Method.OPTIONS);

        // Updates the list of allowed methods
        updateAllowedMethods();

        if (annotationInfo != null) {
            result = doHandle(annotationInfo, null);
        } else {
            doError(Status.CLIENT_ERROR_METHOD_NOT_ALLOWED);
        }
    } catch (IOException e) {
        throw new ResourceException(e);
    }

    return result;
}
 
Example 6
Project: restlet-framework   File: Request.java   Source Code and License 6 votes vote down vote up
/**
 * Constructor.
 * 
 * @param method
 *            The call's method.
 * @param resourceRef
 *            The resource reference.
 * @param entity
 *            The entity.
 */
public Request(Method method, Reference resourceRef, Representation entity) {
    super(entity);
    this.accessControlRequestHeaders = null;
    this.accessControlRequestMethod = null;
    this.challengeResponse = null;
    this.clientInfo = null;
    this.conditions = null;
    this.cookies = null;
    this.hostRef = null;
    this.loggable = true;
    this.maxForwards = -1;
    this.method = method;
    this.originalRef = null;
    this.onResponse = null;
    this.proxyChallengeResponse = null;
    this.protocol = null;
    this.ranges = null;
    this.referrerRef = null;
    this.resourceRef = resourceRef;
    this.rootRef = null;
}
 
Example 7
Project: uReplicator   File: TopicManagementRestletResource.java   Source Code and License 6 votes vote down vote up
@Override
@Delete
public Representation delete() {
  final String topicName = (String) getRequest().getAttributes().get("topicName");
  if (_autoTopicWhitelistingManager != null) {
    _autoTopicWhitelistingManager.addIntoBlacklist(topicName);
  }
  if (!_helixMirrorMakerManager.isTopicExisted(topicName)) {
    getResponse().setStatus(Status.CLIENT_ERROR_NOT_FOUND);
    return new StringRepresentation(
        String.format("Failed to delete not existed topic: %s", topicName));
  }
  try {
    _helixMirrorMakerManager.deleteTopicInMirrorMaker(topicName);
    return new StringRepresentation(
        String.format("Successfully finished delete topic: %s", topicName));
  } catch (Exception e) {
    getResponse().setStatus(Status.SERVER_ERROR_INTERNAL);
    LOGGER.error("Failed to delete topic: {}, with exception: {}", topicName, e);
    return new StringRepresentation(
        String.format("Failed to delete topic: %s, with exception: %s", topicName, e));
  }
}
 
Example 8
Project: restlet-framework   File: IoUtils.java   Source Code and License 6 votes vote down vote up
/**
 * Converts the representation to a string value. Be careful when using this
 * method as the conversion of large content to a string fully stored in
 * memory can result in OutOfMemoryErrors being thrown.
 * 
 * @param representation
 *            The representation to convert.
 * @return The representation as a string value.
 */
public static String getText(Representation representation)
        throws IOException {
    String result = null;

    if (representation.isAvailable()) {
        if (representation.getSize() == 0) {
            result = "";
        } else {
            java.io.StringWriter sw = new java.io.StringWriter();
            representation.write(sw);
            sw.flush();
            result = sw.toString();
        }
    }

    return result;
}
 
Example 9
Project: uReplicator   File: ValidationRestletResource.java   Source Code and License 6 votes vote down vote up
@Override
@Get
public Representation get() {
  final String option = (String) getRequest().getAttributes().get("option");
  if ("srcKafka".equals(option)) {
    if (_srcKafkaValidationManager == null) {
      LOGGER.warn("SourceKafkaClusterValidationManager is null!");
      return new StringRepresentation("SrcKafkaValidationManager is not been initialized!");
    }
    LOGGER.info("Trying to call validation on source kafka cluster!");
    return new StringRepresentation(_srcKafkaValidationManager.validateSourceKafkaCluster());
  } else {
    LOGGER.info("Trying to call validation on current cluster!");
    return new StringRepresentation(_validationManager.validateExternalView());
  }
}
 
Example 10
Project: restlet-framework   File: Transformer.java   Source Code and License 6 votes vote down vote up
/**
 * Transforms a source XML representation by applying an XSLT transform
 * sheet to it.
 * 
 * @param source
 *            The source XML representation.
 * @return The generated result representation.
 */
public Representation transform(Representation source) {
    final Representation result = new TransformRepresentation(getContext(),
            source, getTransformSheet());

    if (this.resultLanguages != null) {
        result.getLanguages().addAll(getResultLanguages());
    }

    result.setCharacterSet(getResultCharacterSet());
    if (this.resultEncodings != null) {
        result.getEncodings().addAll(getResultEncodings());
    }

    result.setMediaType(getResultMediaType());
    return result;
}
 
Example 11
Project: restlet-framework   File: XmlRepresentation.java   Source Code and License 6 votes vote down vote up
/**
 * Returns the schema URI for the current schema media type.
 * 
 * @return The schema URI.
 */
private static String getSchemaLanguageUri(
        Representation schemaRepresentation) {
    String result = null;

    if (schemaRepresentation != null) {
        if (MediaType.APPLICATION_W3C_SCHEMA.equals(schemaRepresentation
                .getMediaType())) {
            result = XMLConstants.W3C_XML_SCHEMA_NS_URI;
        } else if (MediaType.APPLICATION_RELAXNG_COMPACT
                .equals(schemaRepresentation.getMediaType())) {
            result = XMLConstants.RELAXNG_NS_URI;
        } else if (MediaType.APPLICATION_RELAXNG_XML
                .equals(schemaRepresentation.getMediaType())) {
            result = XMLConstants.RELAXNG_NS_URI;
        }
    }

    return result;
}
 
Example 12
Project: restlet-framework   File: ConverterUtils.java   Source Code and License 6 votes vote down vote up
/**
 * Returns the best converter helper matching the given parameters.
 * 
 * @param <T>
 *            The target class.
 * @param source
 *            The source representation variant.
 * @param target
 *            The target class.
 * @param resource
 *            The parent resource.
 * @return The matched converter helper or null.
 */
public static <T> ConverterHelper getBestHelper(Representation source,
        Class<T> target, Resource resource) {
    ConverterHelper result = null;
    float bestScore = -1.0F;
    float currentScore;

    for (ConverterHelper ch : Engine.getInstance()
            .getRegisteredConverters()) {
        if (ch != null) {
            currentScore = ch.score(source, target, resource);

            if (currentScore > bestScore) {
                bestScore = currentScore;
                result = ch;
            }
        }
    }

    return result;
}
 
Example 13
Project: chaperone   File: ValidationRestletResource.java   Source Code and License 6 votes vote down vote up
@Override
@Get
public Representation get() {
  final String option = (String) getRequest().getAttributes().get("option");
  if ("srcKafka".equals(option)) {
    if (_srcKafkaValidationManager == null) {
      LOGGER.warn("SourceKafkaClusterValidationManager is null!");
      return new StringRepresentation("SrcKafkaValidationManager is not been initialized!");
    }
    LOGGER.info("Trying to call validation on source kafka cluster!");
    return new StringRepresentation(_srcKafkaValidationManager.validateSourceKafkaCluster());
  } else {
    LOGGER.info("Trying to call validation on current cluster!");
    return new StringRepresentation(_validationManager.validateExternalView());
  }
}
 
Example 14
Project: restlet-framework   File: ClientResource.java   Source Code and License 6 votes vote down vote up
/**
 * Handles the inbound call. Note that only synchronous calls are processed.
 * 
 * @param response
 * @return The response's entity, if any.
 */
public Representation handleInbound(Response response) {
    if (response == null) {
        return null;
    }

    // Verify that the request was synchronous
    if (response.getRequest().isSynchronous()) {
        if (response.getStatus().isError()) {
            doError(response.getStatus());
            return null;
        }
        return response.getEntity();
    }

    return null;
}
 
Example 15
Project: restlet-framework   File: JaxbConverter.java   Source Code and License 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public <T> T toObject(Representation source, Class<T> target,
        Resource resource) throws IOException {
    JaxbRepresentation<?> jaxbSource = null;
    if (source instanceof JaxbRepresentation) {
        jaxbSource = (JaxbRepresentation<?>) source;
    } else {
        jaxbSource = new JaxbRepresentation<T>(source, target);
    }

    T result = null;
    if (target == null) {
        result = (T) jaxbSource.getObject();
    } else if (JaxbRepresentation.class.isAssignableFrom(target)) {
        result = target.cast(jaxbSource);
    } else if (isJaxbRootElementClass(target)) {
        result = target.cast(jaxbSource.getObject());
    }

    return result;
}
 
Example 16
Project: restlet-framework   File: ThymeleafConverter.java   Source Code and License 6 votes vote down vote up
@Override
public Representation toRepresentation(Object source, Variant target,
        Resource resource) throws IOException {

    if (source instanceof TemplateResolution) {
        Locale locale = getLocale(resource);

        TemplateRepresentation tr = new TemplateRepresentation(
                ((TemplateResolution) source).getTemplateResource().getBaseName(), locale,
                target.getMediaType());
        tr.setDataModel(resource.getRequest(), resource.getResponse());
        return tr;
    }

    return null;
}
 
Example 17
Project: restlet-framework   File: LogService.java   Source Code and License 6 votes vote down vote up
/**
 * Starts the log service by attempting to read the log properties if the
 * {@link #getLogPropertiesRef()} returns a non null URI reference.
 */
@Override
public synchronized void start() throws Exception {
    super.start();

    this.responseLogTemplate = (getResponseLogFormat() == null) ? null
            : new Template(getResponseLogFormat());
    if (getLogPropertiesRef() != null) {
        Representation logProperties = new ClientResource(getContext(),
                getLogPropertiesRef()).get();

        if (logProperties != null) {
            java.util.logging.LogManager.getLogManager().readConfiguration(
                    logProperties.getStream());
        }
    }
}
 
Example 18
Project: restlet-framework   File: GsonConverter.java   Source Code and License 6 votes vote down vote up
@Override
public <T> float score(Representation source, Class<T> target,
        Resource resource) {
    float result = -1.0F;

    if (source instanceof GsonRepresentation<?>) {
        result = 1.0F;
    } else if ((target != null)
            && GsonRepresentation.class.isAssignableFrom(target)) {
        result = 1.0F;
    } else if (VARIANT_JSON.isCompatible(source)) {
        result = 0.8F;
    }

    return result;
}
 
Example 19
Project: restlet-framework   File: GsonConverter.java   Source Code and License 6 votes vote down vote up
@Override
public Representation toRepresentation(Object source, Variant target,
        Resource resource) throws IOException {
    Representation result = null;

    if (source instanceof GsonRepresentation) {
        result = (GsonRepresentation<?>) source;
    } else {
        if (target.getMediaType() == null) {
            target.setMediaType(MediaType.APPLICATION_JSON);
        }

        if (VARIANT_JSON.isCompatible(target)) {
            GsonRepresentation<Object> gsonRepresentation = create(source);
            result = gsonRepresentation;
        }
    }

    return result;
}
 
Example 20
Project: restlet-framework   File: JacksonRepresentation.java   Source Code and License 6 votes vote down vote up
/**
 * Constructor.
 * 
 * @param representation
 *            The representation to parse.
 * @param objectClass
 *            The object class to instantiate.
 */
public JacksonRepresentation(Representation representation,
        Class<T> objectClass) {
    super(representation.getMediaType());
    this.object = null;
    this.objectClass = objectClass;
    this.representation = representation;
    this.objectMapper = null;
    this.objectReader = null;
    this.objectWriter = null;
    this.csvSchema = null;
    // [ifndef android] instruction
    this.expandingEntityRefs = XML_EXPANDING_ENTITY_REFS;
    // [ifndef android] instruction
    this.validatingDtd = XML_VALIDATING_DTD;
}
 
Example 21
Project: restlet-framework   File: RangeReader.java   Source Code and License 6 votes vote down vote up
/**
 * Parse the Content-Range header value and update the given representation.
 * 
 * @param value
 *            Content-range header.
 * @param representation
 *            Representation to update.
 */
public static void update(String value, Representation representation) {
    String prefix = "bytes ";
    if (value != null && value.startsWith(prefix)) {
        value = value.substring(prefix.length());

        int index = value.indexOf("-");
        int index1 = value.indexOf("/");

        if (index != -1) {
            long startIndex = (index == 0) ? Range.INDEX_LAST : Long
                    .parseLong(value.substring(0, index));
            long endIndex = Long.parseLong(value.substring(index + 1,
                    index1));

            representation.setRange(new Range(startIndex, endIndex
                    - startIndex + 1));
        }

        String strLength = value.substring(index1 + 1, value.length());
        if (!("*".equals(strLength))) {
            representation.setSize(Long.parseLong(strLength));
        }
    }
}
 
Example 22
Project: restlet-framework   File: Decoder.java   Source Code and License 6 votes vote down vote up
/**
 * Indicates if a representation can be decoded.
 * 
 * @param representation
 *            The representation to test.
 * @return True if the call can be decoded.
 */
public boolean canDecode(Representation representation) {
    // Test the existence of the representation and that at least an
    // encoding applies.
    boolean result = (representation != null)
            && (!representation.getEncodings().isEmpty());

    if (result) {
        boolean found = false;

        for (final Iterator<Encoding> iter = representation.getEncodings()
                .iterator(); !found && iter.hasNext();) {
            found = (!iter.next().equals(Encoding.IDENTITY));
        }

        result = found;
    }
    return result;
}
 
Example 23
Project: springboot-shiro-cas-mybatis   File: TicketResource.java   Source Code and License 5 votes vote down vote up
/**
 * Accept credentials and attempt to create the TGT.
 *
 * @param entity the entity
 */
@Post
public final void acceptRepresentation(final Representation entity)  {
    LOGGER.debug("Obtaining credentials...");
    final Credential c = obtainCredentials();

    if (c == null) {
        LOGGER.trace("No credentials could be obtained from the REST entity representation");
        getResponse().setStatus(Status.CLIENT_ERROR_BAD_REQUEST, "Invalid or missing credentials");
        return;
    }

    try (final Formatter fmt = new Formatter()) {
        final TicketGrantingTicket ticketGrantingTicketId = this.centralAuthenticationService.createTicketGrantingTicket(c);
        getResponse().setStatus(determineStatus());
        final Reference ticketReference = getRequest().getResourceRef().addSegment(ticketGrantingTicketId.getId());
        getResponse().setLocationRef(ticketReference);

        fmt.format("<!DOCTYPE HTML PUBLIC \\\"-//IETF//DTD HTML 2.0//EN\\\"><html><head><title>");
        fmt.format("%s %s", getResponse().getStatus().getCode(), getResponse().getStatus().getDescription())
           .format("</title></head><body><h1>TGT Created</h1><form action=\"%s", ticketReference)
           .format("\" method=\"POST\">Service:<input type=\"text\" name=\"service\" value=\"\">")
           .format("<br><input type=\"submit\" value=\"Submit\"></form></body></html>");

        getResponse().setEntity(fmt.toString(), MediaType.TEXT_HTML);
    } catch (final Exception e) {
        LOGGER.error(e.getMessage(), e);
        getResponse().setStatus(Status.CLIENT_ERROR_BAD_REQUEST, e.getMessage());
    }
}
 
Example 24
Project: microservices-perf   File: JacksonCustomConverter.java   Source Code and License 5 votes vote down vote up
@Override
protected <T> JacksonRepresentation<T> create(Representation source, Class<T> objectClass) {
    ObjectMapper mapper = createMapper();
    JacksonRepresentation<T> jr = new JacksonRepresentation<>(source, objectClass);
    jr.setObjectMapper(mapper);
    return jr;
}
 
Example 25
Project: CatchMeIfUCan   File: RegisterUserService.java   Source Code and License 5 votes vote down vote up
@Post
public Representation post(JsonRepresentation jsonRep) {

	JSONObject request = jsonRep.getJsonObject();
	String username = request.getString("username");
	System.out.println(username);
		
	Iterator userListIterator = Game.getInstance().getIterator();

	JSONObject response = new JSONObject();

	// check if user already exists
	while (userListIterator.hasNext()) {
		User user = (User) userListIterator.next();

		if (user.getUsername().equals(username)) {
			response.put("statusCode", 401);
			return new JsonRepresentation(response);
		}
	}

	// otherwise register user
	Game.getInstance().addUser(new User(username));

	response.put("username", username);
	response.put("statusCode", 200);

	return new JsonRepresentation(response);
}
 
Example 26
Project: bigstreams   File: AgentsStatusResource.java   Source Code and License 5 votes vote down vote up
@Get("html")
public Representation getCollectorsHtml() throws ResourceNotFoundException, ParseErrorException, MethodInvocationException, IOException, Exception{
	
	List<Map<String, Object>> agents = getCollectorsJson();
	VelocityContext ctx = new VelocityContext();
	ctx.put("agents",agents);
	StringWriter writer = new StringWriter();
	Velocity.getTemplate("agentsStatusResource.vm").merge(ctx, writer);
	return new  StringRepresentation(writer.toString(), MediaType.TEXT_HTML);
}
 
Example 27
Project: bigstreams   File: CollectorsStatusResource.java   Source Code and License 5 votes vote down vote up
@Get("html")
public Representation getCollectorsHtml() throws ResourceNotFoundException, ParseErrorException, Exception{
	
	List<Map<String, Object>> collectors = getCollectors();
	//TemplateRepresentation rep = new TemplateRepresentation(Velocity.getTemplate("collectorsStatusResource.vm"), model, MediaType.TEXT_HTML);
	VelocityContext ctx = new VelocityContext();
	ctx.put("collectors", collectors);
	StringWriter writer = new StringWriter();
	Velocity.getTemplate("collectorsStatusResource.vm").merge(ctx, writer);
	return new  StringRepresentation(writer.toString(), MediaType.TEXT_HTML);
}
 
Example 28
Project: bigstreams   File: CollectorStatusResource.java   Source Code and License 5 votes vote down vote up
@Get("html")
public Representation getCollectorsHtml() throws ResourceNotFoundException, ParseErrorException, Exception{
	
	//this is not the view port
	int port = Integer.valueOf(getQuery().getFirstValue("port", "8220"));
	String collectorHostParam = getQuery().getFirstValue("collector", true);
	String statusObj = null;
	
	if(collectorHostParam != null && collectorHostParam.trim().length() > 0){
		String url = "http://" + collectorHostParam + ":" + viewPort + "/view/collector/status";
		getResponse().redirectPermanent(url);
		return null;
	}else{
		statusObj = objectMapper.writeValueAsString(status);
		collectorHostParam = "localhost";
	}
	
	VelocityContext ctx = new VelocityContext();
	
	ctx.put("collectorPort", port);
	ctx.put("collectorHost", collectorHostParam);
	ctx.put("collectorStatus", statusObj);
	StringWriter writer = new StringWriter();
	Velocity.getTemplate("collectorStatusResource.vm").merge(ctx, writer);
	
	return  new  StringRepresentation(writer.toString(), MediaType.TEXT_HTML);
}
 
Example 29
Project: bigstreams   File: TestCoordinationFileTrackingCountResource.java   Source Code and License 5 votes vote down vote up
/**
 * Test a simple count request
 * 
 * @throws Exception
 */
public void testLs() throws Exception {
	
	CollectorFileTrackerMemory memory = bootstrap
			.getBean(HazelcastFileTrackerStorage.class);

	int fileCount = 10;

	// prepare data
	for (int i = 0; i < fileCount; i++) {
		FileTrackingStatus stat = new FileTrackingStatus(new Date(), 0,
				10L, 0, "test" + i, "test" + i, "type" + i, new Date(), 1L);
		memory.setStatus(stat);
	}

	int port = conf.getInt(CoordinationProperties.PROP.COORDINATION_PORT
			.toString(),
			(Integer) CoordinationProperties.PROP.COORDINATION_PORT
					.getDefaultValue());

	ClientResource clientResource = new ClientResource("http://localhost:"
			+ port + "/files/count");

	Representation rep = clientResource.get(MediaType.APPLICATION_JSON);

	long count = Long.parseLong(rep.getText());

	assertEquals(fileCount, count);

}
 
Example 30
Project: bigstreams   File: TestCoordinationHistoryAgentsLatestResource.java   Source Code and License 5 votes vote down vote up
/**
 * Test a simple ls request
 * 
 * @throws Exception
 */
public void testLsQuery() throws Exception {

	FileTrackerHistoryMemory memory = bootstrap
			.getBean(FileTrackerHistoryMemory.class);

	int fileCount = 10;
	
	// prepare data
	for (int i = 0; i < fileCount; i++) {
		memory.addToHistory(new FileTrackerHistoryItem(
				new Date(), "agent" + i, "test" + i, FileTrackerHistoryItem.STATUS.OK));
	}

	int port = conf.getInt(CoordinationProperties.PROP.COORDINATION_PORT
			.toString(),
			(Integer) CoordinationProperties.PROP.COORDINATION_PORT
					.getDefaultValue());

	String address = "http://localhost:" + port + "/agents/latest";

	ClientResource clientResource = new ClientResource(address);
	
	Representation rep = clientResource.get(MediaType.APPLICATION_JSON);
	ObjectMapper objMapper = new ObjectMapper();
	
	Map<String, FileTrackerHistoryItem> statusList = objMapper.readValue(
			rep.getText(),
			new TypeReference<HashMap<String, FileTrackerHistoryItem>>() {
			});

	assertNotNull(statusList);
	assertEquals(fileCount, statusList.size());
}
 
Example 31
Project: restlet-framework   File: DecodeRepresentation.java   Source Code and License 5 votes vote down vote up
/**
 * Constructor.
 * 
 * @param wrappedRepresentation
 *            The wrapped representation.
 */
public DecodeRepresentation(Representation wrappedRepresentation) {
    super(wrappedRepresentation);
    this.decoding = getSupportedEncodings().containsAll(
            wrappedRepresentation.getEncodings());
    this.wrappedEncodings = new CopyOnWriteArrayList<Encoding>(
            wrappedRepresentation.getEncodings());
}
 
Example 32
Project: restlet-framework   File: ClientResource.java   Source Code and License 5 votes vote down vote up
/**
 * Handles an object entity. Automatically serializes the object using the
 * {@link org.restlet.service.ConverterService}.
 * 
 * @param method
 *            The request method to use.
 * @param entity
 *            The object entity to post.
 * @param resultClass
 *            The class of the response entity.
 * @return The response object entity.
 * @throws ResourceException
 */
protected <T> T handle(Method method, Object entity, Class<T> resultClass)
        throws ResourceException {
    org.restlet.service.ConverterService cs = getConverterService();
    ClientInfo clientInfo = getClientInfo();

    if (clientInfo.getAcceptedMediaTypes().isEmpty()) {
        cs.updatePreferences(clientInfo.getAcceptedMediaTypes(),
                resultClass);
    }

    // Prepare the request by cloning the prototype request
    Request request = createRequest();
    request.setMethod(method);
    request.setClientInfo(clientInfo);

    if (entity != null) {
        List<? extends Variant> entityVariants;
        try {
            entityVariants = cs.getVariants(entity.getClass(), null);
            request.setEntity(toRepresentation(
                    entity,
                    getConnegService().getPreferredVariant(entityVariants,
                            request, getMetadataService())));
        } catch (IOException e) {
            throw new ResourceException(e);
        }
    } else {
        request.setEntity(null);
    }

    // Actually handle the call
    Response response = handleOutbound(request);
    Representation responseEntity = handleInbound(response);
    return toObject(responseEntity, resultClass);
}
 
Example 33
Project: restlet-framework   File: RangeRepresentation.java   Source Code and License 5 votes vote down vote up
/**
 * Constructor.
 * 
 * @param wrappedRepresentation
 *            The wrapped representation with a complete content.
 * @param range
 *            The range to expose.
 */
public RangeRepresentation(Representation wrappedRepresentation, Range range) {
    super(wrappedRepresentation);
    if (wrappedRepresentation.getRange() != null) {
        throw new IllegalArgumentException(
                "The wrapped representation must not have a range set.");
    }
    setRange(range);
}
 
Example 34
Project: sync-android-p2p   File: HttpListener.java   Source Code and License 5 votes vote down vote up
private Representation lastSequence(String dbname) {
    // the update_seq value may not actually be required
    Map<String, Object> response = new HashMap<String, Object>();
    response.put("instance_start_time", getInstanceStartTime(dbname).toString());
    response.put("update_seq", getLastSequence(dbname));
    String body = JSONUtils.serializeAsString(response);
    return new StringRepresentation(body, MediaType.APPLICATION_JSON);
}
 
Example 35
Project: uReplicator   File: TopicManagementRestletResource.java   Source Code and License 5 votes vote down vote up
@Override
@Post("json")
public Representation post(Representation entity) {
  try {
    final String topicName = (String) getRequest().getAttributes().get("topicName");
    String jsonRequest = entity.getText();
    TopicPartition topicPartitionInfo = null;
    if ((jsonRequest == null || jsonRequest.isEmpty()) && topicName != null
        && _srcKafkaBrokerTopicObserver != null) {
      // Only triggered when srcKafkaObserver is there and curl call has no json blob.
      topicPartitionInfo = _srcKafkaBrokerTopicObserver.getTopicPartition(topicName);
      if (topicPartitionInfo == null) {
        return new StringRepresentation(String.format(
            "Failed to add new topic: %s, it's not exsited in source kafka cluster!", topicName));
      }
    } else {
      topicPartitionInfo = TopicPartition.init(jsonRequest);
    }
    if (_autoTopicWhitelistingManager != null) {
      _autoTopicWhitelistingManager.removeFromBlacklist(topicPartitionInfo.getTopic());
    }
    if (_helixMirrorMakerManager.isTopicExisted(topicPartitionInfo.getTopic())) {
      getResponse().setStatus(Status.CLIENT_ERROR_NOT_FOUND);
      return new StringRepresentation(String.format(
          "Failed to add new topic: %s, it is already existed!", topicPartitionInfo.getTopic()));
    } else {
      _helixMirrorMakerManager.addTopicToMirrorMaker(topicPartitionInfo);
      return new StringRepresentation(
          String.format("Successfully add new topic: %s", topicPartitionInfo));
    }
  } catch (IOException e) {
    LOGGER.error("Got error during processing Post request", e);
    getResponse().setStatus(Status.SERVER_ERROR_INTERNAL);
    return new StringRepresentation(
        String.format("Failed to add new topic, with exception: %s", e));
  }
}
 
Example 36
Project: restlet-framework   File: MethodAnnotationInfo.java   Source Code and License 5 votes vote down vote up
/**
 * Indicates if the annotated method described is compatible with the given
 * parameters.
 * 
 * @param restletMethod
 *            The Restlet method to match.
 * @param requestEntity
 *            Optional request entity.
 * @param metadataService
 *            The metadata service to use.
 * @param converterService
 *            The converter service to use.
 * @return True if the annotated method is compatible.
 * @throws IOException
 */
public boolean isCompatible(Method restletMethod, Form queryParams,
        Representation requestEntity, MetadataService metadataService,
        org.restlet.service.ConverterService converterService)
        throws IOException {
    boolean result = true;

    // Verify query parameters
    if (getQuery() != null) {
        Form requiredParams = new Form(getQuery());

        for (Iterator<Parameter> iter = requiredParams.iterator(); iter
                .hasNext() && result;) {
            result = queryParams.contains(iter.next());
        }
    }

    // Verify HTTP method
    if (result) {
        result = getRestletMethod().equals(restletMethod);
    }

    // Verify request entity
    if (result) {
        result = isCompatibleRequestEntity(requestEntity, metadataService,
                converterService);

    }

    return result;
}
 
Example 37
Project: restlet-framework   File: ServerResource.java   Source Code and License 5 votes vote down vote up
/**
 * Describes the available variants to help client-side content negotiation.
 * Return null by default.
 * 
 * @return The description of available variants.
 */
protected Representation describeVariants() {
    Representation result = null;

    // The list of all variants is transmitted to the client
    // final ReferenceList refs = new ReferenceList(variants.size());
    // for (final Variant variant : variants) {
    // if (variant.getIdentifier() != null) {
    // refs.add(variant.getIdentifier());
    // }
    // }
    //
    // result = refs.getTextRepresentation();
    return result;
}
 
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: FreemarkerConverter.java   Source Code and License 5 votes vote down vote up
@Override
public Representation toRepresentation(Object source, Variant target,
        Resource resource) throws IOException {

    if (source instanceof Template) {
        return new TemplateRepresentation((Template) source,
                new ResolverHashModel(Resolver.createResolver(
                        resource.getRequest(), resource.getResponse())),
                target.getMediaType());

    }

    return null;
}
 
Example 40
Project: Team-Project-1   File: RoomResource.java   Source Code and License 5 votes vote down vote up
@Get
public Representation get(JsonRepresentation jsonRep) throws JSONException {
	try {
		int roomId = Integer.parseInt(getQueryValue("roomId"));
		return new JacksonRepresentation<Score>(MySQL.getOpponent(roomId));
	} catch (Exception e) {
		e.printStackTrace();
	}
	return null;
}