org.restlet.Response Java Examples

The following examples show how to use org.restlet.Response. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: RootResource.java    From attic-polygene-java with Apache License 2.0 6 votes vote down vote up
@SubResource
public void administration()
{
    ChallengeResponse challenge = Request.getCurrent().getChallengeResponse();
    if( challenge == null )
    {
        Response.getCurrent()
            .setChallengeRequests( Collections.singletonList( new ChallengeRequest( ChallengeScheme.HTTP_BASIC, "Forum" ) ) );
        throw new ResourceException( Status.CLIENT_ERROR_UNAUTHORIZED );
    }

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

    current().select( user );

    subResource( AdministrationResource.class );
}
 
Example #2
Source File: ContextResourceClient.java    From attic-polygene-java with Apache License 2.0 6 votes vote down vote up
public <T> ContextResourceClient onResource( final ResultHandler<T> handler)
{
    resourceHandler = new ResponseHandler()
    {
        @Override
        public HandlerCommand handleResponse( Response response, ContextResourceClient client )
        {
            final Class<T> resultType = (Class<T>) Classes.RAW_CLASS.apply(( (ParameterizedType) handler.getClass().getGenericInterfaces()[ 0 ] ).getActualTypeArguments()[0]);
            T result = contextResourceFactory.readResponse( response, resultType );

            if (result instanceof Resource)
            {
                resource = (Resource) result;
            }

            return handler.handleResult( result, client );
        }
    };
    return this;
}
 
Example #3
Source File: GeoWaveOperationServiceWrapperTest.java    From geowave with Apache License 2.0 6 votes vote down vote up
@Test
@Ignore
public void asyncMethodReturnsSuccessStatus() throws Exception {

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

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

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

  // TODO: Returns 500. Error Caught at
  // "final Context appContext = Application.getCurrent().getContext();"
  Assert.assertEquals(
      successStatusIs200,
      classUnderTest.getResponse().getStatus().equals(Status.SUCCESS_OK));
}
 
Example #4
Source File: ApiHelper.java    From scava with Eclipse Public License 2.0 6 votes vote down vote up
public Response createTask(String projectId, String taskId, String label, AnalysisExecutionMode mode,
		List<String> metrics, String start, String end) {
	Request request = new Request(Method.POST, "http://localhost:8182/analysis/task/create");

	ObjectMapper mapper = new ObjectMapper();
	ObjectNode n = mapper.createObjectNode();
	n.put("analysisTaskId", taskId);
	n.put("label", label);
	n.put("type", mode.name());
	n.put("startDate", start);
	n.put("endDate", end);
	n.put("projectId", projectId);
	ArrayNode arr = n.putArray("metricProviders");
	for (String m : metrics)
		arr.add(m);

	request.setEntity(n.toString(), MediaType.APPLICATION_JSON);

	return client.handle(request);
}
 
Example #5
Source File: GeoWaveOperationServiceWrapperTest.java    From geowave with Apache License 2.0 6 votes vote down vote up
@Test
public void getMethodReturnsSuccessStatus() throws Exception {

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

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

  classUnderTest = new GeoWaveOperationServiceWrapper(operation, null);
  classUnderTest.setResponse(new Response(null));
  classUnderTest.setRequest(new Request(Method.GET, "foo.bar"));
  classUnderTest.restGet();
  Assert.assertEquals(
      successStatusIs200,
      classUnderTest.getResponse().getStatus().equals(Status.SUCCESS_OK));
}
 
Example #6
Source File: DefaultResponseReader.java    From attic-polygene-java with Apache License 2.0 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 #7
Source File: TestProjectImportResource.java    From scava with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testEclipse() {
	Client client = new Client(Protocol.HTTP);
	Request request = new Request(Method.POST, "http://localhost:8182/projects/import");
	
	ObjectMapper mapper = new ObjectMapper();
	ObjectNode n = mapper.createObjectNode();
	n.put("url", "https://projects.eclipse.org/projects/modeling.epsilon");
	
	request.setEntity(n.toString(), MediaType.APPLICATION_JSON);
	
	Response response = client.handle(request);
	
	validateResponse(response, 201);
	
	System.out.println(response.getEntityAsText());
}
 
Example #8
Source File: ExceptionProcessor.java    From container with Apache License 2.0 6 votes vote down vote up
@Override
public void process(final Exchange exchange) throws Exception {

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

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

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

    exchange.getOut().setBody(response);
}
 
