Java Code Examples for org.restlet.data.MediaType

The following are top voted examples for showing how to use org.restlet.data.MediaType. 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: cyclops-rc   File: AccountingClient.java   Source Code and License 7 votes vote down vote up
/**
 * Pull data from provided URL
 *
 * @param url
 * @return output string
 */
private String pullData(String url) throws IOException {
    Client client = new Client(Protocol.HTTP);
    ClientResource cr = new ClientResource(url);
    Request req = cr.getRequest();

    // now header
    Series<Header> headerValue = new Series<Header>(Header.class);
    req.getAttributes().put(HeaderConstants.ATTRIBUTE_HEADERS, headerValue);
    headerValue.add("Accept", "application/json");
    headerValue.add("Content-Type", "application/json");

    // fire it up
    cr.get(MediaType.APPLICATION_JSON);
    Representation output = cr.getResponseEntity();

    // and return response data
    return output.getText();
}
 
Example 2
Project: hub-email-extension   File: EmailTestServerResource.java   Source Code and License 6 votes vote down vote up
@Get
public FileRepresentation getTestForm() {
    ExtensionTokenManager tokenManager = this.getTokenManager();
    if (tokenManager.authenticationRequired()) {
        getResponse().setStatus(Status.CLIENT_ERROR_UNAUTHORIZED);
        return null;
    } else {
        try {
            File webDir = getWebDirectory();
            File file = new File(webDir, TEST_FORM_HTML);
            FileRepresentation htmlForm = new FileRepresentation(file, MediaType.TEXT_HTML);
            return htmlForm;
        } catch (Exception ex) {
            getResponse().setStatus(Status.SERVER_ERROR_INTERNAL);
            return null;
        }
    }
}
 
Example 3
Project: bigstreams   File: StopAgent.java   Source Code and License 6 votes vote down vote up
/**
 * Counts the FileTrackingStatus instances
 */
@Override
public void process(CommandLine cmdLine, OutputStream out) throws Exception {

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

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

	PrintWriter writer = new PrintWriter(out);
	try {

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

	} finally {
		writer.close();
	}

}
 
Example 4
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 5
Project: bigstreams   File: TestFileTrackerStatusResource.java   Source Code and License 6 votes vote down vote up
/**
 * Helper method. The method will call the client with the status parameter
 * provided and using json return a FileTrackingStatus as response
 * 
 * @param client
 * @param status
 * @return
 * @throws Exception
 */
@SuppressWarnings("unchecked")
private Collection<FileTrackingStatus> getStatusObject(Client client,
		String status, int from, int max) throws Exception {

	ByteArrayOutputStream out = new ByteArrayOutputStream();
	ClientResource clientResource = new ClientResource("http://localhost:"
			+ port + "/files/list/" + status);
	if (from > -1) {
		clientResource.setRanges(Arrays.asList(new Range(from, max)));
	}

	clientResource.get(MediaType.APPLICATION_JSON).write(out);

	ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
	ObjectMapper om = new ObjectMapper();

	return (Collection<FileTrackingStatus>) om.readValue(in,
			Collection.class);

}
 
Example 6
Project: bigstreams   File: TestFileTrackerStatusResourceByStatus.java   Source Code and License 6 votes vote down vote up
/**
 * Helper method. The method will call the client with the status parameter
 * provided and using json return a FileTrackingStatus as response
 * 
 * @param client
 * @param status
 * @return
 * @throws Exception
 */
@SuppressWarnings("unchecked")
private Collection<FileTrackingStatus> getStatusObject(Client client,
		String status, int from, int max) throws Exception {

	ByteArrayOutputStream out = new ByteArrayOutputStream();
	ClientResource clientResource = new ClientResource("http://localhost:"
			+ port + "/files/list/" + status);
	if (from > -1) {
		clientResource.setRanges(Arrays.asList(new Range(from, max)));
	}

	clientResource.get(MediaType.APPLICATION_JSON).write(out);

	ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
	ObjectMapper om = new ObjectMapper();

	return (Collection<FileTrackingStatus>) om.readValue(in,
			Collection.class);

}
 