Example #9
Source File: LinksResponseWriter.java    From attic-polygene-java with Apache License 2.0 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 #10
Source File: LinksResponseWriter.java    From attic-polygene-java with Apache License 2.0 6 votes vote down vote up
private Representation createTextHtmlRepresentation( final Object result, final Response response )
{
    return new WriterRepresentation( MediaType.TEXT_HTML )
                {
                    @Override
                    public void write( Writer writer )
                        throws IOException
                    {
                        Map<String, Object> context = new HashMap<>();
                        context.put( "request", response.getRequest() );
                        context.put( "response", response );
                        context.put( "result", result );
                        try
                        {
                            cfg.getTemplate( "links.htm" ).process( context, writer );
                        }
                        catch( TemplateException e )
                        {
                            throw new IOException( e );
                        }
                    }
                };
}
 
Example #11
Source File: ContextResource.java    From attic-polygene-java with Apache License 2.0 6 votes vote down vote up
private boolean shouldShowCommandForm( Method interactionMethod )
{
    // Show form on GET/HEAD
    if( Request.getCurrent().getMethod().isSafe() )
    {
        return true;
    }

    if( interactionMethod.getParameterTypes().length > 0 )
    {
        return !( interactionMethod.getParameterTypes()[ 0 ].equals( Response.class ) || Request.getCurrent()
            .getEntity()
            .isAvailable() || Request.getCurrent().getEntityAsText() != null || Request.getCurrent()
                                                                                    .getResourceRef()
                                                                                    .getQuery() != null );
    }

    return false;
}
 
Example #12
Source File: TestClusterManagementWebapp.java    From helix with Apache License 2.0 5 votes vote down vote up
private ZNRecord get(Client client, String url, ObjectMapper mapper) throws Exception {
  Request request = new Request(Method.GET, new Reference(url));
  Response response = client.handle(request);
  Representation result = response.getEntity();
  StringWriter sw = new StringWriter();
  result.write(sw);
  String responseStr = sw.toString();
  Assert.assertTrue(responseStr.toLowerCase().indexOf("error") == -1);
  Assert.assertTrue(responseStr.toLowerCase().indexOf("exception") == -1);

  ZNRecord record = mapper.readValue(new StringReader(responseStr), ZNRecord.class);
  return record;
}
 
Example #13
Source File: JSONResponseReader.java    From attic-polygene-java with Apache License 2.0 5 votes vote down vote up
@Override
public Object readResponse( Response response, Class<?> resultType )
{
    if( response.getEntity().getMediaType().equals( MediaType.APPLICATION_JSON ) )
    {
        if( ValueComposite.class.isAssignableFrom( resultType ) )
        {
            String jsonValue = response.getEntityAsText();
            ValueCompositeType valueType = module.valueDescriptor( resultType.getName() ).valueType();
            return jsonDeserializer.deserialize( module, valueType, jsonValue );
        }
        else if( resultType.equals( Form.class ) )
        {
            try( JsonReader reader = jsonFactories.readerFactory()
                                                  .createReader( response.getEntity().getReader() ) )
            {
                JsonObject jsonObject = reader.readObject();
                Form form = new Form();
                jsonObject.forEach(
                    ( key, value ) ->
                    {
                        String valueString = value.getValueType() == JsonValue.ValueType.STRING
                                             ? ( (JsonString) value ).getString()
                                             : value.toString();
                        form.set( key, valueString );
                    } );
                return form;
            }
            catch( IOException | JsonException e )
            {
                throw new ResourceException( e );
            }
        }
    }
    return null;
}
 
Example #14
Source File: ContextResourceClientFactory.java    From attic-polygene-java with Apache License 2.0 5 votes vote down vote up
void updateCache( Response response )
{
    if( cache != null )
    {
        cache.updateCache( response );
    }
}
 
Example #15
Source File: PolygeneEntityRestlet.java    From attic-polygene-java with Apache License 2.0 5 votes vote down vote up
private void post( final Request request, final Response response )
{
    execute( request, response, resource -> {
        RestForm form = createRestForm( request );
        RestLink link = resource.post( form );
        response.setLocationRef( link.path().get() );
        response.setStatus( Status.REDIRECTION_SEE_OTHER );
    } );
}
 
Example #16
Source File: HandlerCommand.java    From attic-polygene-java with Apache License 2.0 5 votes vote down vote up
public <T> HandlerCommand onSuccess(final ResultHandler<T> resultHandler)
{
    final Class<T> resultType = (Class<T>) Classes.RAW_CLASS.apply(( (ParameterizedType) resultHandler.getClass().getGenericInterfaces()[ 0 ] ).getActualTypeArguments()[0]);
    this.responseHandler = new ResponseHandler()
    {
        @Override
        public HandlerCommand handleResponse( Response response, ContextResourceClient client )
        {
            T result = client.getContextResourceClientFactory().readResponse( response, resultType );
            return resultHandler.handleResult( result, client );
        }
    };
    return this;
}
 
Example #17
Source File: ErrorHandler.java    From attic-polygene-java with Apache License 2.0 5 votes vote down vote up
@Override
public HandlerCommand handleResponse( Response response, ContextResourceClient client )
{
    for( Map.Entry<Predicate<Response>, ResponseHandler> specificationResponseHandlerEntry : handlers.entrySet() )
    {
        if (specificationResponseHandlerEntry.getKey().test( response ))
        {
            return specificationResponseHandlerEntry.getValue().handleResponse( response, client );
        }
    }

    // No handlers, throw exception
    throw new ResourceException( response.getStatus() );
}
 
Example #18
Source File: GeoWaveOperationFinder.java    From geowave with Apache License 2.0 5 votes vote down vote up
@Override
public ServerResource create(
    final Class<? extends ServerResource> targetClass,
    final Request request,
    final Response response) {
  try {
    return new GeoWaveOperationServiceWrapper<>(
        operation.getClass().newInstance(),
        defaultConfigFile);
  } catch (InstantiationException | IllegalAccessException e) {
    getLogger().log(Level.SEVERE, "Unable to instantiate Service Resource", e);
    return null;
  }
}
 
Example #19
Source File: ContextResource.java    From attic-polygene-java with Apache License 2.0 5 votes vote down vote up
private void result( Object resultValue )
    throws Exception
{
    if( resultValue != null )
    {
        if( !responseWriter.writeResponse( resultValue, Response.getCurrent() ) )
        {
            throw new ResourceException( Status.SERVER_ERROR_INTERNAL, "No result writer for type " + resultValue.getClass()
                .getName() );
        }
    }
}
 
Example #20
Source File: ContextResource.java    From attic-polygene-java with Apache License 2.0 5 votes vote down vote up
@Override
public final void handle( Request request, Response response )
{
    ObjectSelection objectSelection = current();

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

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

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

        if( segments.size() > 0 )
        {
            handleSubResource( segment );
        }
        else
        {
            handleResource( segment );
        }
    }
}
 
Example #21
Source File: TestHelixAdminScenariosRest.java    From helix with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetResources() throws IOException {
  final String clusterName = "TestTagAwareness_testGetResources";
  final String TAG = "tag";
  final String URL_BASE =
      "http://localhost:" + ADMIN_PORT + "/clusters/" + clusterName + "/resourceGroups";

  _gSetupTool.addCluster(clusterName, true);
  HelixAdmin admin = _gSetupTool.getClusterManagementTool();

  // Add a tagged resource
  IdealState taggedResource = new IdealState("taggedResource");
  taggedResource.setInstanceGroupTag(TAG);
  taggedResource.setStateModelDefRef("OnlineOffline");
  admin.addResource(clusterName, taggedResource.getId(), taggedResource);

  // Add an untagged resource
  IdealState untaggedResource = new IdealState("untaggedResource");
  untaggedResource.setStateModelDefRef("OnlineOffline");
  admin.addResource(clusterName, untaggedResource.getId(), untaggedResource);

  // Now make a REST call for all resources
  Reference resourceRef = new Reference(URL_BASE);
  Request request = new Request(Method.GET, resourceRef);
  Response response = _gClient.handle(request);
  ZNRecord responseRecord =
      ClusterRepresentationUtil.JsonToObject(ZNRecord.class, response.getEntityAsText());

  // Ensure that the tagged resource has information and the untagged one doesn't
  Assert.assertNotNull(responseRecord.getMapField("ResourceTags"));
  Assert
      .assertEquals(TAG, responseRecord.getMapField("ResourceTags").get(taggedResource.getId()));
  Assert.assertFalse(responseRecord.getMapField("ResourceTags").containsKey(
      untaggedResource.getId()));
}
 