Example 7
Project: bigstreams   File: StopCollectorCommand.java   Source Code and License 6 votes vote down vote up
/**
 * Counts the FileTrackingStatus instances
 */
@Override
public void process(CommandLine cmdLine, OutputStream out) throws Exception {

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

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

	PrintWriter writer = new PrintWriter(out);
	try {

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

	} finally {
		writer.close();
	}

}
 
Example 8
Project: bigstreams   File: StopCoordinationCommand.java   Source Code and License 6 votes vote down vote up
/**
 * Counts the FileTrackingStatus instances
 */
@Override
public void process(CommandLine cmdLine, OutputStream out) throws Exception {

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

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

	PrintWriter writer = new PrintWriter(out);
	try {

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

	} finally {
		writer.close();
	}

}
 
Example 9
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 10
Project: sync-android-p2p   File: HttpListener.java   Source Code and License 6 votes vote down vote up
@Post("json")
public Representation handlePost(Representation entity) {

    String path = getReference().getPath();

    String dbname = getDatabaseName(path);
    
    if (!dbNameExists(dbname)) {
        return databaseNotFound();
    }
    else if (path.endsWith("/_revs_diff")) {
        return handleRevsDiff(dbname);
    }
    else if (path.endsWith("/_ensure_full_commit")) {
        return handleEnsureFullCommitPost(dbname);
    }
    else if (path.endsWith("/_bulk_docs")) {
        return handleBulkDocsPost(dbname);
    }
    else {
    	getResponse().setStatus(Status.SERVER_ERROR_INTERNAL);
    	return new StringRepresentation("{\"message\": \"Server error for request: " + getMethod() + " " + path + "\"}", MediaType.TEXT_PLAIN);
    }
}
 
Example 11
Project: sync-android-p2p   File: HttpListener.java   Source Code and License 6 votes vote down vote up
@Put("json")
public Representation handlePut(Representation entity) {

    String path = getReference().getPath();

    String dbname = getDatabaseName(path);

    String pathWithFirstAndLastSlashRemoved = path.replaceAll("^/", "").replaceAll("/$", "");

    if (pathWithFirstAndLastSlashRemoved.equals(dbname)) {
        // must be a PUT /target request
        return handleCreateTargetPut(dbname);
    }
    else if (!dbNameExists(dbname)) {
        return databaseNotFound();
    }
    else if (path.contains("/_local/")) {
        return handleLocalPut(dbname);
    } else {
    	getResponse().setStatus(Status.SERVER_ERROR_INTERNAL);
    	return new StringRepresentation("{\"message\": \"Server error for request: " + getMethod() + " " + path + "\"}", MediaType.TEXT_PLAIN);
    }
}
 
Example 12
Project: uReplicator   File: TopicManagementRestletResource.java   Source Code and License 6 votes vote down vote up
public TopicManagementRestletResource() {
  getVariants().add(new Variant(MediaType.TEXT_PLAIN));
  getVariants().add(new Variant(MediaType.APPLICATION_JSON));
  setNegotiated(false);
  _helixMirrorMakerManager = (HelixMirrorMakerManager) getApplication().getContext()
      .getAttributes().get(HelixMirrorMakerManager.class.toString());
  _autoTopicWhitelistingManager = (AutoTopicWhitelistingManager) getApplication().getContext()
      .getAttributes().get(AutoTopicWhitelistingManager.class.toString());
  if (getApplication().getContext().getAttributes()
      .containsKey(KafkaBrokerTopicObserver.class.toString())) {
    _srcKafkaBrokerTopicObserver = (KafkaBrokerTopicObserver) getApplication().getContext()
        .getAttributes().get(KafkaBrokerTopicObserver.class.toString());
  } else {
    _srcKafkaBrokerTopicObserver = null;
  }
}
 
Example 13
Project: uReplicator   File: ValidationRestletResource.java   Source Code and License 6 votes vote down vote up
public ValidationRestletResource() {
  getVariants().add(new Variant(MediaType.TEXT_PLAIN));
  getVariants().add(new Variant(MediaType.APPLICATION_JSON));
  setNegotiated(false);

  _validationManager = (ValidationManager) getApplication().getContext()
      .getAttributes().get(ValidationManager.class.toString());
  if (getApplication().getContext().getAttributes()
      .containsKey(SourceKafkaClusterValidationManager.class.toString())) {
    _srcKafkaValidationManager =
        (SourceKafkaClusterValidationManager) getApplication().getContext()
            .getAttributes().get(SourceKafkaClusterValidationManager.class.toString());
  } else {
    _srcKafkaValidationManager = null;
  }
}
 
Example 14
Project: chaperone   File: TopicManagementRestletResource.java   Source Code and License 6 votes vote down vote up
public TopicManagementRestletResource() {
  getVariants().add(new Variant(MediaType.TEXT_PLAIN));
  getVariants().add(new Variant(MediaType.APPLICATION_JSON));
  setNegotiated(false);
  _helixMirrorMakerManager = (HelixMirrorMakerManager) getApplication().getContext()
      .getAttributes().get(HelixMirrorMakerManager.class.toString());
  _autoTopicWhitelistingManager = (AutoTopicWhitelistingManager) getApplication().getContext()
      .getAttributes().get(AutoTopicWhitelistingManager.class.toString());
  if (getApplication().getContext().getAttributes()
      .containsKey(KafkaBrokerTopicObserver.class.toString())) {
    _srcKafkaBrokerTopicObserver = (KafkaBrokerTopicObserver) getApplication().getContext()
        .getAttributes().get(KafkaBrokerTopicObserver.class.toString());
  } else {
    _srcKafkaBrokerTopicObserver = null;
  }
}
 
Example 15
Project: chaperone   File: ValidationRestletResource.java   Source Code and License 6 votes vote down vote up
public ValidationRestletResource() {
  getVariants().add(new Variant(MediaType.TEXT_PLAIN));
  getVariants().add(new Variant(MediaType.APPLICATION_JSON));
  setNegotiated(false);

  _validationManager = (ValidationManager) getApplication().getContext()
      .getAttributes().get(ValidationManager.class.toString());
  if (getApplication().getContext().getAttributes()
      .containsKey(SourceKafkaClusterValidationManager.class.toString())) {
    _srcKafkaValidationManager =
        (SourceKafkaClusterValidationManager) getApplication().getContext()
            .getAttributes().get(SourceKafkaClusterValidationManager.class.toString());
  } else {
    _srcKafkaValidationManager = null;
  }
}
 
Example 16
Project: Camel   File: RestletRouteBuilderAuthTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testBasicAuth() throws IOException {
    
    // START SNIPPET: auth_request
    final String id = "89531";

    Map<String, Object> headers = new HashMap<String, Object>();
    headers.put(RestletConstants.RESTLET_LOGIN, "admin");
    headers.put(RestletConstants.RESTLET_PASSWORD, "foo");
    headers.put(Exchange.CONTENT_TYPE, MediaType.APPLICATION_XML);
    headers.put("id", id);
    
    String response = template.requestBodyAndHeaders(
        "direct:start-auth", "<order foo='1'/>", headers, String.class);
    // END SNIPPET: auth_request

    assertEquals("received [<order foo='1'/>] as an order id = " + id, response);
}
 
Example 17
Project: polygene-java   File: AbstractResponseWriter.java   Source Code and License 6 votes vote down vote up
protected Variant getVariant( Request request,
                              List<Language> possibleLanguages,
                              List<MediaType> possibleMediaTypes
)
{
    Language language = request.getClientInfo().getPreferredLanguage( possibleLanguages );

    if( language == null )
    {
        language = possibleLanguages.get( 0 );
    }

    MediaType responseType = request.getClientInfo().getPreferredMediaType( possibleMediaTypes );

    if( responseType == null && request.getClientInfo()
                                    .getPreferredMediaType( Collections.singletonList( MediaType.ALL ) ) == MediaType.ALL )
    {
        responseType = possibleMediaTypes.get( 0 );
    }

    Variant variant = new Variant( responseType, language );
    variant.setCharacterSet( CharacterSet.UTF_8 );

    return variant;
}
 