Example #22
Source File: AuthTokenVerifier.java    From microservices-comparison with Apache License 2.0 5 votes vote down vote up
@Override
public int verify(Request request, Response response) {
    final String token;

    try {
        ChallengeResponse cr = request.getChallengeResponse();
        if (cr == null) {
            return RESULT_MISSING;
        } else if (ChallengeScheme.HTTP_OAUTH_BEARER.equals(cr.getScheme())) {
            final String bearer = cr.getRawValue();
            if (bearer == null || bearer.isEmpty()) {
                return RESULT_MISSING;
            }
            token = bearer;
        } else {
            return RESULT_UNSUPPORTED;
        }
    } catch (Exception ex) {
        return RESULT_INVALID;
    }

    Try<User> user = accessTokenVerificationCommandFactory.createVerificationCommand(token).executeCommand();
    return user.map(u -> {
        org.restlet.security.User restletUser = createRestletUser(u);
        request.getClientInfo().setUser(restletUser);
        request.getAttributes().put("token", token);
        return RESULT_VALID;
    }).orElse(RESULT_INVALID);
}
 
Example #23
Source File: RestApiServer.java    From floodlight_with_topoguard with Apache License 2.0 5 votes vote down vote up
public void run(FloodlightModuleContext fmlContext, String restHost, int restPort) {
    setStatusService(new StatusService() {
        @Override
        public Representation getRepresentation(Status status,
                                                Request request,
                                                Response response) {
            return new JacksonRepresentation<Status>(status);
        }                
    });
    
    // Add everything in the module context to the rest
    for (Class<? extends IFloodlightService> s : fmlContext.getAllServices()) {
        if (logger.isTraceEnabled()) {
            logger.trace("Adding {} for service {} into context",
                         s.getCanonicalName(), fmlContext.getServiceImpl(s));
        }
        context.getAttributes().put(s.getCanonicalName(), 
                                    fmlContext.getServiceImpl(s));
    }
    
    // Start listening for REST requests
    try {
        final Component component = new Component();
        if (restHost == null) {
        	component.getServers().add(Protocol.HTTP, restPort);
        } else {
        	component.getServers().add(Protocol.HTTP, restHost, restPort);
        }
        component.getClients().add(Protocol.CLAP);
        component.getDefaultHost().attach(this);
        component.start();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example #24
Source File: JacksonRepresentationImpl.java    From ontopia with Apache License 2.0 5 votes vote down vote up
@Override
protected ObjectMapper createObjectMapper() {
	ObjectMapper mapper = super.createObjectMapper();
	mapper.addMixInAnnotations(LocatorIF.class, MLocator.class);
	mapper.addMixInAnnotations(TopicIF.class, MTopic.class);
	mapper.addMixInAnnotations(TopicNameIF.class, MTopicName.class);
	mapper.addMixInAnnotations(VariantNameIF.class, MVariantName.class);
	mapper.addMixInAnnotations(OccurrenceIF.class, MOccurrence.class);
	mapper.addMixInAnnotations(AssociationIF.class, MAssociation.class);
	mapper.addMixInAnnotations(AssociationRoleIF.class, MAssociationRole.class);
	mapper.addMixInAnnotations(TopicMapIF.class, MTopicMapAsValue.class);
	mapper.addMixInAnnotations(TopicMapReferenceIF.class, MTopicMapReference.class);
	mapper.addMixInAnnotations(TopicMapSourceIF.class, MTopicMapSource.class);
	
	@SuppressWarnings("unchecked")
	Map<Class<?>, Class<?>> additional = (Map<Class<?>, Class<?>>) Response.getCurrent().getAttributes().get(ADDITIONAL_MIXINS_ATTRIBUTE);

	if ((additional != null) && (!additional.isEmpty())) {
		for (Map.Entry<Class<?>, Class<?>> entry : additional.entrySet()) {
			mapper.addMixInAnnotations(entry.getKey(), entry.getValue());
		}
	}
	
	for (JsonParser.Feature feature : JsonParser.Feature.values()) {
		Parameter parameter = ContextUtils.getParameter(ContextUtils.getCurrentApplicationContext(), JSONPARSER_FEATURE + feature.name());
		if (parameter != null) {
			mapper.configure(feature, ContextUtils.getParameterAsBoolean(parameter, feature.enabledByDefault() || DEFAULT_PARSER_FEATURES.contains(feature)));
		}
	}
	
	return mapper;
}
 
Example #25
Source File: OntopiaStatusService.java    From ontopia with Apache License 2.0 5 votes vote down vote up
@Override
public Representation getRepresentation(Status status, Request request, Response response) {
	//if (status.isClientError()) {
		return new JacksonRepresentation<>(new Error(status));
	//}
	//return null;
}
 
Example #26
Source File: AuthenticationVerifier.java    From vicinity-gateway-api with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Overridden method from super class.  
 */
@Override
public int verify(Request request, Response response) {
	
	ChallengeResponse cr = request.getChallengeResponse();
	
	if (cr == null){
		logger.info("Missing credentials in request from a client with IP " 
									+ request.getClientInfo().getAddress() + ".");
		return Verifier.RESULT_MISSING;
	}
	
	String objectId = cr.getIdentifier();
	String password = new String(cr.getSecret());
	
	if (communicationManager.isConnected(objectId)){
		// if the client is already connected, just verify the password
		if (!communicationManager.verifyPassword(objectId, password)){
			logger.info("Invalid credentials in request from a client with IP " 
					+ request.getClientInfo().getAddress() + ".");
			return Verifier.RESULT_INVALID;
		}
	} else {
		// if not, establish a connection
		StatusMessage statusMessage = communicationManager.establishConnection(objectId, password); 
		if (statusMessage.isError()){
			logger.info("Invalid credentials in request from a client with IP " 
										+ request.getClientInfo().getAddress() + ".");
			return Verifier.RESULT_INVALID;
		}
	}
	
	logger.info("Valid credentials received from a client with IP " + request.getClientInfo().getAddress() + ".");
	return Verifier.RESULT_VALID;
}
 
Example #27
Source File: LocalOAuth2Main.java    From DeviceConnect-Android with MIT License 5 votes vote down vote up
/**
 * 認可コードを渡してアクセストークンを取得する.
 * 
 * @param client クライアント
 * @param authCode 認可コード(TokenManager.sessionsに存在するキー値を設定する)
 * @param applicationName アプリケーション名
 * @return not null: アクセストークン / null: アクセストークン取得失敗
 */
private String callAccessTokenServerResource(final Client client, final String authCode,
        final String applicationName) {

    Request request = new Request();
    ClientInfo clientInfo = new ClientInfo();
    org.restlet.security.User user = new org.restlet.security.User(client.getClientId());
    clientInfo.setUser(user);
    request.setClientInfo(clientInfo);

    Response response = new Response(request);
    AccessTokenServerResource.init(request, response);

    // 入力値(アプリケーション名はbase64エンコードする)
    String base64ApplicationName = Base64.encodeToString(applicationName.getBytes(), Base64.URL_SAFE|Base64.NO_WRAP);
    StringRepresentation input = new StringRepresentation("grant_type=authorization_code&code=" + authCode + "&"
            + AccessTokenServerResource.REDIR_URI + "=" + DUMMY_REDIRECT_URI + "&"
            + AccessTokenServerResource.APPLICATION_NAME + "=" + base64ApplicationName);
    try {
        ResultRepresentation resultRepresentation = (ResultRepresentation) AccessTokenServerResource
                .requestToken(input);
        if (resultRepresentation.getResult()) {
            return resultRepresentation.getText();
        }
    } catch (JSONException | OAuthException e) {
        e.printStackTrace();
    }
    return null;
}
 
Example #28
Source File: GeoWaveOperationServiceWrapperTest.java    From geowave with Apache License 2.0 5 votes vote down vote up
@Test
public void postMethodReturnsSuccessStatus() throws Exception {

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

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

  classUnderTest = new GeoWaveOperationServiceWrapper(operation, null);
  classUnderTest.setResponse(new Response(null));
  classUnderTest.restPost(mockedRequest(MediaType.APPLICATION_JSON));
  Assert.assertEquals(
      successStatusIs200,
      classUnderTest.getResponse().getStatus().equals(Status.SUCCESS_OK));
}
 
Example #29
Source File: LoginResource.java    From attic-polygene-java with Apache License 2.0 5 votes vote down vote up
public Representation login( String name, String password )
{
    context( Login.class ).login( name, password );

    EmptyRepresentation rep = new EmptyRepresentation();
    Response.getCurrent().getCookieSettings().add( "user", name );
    return rep;
}
 
Example #30
Source File: ResourceValidity.java    From attic-polygene-java with Apache License 2.0 5 votes vote down vote up
void updateResponse( Response response )
{
    if( entity != null )
    {
        EntityState state = spi.entityStateOf( entity );
        Tag tag = new Tag( state.entityReference().identity() + "/" + state.version() );
        response.getEntity().setModificationDate( java.util.Date.from( state.lastModified() ) );
        response.getEntity().setTag( tag );
    }
}