Example 18
Project: polygene-java   File: LinksResponseWriter.java   Source Code and License 6 votes vote down vote up
private Representation createTextHtmlRepresentation( final Object result, final Response response )
{
    return new WriterRepresentation( MediaType.TEXT_HTML )
                {
                    @Override
                    public void write( Writer writer )
                        throws IOException
                    {
                        Map<String, Object> context = new HashMap<>();
                        context.put( "request", response.getRequest() );
                        context.put( "response", response );
                        context.put( "result", result );
                        try
                        {
                            cfg.getTemplate( "links.htm" ).process( context, writer );
                        }
                        catch( TemplateException e )
                        {
                            throw new IOException( e );
                        }
                    }
                };
}
 
Example 19
Project: polygene-java   File: LinksResponseWriter.java   Source Code and License 6 votes vote down vote up
private Representation createAtomRepresentation( final Object result, final Response response )
{
    return new WriterRepresentation( MediaType.APPLICATION_ATOM )
    {
        @Override
        public void write( Writer writer )
            throws IOException
        {
            Map<String, Object> context = new HashMap<>();
            context.put( "request", response.getRequest() );
            context.put( "response", response );
            context.put( "result", result );
            try
            {
                cfg.getTemplate( "links.atom" ).process( context, writer );
            }
            catch( TemplateException e )
            {
                throw new IOException( e );
            }
        }
    };
}
 
Example 20
Project: polygene-java   File: DefaultResponseWriter.java   Source Code and License 6 votes vote down vote up
@Override
public boolean writeResponse( final Object result, final Response response )
    throws ResourceException
{
    MediaType type = getVariant( response.getRequest(), ENGLISH, supportedMediaTypes ).getMediaType();
    if( MediaType.APPLICATION_JSON.equals( type ) )
    {
        if( result instanceof String || result instanceof Number || result instanceof Boolean )
        {
            StringRepresentation representation = new StringRepresentation( result.toString(),
                                                                            MediaType.APPLICATION_JSON );

            response.setEntity( representation );

            return true;
        }
    }

    return false;
}
 
Example 21
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 22
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 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: cyclops-rc   File: McnPuller.java   Source Code and License 6 votes vote down vote up
/**
 * Pull data from provided URL
 * @param url
 * @return output string or empty string
 */
private String pullData(String url) throws IOException {
    Client client = new Client(Protocol.HTTP);
    ClientResource cr = new ClientResource(url);
    Request req = cr.getRequest();

    // now header
    Series<Header> headerValue = new Series<Header>(Header.class);
    req.getAttributes().put(HeaderConstants.ATTRIBUTE_HEADERS, headerValue);
    headerValue.add("Accept", "application/json");
    headerValue.add("Content-Type", "application/json");

    // fire it up
    cr.get(MediaType.APPLICATION_JSON);
    Representation output = cr.getResponseEntity();

    // return null or received text
    return (output == null) ? "" : output.getText();
}
 
Example 25
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 26
Project: polygene-java   File: PolygeneConverter.java   Source Code and License 6 votes vote down vote up
@Override
public Representation toRepresentation( Object source, Variant target, Resource resource )
{
    Representation result = null;

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

    return result;
}
 
Example 27
Project: ontopia   File: AbstractOntopiaResource.java   Source Code and License 6 votes vote down vote up
/**
 * Blocks the use of specified mime types for this resource, as it is known that the converter for that mime type
 * cannot produce the representation for the Resource's target class.
 * @param types The mime types to block
 */
protected void blockMimeType(MediaType... types) {
	List<Preference<MediaType>> acceptedMediaTypes = getClientInfo().getAcceptedMediaTypes();
	if (acceptedMediaTypes.size() > types.length) {
		return;
	}	

	Set<MediaType> accepted = new HashSet<>(acceptedMediaTypes.size());
	for (Preference<MediaType> p : acceptedMediaTypes) {
		accepted.add(p.getMetadata());
	}
	
	accepted.removeAll(Arrays.asList(types));
	
	if (accepted.isEmpty()) {
		throw OntopiaRestErrors.UNSUPPORTED_MIME_TYPE.build(getClass().getName(), Arrays.toString(types));
	}
}
 
Example 28
Project: cyclops-udr   File: CloudStackDownloader.java   Source Code and License 6 votes vote down vote up
/**
 * Pulls data from CloudStack API
 *
 * @return JSON string
 * @throws IOException
 */
private String pullData() throws IOException {
    logger.trace("Starting to pull data from provided URL");

    // create connection
    Client client = new Client(Protocol.HTTP);
    ClientResource cr = new ClientResource(url);
    Request req = cr.getRequest();

    // now header
    Series<Header> headerValue = new Series<Header>(Header.class);
    req.getAttributes().put(HeaderConstants.ATTRIBUTE_HEADERS, headerValue);
    headerValue.add("Accept", "application/json");
    headerValue.add("Content-Type", "application/json");

    // fire it up
    cr.get(MediaType.APPLICATION_JSON);
    Representation output = cr.getResponseEntity();

    logger.trace("Successfully pulled data from provided URL");

    // and return response data
    return output.getText();
}
 
Example 29
Project: fiware-iot-discovery-ngsi9   File: Resource10_AvailabilitySubscription.java   Source Code and License 6 votes vote down vote up
@Delete
public Representation removeDescription() throws JAXBException, ResourceException, IOException {
    
    String acceptType = "";
    int size = getClientInfo().getAcceptedMediaTypes().size();
    if (size > 0) {
        acceptType = getClientInfo().getAcceptedMediaTypes().get(0).getMetadata().getSubType();
    }
    else acceptType = MediaType.APPLICATION_JSON.getSubType();

    String subsId = (String) getRequest().getAttributes().get("subscriptionID");
    System.out.println("CO 10: DELETE AVAILABILITY SUBSCRIPTION: subscriptionId = '" + subsId + "'");
    
    UnsubscribeContextAvailabilityRequest ucar = new UnsubscribeContextAvailabilityRequest();
    ucar.setSubscriptionId(subsId);        
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
    InputStream stream = new ByteArrayInputStream(objectMapper.writeValueAsBytes(ucar));

    Resource05_AvailabilitySubscriptionDeletion ras = new Resource05_AvailabilitySubscriptionDeletion();
    StringRepresentation result = ras.unsubscribeJsonHandler(stream, acceptType);
    return result;

}
 
Example 30
Project: fiware-iot-discovery-ngsi9   File: indexResource.java   Source Code and License 6 votes vote down vote up
@Get
    public Representation getWebIndex() {

        //get servlet context for getting files
        
        //get servlet context for getting files
//        ServletContext sc = (ServletContext) getContext().getServerDispatcher().getContext().getAttributes().get("org.restlet.ext.servlet.ServletContext");
        ServletContext sc = StorageStartup.servletContext;
        System.out.println(sc.getRealPath("")+"index.html");
        String htmlContent="";
        try {
            htmlContent = FileUtils.readFileToString(new File(sc.getRealPath("/")+"index.html"));
        } catch (IOException ex) {
            Logger.getLogger(indexResource.class.getName()).log(Level.SEVERE, null, ex);
        } 
        
        StringRepresentation result = new StringRepresentation(htmlContent, MediaType.TEXT_HTML);
       

        return result;
    }
 
Example 31
Project: ontopia   File: APIInfoResource.java   Source Code and License 6 votes vote down vote up
@Get
public Representation getAPIInfo() throws IOException {
	TemplateRepresentation r = new TemplateRepresentation("net/ontopia/topicmaps/rest/resources/info.html", MediaType.TEXT_HTML);
	r.getEngine().addProperty(VelocityEngine.RESOURCE_LOADER, "classpath");
	r.getEngine().addProperty("classpath." + VelocityEngine.RESOURCE_LOADER + ".class", ClasspathResourceLoader.class.getName());
	
	Map<Restlet, String> allRoutes = new HashMap<>();
	list(allRoutes, getApplication().getInboundRoot(), "");
	Map<String, Object> data = new HashMap<>();
	data.put("util", this);
	data.put("root", getApplication().getInboundRoot());
	data.put("routes", allRoutes);
	data.put("cutil", ClassUtils.class);
	
	r.setDataModel(data);

	return r;
}
 
Example 32
Project: prudence   File: DelegatedResourceConversationService.java   Source Code and License 6 votes vote down vote up
private void addVariant( MediaType mediaType, Language language )
{
	DelegatedResource resource = getResource();
	List<Variant> variants = resource.getVariants();
	if( resource.getAttributes().isNegotiateEncoding() )
	{
		for( Encoding encoding : CachingUtil.SUPPORTED_ENCODINGS )
		{
			Variant variant = new Variant( mediaType, language );
			variant.getEncodings().add( encoding );
			variants.add( variant );
		}
	}
	else
		variants.add( new Variant( mediaType, language ) );
}
 
Example 33
Project: prudence   File: LazyInitializationFile.java   Source Code and License 6 votes vote down vote up
@Override
protected void initialize()
{
	if( ( request.getMethod().equals( Method.POST ) || request.getMethod().equals( Method.PUT ) ) && request.isEntityAvailable() && request.getEntity().getMediaType().includes( MediaType.MULTIPART_FORM_DATA ) )
	{
		try
		{
			for( FileItem fileItem : fileUpload.parseRequest( request ) )
			{
				if( fileItem.isFormField() )
					formFields.put( fileItem.getFieldName(), fileItem.getString() );
				else
					map.put( fileItem.getFieldName(), Collections.unmodifiableMap( createFileItemMap( fileItem ) ) );
			}
		}
		catch( FileUploadException x )
		{
			x.printStackTrace();
		}
	}
}
 
Example 34
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 35
Project: springboot-shiro-cas-mybatis   File: TicketGrantingTicketResource.java   Source Code and License 5 votes vote down vote up
@Override
public void init(final Context context, final Request request, final Response response) {
    super.init(context, request, response);
    this.ticketGrantingTicketId = (String) request.getAttributes().get("ticketGrantingTicketId");
    this.setNegotiated(false);
    this.getVariants().add(new Variant(MediaType.APPLICATION_WWW_FORM));
}
 
Example 36
Project: eSDK_FC_SDK_Java   File: RestletClient.java   Source Code and License 5 votes vote down vote up
/**
 * 设置标准http header
 * 
 * @param request {@code void}
 * @since eSDK Cloud V100R003C50
 */
private void setDefaultHttpHeader(Request request, String version)
{
	ClientInfo clientInfo = new ClientInfo();

	List<Preference<MediaType>> acceptedMediaTypes = new ArrayList<Preference<MediaType>>();
	Preference<MediaType> preferenceMediaType = new Preference<MediaType>();

	String acceptStr = "application/json;";
	if (null == version)
	{
		acceptStr += "charset=UTF-8;";
	}
	else
	{
		acceptStr += version + "charset=UTF-8;";
	}
	MediaType mediaType = MediaType.register(acceptStr, "");
	preferenceMediaType.setMetadata(mediaType);
	acceptedMediaTypes.add(preferenceMediaType);
	clientInfo.setAcceptedMediaTypes(acceptedMediaTypes);

	List<Preference<Language>> acceptedLanguages = new ArrayList<Preference<Language>>();

	Preference<Language> preferenceLanguage = new Preference<Language>();
	Language language = new Language("zh_CN", "");
	preferenceLanguage.setMetadata(language);
	acceptedLanguages.add(preferenceLanguage);

	clientInfo.setAcceptedLanguages(acceptedLanguages);
	request.setClientInfo(clientInfo);
}
 
Example 37
Project: microservices-perf   File: JacksonCustomConverter.java   Source Code and License 5 votes vote down vote up
@Override
protected <T> JacksonRepresentation<T> create(MediaType mediaType, T source) {
    ObjectMapper mapper = createMapper();
    JacksonRepresentation<T> jr = new JacksonRepresentation<>(mediaType, source);
    jr.setObjectMapper(mapper);
    return jr;
}
 
Example 38
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 39
Project: bigstreams   File: AgentStatusCommand.java   Source Code and License 5 votes vote down vote up
/**
 * Counts the FileTrackingStatus instances
 */
@Override
public void process(CommandLine cmdLine, OutputStream out) throws Exception {

	PrintWriter writer = new PrintWriter(out);
	try {
		if (client == null) {
			// if no client is injected print out shutdown
			writer.println("shutdown");
		} else {

			LOG.info("Connecting via rest");

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

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

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

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

		}
	} finally {
		writer.println();
		writer.flush();
		writer.close();
	}

}
 
Example 40
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 41
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 42
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 43
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 44
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 45
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 46
Project: bigstreams   File: TestCoordinationFileTrackingCountResource.java   Source Code and License 5 votes vote down vote up
/**
 * Test a simple count request with query
 * 
 * @throws Exception
 */
public void testCountQuery() 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());

	String address = "http://localhost:" + port + "/files/count";

	ClientResource clientResource = new ClientResource(address);
	clientResource.getReference().addQueryParameter("query",
			"agentName='test1'");

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

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

	assertEquals(1, count);
}
 
Example 47
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 48
Project: bigstreams   File: TestCoordinationFileTrackingHistoryResource.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;
	String agentName = "testAgent";
	
	// prepare data
	for (int i = 0; i < fileCount; i++) {
		memory.addToHistory(new FileTrackerHistoryItem(
				new Date(), agentName, "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 + "/agent/" + agentName + "/history";

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

	assertNotNull(statusList);
	assertEquals(fileCount, statusList.size());
}
 
Example 49
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 50
Project: bigstreams   File: TestCoordinationHistoryCollectorsLatestResource.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 + "/collectors/latest";

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

	assertNotNull(statusList);
	assertEquals(fileCount, statusList.size());
}
 
Example 51
Project: bigstreams   File: TestCoordinationFileTrackingResource.java   Source Code and License 5 votes vote down vote up
/**
 * Test a simple ls request
 * 
 * @throws Exception
 */
public void testLsQuery() 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());

	String address = "http://localhost:" + port + "/files/list";

	ClientResource clientResource = new ClientResource(address);
	clientResource.getReference().addQueryParameter("query",
			"agentName='test1'");

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

	ObjectMapper objMapper = new ObjectMapper();
	Collection<FileTrackingStatus> statusList = objMapper.readValue(
			rep.getText(),
			new TypeReference<Collection<FileTrackingStatus>>() {
			});

	assertNotNull(statusList);
	assertEquals(1, statusList.size());
	assertEquals("test1", statusList.iterator().next().getAgentName());
}
 
Example 52
Project: bigstreams   File: TestCoordinationFileTrackingResource.java   Source Code and License 5 votes vote down vote up
/**
 * Test a simple ls 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/list");

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

	ObjectMapper objMapper = new ObjectMapper();
	Collection<FileTrackingStatus> statusList = objMapper.readValue(
			rep.getReader(),
			new TypeReference<Collection<FileTrackingStatus>>() {
			});

	assertNotNull(statusList);
	assertEquals(fileCount, statusList.size());

}
 
Example 53
Project: sync-android-p2p   File: HttpListener.java   Source Code and License 5 votes vote down vote up
private Representation handleCreateTargetPut(String dbname) {

        // TODO - authenticate request
        /*
            HTTP/1.1 500 Internal Server Error
            Cache-Control: must-revalidate
            Content-Length: 108
            Content-Type: application/json
            Date: Fri, 09 May 2014 13:50:32 GMT
            Server: CouchDB (Erlang OTP)

            {
              "error": "unauthorized",
              "reason": "unauthorized to access or create database http://localhost:5984/target"
            }
        */

        // TODO this method does not check and handle failure to create the database
        Datastore ds;
		try {
			ds = manager.openDatastore(dbname);
			ds.close();
		} catch (DatastoreNotCreatedException e) {
			throw new RuntimeException(e);
		}

        String body = "{ \"ok\": true }";
        getResponse().setStatus(Status.SUCCESS_CREATED);
        return new StringRepresentation(body, MediaType.APPLICATION_JSON);
    }
 
Example 54
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 55
Project: sync-android-p2p   File: HttpListener.java   Source Code and License 5 votes vote down vote up
private Representation handleEnsureFullCommitPost(String dbname) {
    // http://docs.couchdb.org/en/latest/replication/protocol.html#ensure-in-commit
    Map<String, Object> response = new HashMap<String, Object>();
    response.put("instance_start_time", getInstanceStartTime(dbname));
    response.put("ok", true);
    String responseBody = JSONUtils.serializeAsString(response);
    //System.out.println(responseBody);
    getResponse().setStatus(Status.SUCCESS_CREATED);
    return new StringRepresentation(responseBody, MediaType.APPLICATION_JSON);
}
 
Example 56
Project: cas4.1.9   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 57
Project: cas4.1.9   File: TicketGrantingTicketResource.java   Source Code and License 5 votes vote down vote up
@Override
public void init(final Context context, final Request request, final Response response) {
    super.init(context, request, response);
    this.ticketGrantingTicketId = (String) request.getAttributes().get("ticketGrantingTicketId");
    this.setNegotiated(false);
    this.getVariants().add(new Variant(MediaType.APPLICATION_WWW_FORM));
}
 
Example 58
Project: Camel   File: DefaultRestletBinding.java   Source Code and License 5 votes vote down vote up
protected Representation createRepresentationFromBody(Exchange exchange, MediaType mediaType) {
    Object body = exchange.getIn().getBody();
    if (body == null) {
        return new EmptyRepresentation();
    }

    // unwrap file
    if (body instanceof WrappedFile) {
        body = ((WrappedFile) body).getFile();
    }

    if (body instanceof InputStream) {
        return new InputRepresentation((InputStream) body, mediaType);
    } else if (body instanceof File) {
        return new FileRepresentation((File) body, mediaType);
    } else if (body instanceof byte[]) {
        return new ByteArrayRepresentation((byte[]) body, mediaType);
    } else if (body instanceof String) {
        return new StringRepresentation((CharSequence) body, mediaType);
    }

    // fallback as string
    body = exchange.getIn().getBody(String.class);
    if (body != null) {
        return new StringRepresentation((CharSequence) body, mediaType);
    } else {
        return new EmptyRepresentation();
    }
}
 
Example 59
Project: Camel   File: RestletRouteBuilderTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testProducer() throws IOException {
    Map<String, Object> headers = new HashMap<String, Object>();
    headers.put(Exchange.CONTENT_TYPE, MediaType.APPLICATION_XML);
    
    String response = template.requestBodyAndHeaders("direct:start", "<order foo='1'/>", headers, String.class);
    assertEquals("received [<order foo='1'/>] as an order id = " + ID, response);
    
    headers.put("id", "89531");
    
    response = template.requestBodyAndHeaders(
        "restlet:http://localhost:" + portNum + "/orders?restletMethod=post&foo=bar", 
        "<order foo='1'/>", headers, String.class);
    assertEquals("received [<order foo='1'/>] as an order id = " + ID, response);
}
 
Example 60
Project: Camel   File: RestletRouteBuilderTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testProducerJSON() throws IOException {
    String response = template.requestBodyAndHeader(
        "restlet:http://localhost:" + portNum + "/ordersJSON?restletMethod=post&foo=bar", 
        JSON,
        Exchange.CONTENT_TYPE,
        MediaType.APPLICATION_JSON,
        String.class);
       
    assertEquals(JSON, response);
}