@Override public void serialize(RestEntity entity, OutputStream outputStream) throws RestException { if(entity instanceof StreamableEntityCollection) { StreamableEntityCollection entityCollection = (StreamableEntityCollection) entity; generateEntityOutput(entityCollection.getSize(), entityCollection.getTimeMilliseconds(), entityCollection.getResult(), outputStream); } else { throw new RestException("Unable to serialize the entity, not of type: " + StreamableEntityCollection.class.getName()); } }
private RestEntity requestById(StorageService storageService, String requestedId, RequestContext context) throws JasDBStorageException { Entity entity = storageService.getEntityById(context, requestedId); if(entity != null) { return new StreamedEntity(entity); } else { return new ErrorEntity(404, "No entity was found with id: " + requestedId); } }
private StreamableEntityCollection handleCollection(HttpServletRequest request, String instanceId, String bagName, int max) throws JasDBStorageException { StorageService storageService = storageServiceFactory.getOrCreateStorageService(instanceId, bagName); long start = System.currentTimeMillis(); QueryResult queryResult; if(max != -1) { queryResult = storageService.getEntities(getRequestContext(request), max); } else { queryResult = storageService.getEntities(getRequestContext(request)); } StreamableEntityCollection collection = new StreamableEntityCollection(queryResult); long end = System.currentTimeMillis(); collection.setTimeMilliseconds((end - start)); return collection; } }
@Override public Entity insertEntity(RemotingContext context, String instance, String bag, Entity entity) throws RemoteException { String connectionString = new RestConnectionBuilder().instance(instance).bag(bag).entities().getConnectionString(); try { ByteArrayOutputStream bos = new ByteArrayOutputStream(); new JsonRestResponseHandler().serialize(new StreamedEntity(entity), bos); ClientResponse clientResponse = doInternalRequest(context, connectionString, new HashMap<>(), bos.toByteArray(), REQUEST_MODE.POST); try { StreamedEntity returnedEntity = new JsonRestResponseHandler().deserialize(StreamedEntity.class, clientResponse.getEntityInputStream()); entity.setInternalId(returnedEntity.getEntity().getInternalId()); return returnedEntity.getEntity(); } finally { clientResponse.close(); } } catch(RestException e) { throw new RemoteException("Unable to insert entity on remote destination", e); } }
@Override public void serialize(RestEntity entity, OutputStream outputStream) throws RestException { if(entity instanceof StreamedEntity) { try { StreamedEntity streamedEntity = (StreamedEntity) entity; JsonGenerator generator = factory.createGenerator(outputStream); generator.configure(JsonGenerator.Feature.AUTO_CLOSE_TARGET, false); generator.configure(JsonGenerator.Feature.FLUSH_PASSED_TO_STREAM, false); try { JsonEntitySerializer entitySerializer = new JsonEntitySerializer(); entitySerializer.serializeEntity(streamedEntity.getEntity(), generator); } finally { generator.close(); } } catch(IOException | MetadataParseException e) { throw new RestException("Unable to serialize entity", e); } } else { throw new RestException("Unable to serialize entity not of type Entity"); } }
private QueryResult parseAsEntityCollection(ClientResponse response) throws RemoteException { try { StreamableEntityCollection entityCollection = new JsonRestResponseHandler().deserialize(StreamableEntityCollection.class, new WrappedInputStream(response)); return entityCollection.getResult(); } catch(RestException e) { throw new RemoteException("Unable to parse remote entity data", e); } }
log.debug("Parsing a stream of entities of size: {} queried in: {} ms.", size, timeMilliseconds); QueryResult result = new StreamableQueryResult(parser, size, inputStream); return dataType.cast(new StreamableEntityCollection(result));
@Override public UserSession loadSession(String userName, String password) throws RemoteException { Map<String, String> parameters = Maps.newHashMap(); parameters.put("client_id", userName); parameters.put("client_secret", password); ClientResponse response = doRequest(new RemotingContext(true), "token", parameters, "", REQUEST_MODE.POST); try { OauthToken token = new JsonRestResponseHandler().deserialize(OauthToken.class, response.getEntityInputStream()); return new UserSessionImpl(token.getSessionId(), token.getOauthToken(), null, null); } catch(RestException e) { throw new RemoteException("Unable to retrieve authentication token", e); } finally { response.close(); } } }
private RestEntity doModificationOperation(String instanceId, String bagName, String rawData, RequestContext context, OPERATION_TYPE type) throws RestException { if(stringNotEmpty(instanceId) && stringNotEmpty(bagName)) { LOG.debug("Raw entity data received: {}", rawData); StreamedEntity streamedEntity = ENTITY_HANDLER.deserialize(StreamedEntity.class, rawData); Entity storeEntity = streamedEntity.getEntity(); try { StorageService storageService = storageServiceFactory.getOrCreateStorageService(instanceId, bagName); if(type == OPERATION_TYPE.UPDATE) { LOG.debug("Updating entity with id: {}", storeEntity.getInternalId()); storageService.persistEntity(context, storeEntity); } else if(type == OPERATION_TYPE.INSERT) { LOG.debug("Inserting new entity into bag: {}", bagName); storageService.insertEntity(context, storeEntity); } return new StreamedEntity(storeEntity); } catch(JasDBStorageException e) { throw new RestException("Unable to store entity: " + e.getMessage()); } } else { throw new SyntaxException("Cannot store entity, no Bag specified"); } }
@Override public <T extends RestEntity> T deserialize(Class<T> dataType, String data) throws RestException { JsonEntityDeserializer entityDeserializer = new JsonEntityDeserializer(); try { return dataType.cast(new StreamedEntity(entityDeserializer.deserializeEntity(data))); } catch(MetadataParseException e) { throw new RestException("Unable to parse entity", e); } }
private RestEntity handleQuery(StorageService storageService, InputCondition condition, int begin, int top, List<OrderParam> orderParams, RequestContext context) throws JasDBStorageException { LOG.debug("Query: {} begin: {} top: {}", condition, begin, top); if(condition.getTokenType() == TokenType.LITERAL && ((FieldCondition)condition).getField().equals(FieldCondition.ID_PARAM)) { FieldCondition idCondition = (FieldCondition) condition; return requestById(storageService, idCondition.getValue(), context); } else { QueryBuilder parentBuilder = generateQueryBuilder(condition, QueryBuilder.createBuilder()); setOrderingParams(parentBuilder, orderParams); long start = System.currentTimeMillis(); QueryResult result = storageService.search(context, BuilderTransformer.transformBuilder(parentBuilder), new SearchLimit(begin, top), parentBuilder.getSortParams()); long end = System.currentTimeMillis(); StreamableEntityCollection collection = new StreamableEntityCollection(result); collection.setTimeMilliseconds((end - start)); return collection; } }
@Override public Entity findById(RemotingContext context, String instance, String bag, String id) throws RemoteException { String connectionString = new RestConnectionBuilder().instance(instance).bag(bag).entityById(id).getConnectionString(); try { ClientResponse response = doRequest(context, connectionString); try { StreamedEntity entity = new JsonRestResponseHandler().deserialize(StreamedEntity.class, response.getEntityInputStream()); return entity.getEntity(); } catch (RestException e) { throw new RemoteException("Unable to parse remote entity data", e); } finally { response.close(); } } catch(ResourceNotFoundException e) { LOG.debug("Entity: {} not found in bag: {} on instance: {}", id, bag, instance); return null; } }
@Override public Entity updateEntity(RemotingContext context, String instance, String bag, Entity entity) throws RemoteException { String connectionString = new RestConnectionBuilder().instance(instance).bag(bag).entities().getConnectionString(); try { ByteArrayOutputStream bos = new ByteArrayOutputStream(); new JsonRestResponseHandler().serialize(new StreamedEntity(entity), bos); ClientResponse clientResponse = doRequest(context, connectionString, new HashMap<>(), bos.toString(CHARACTER_ENCODING), REQUEST_MODE.PUT); try { StreamedEntity returnedEntity = new JsonRestResponseHandler().deserialize(StreamedEntity.class, clientResponse.getEntityInputStream()); return returnedEntity.getEntity(); } finally { clientResponse.close(); } } catch(RestException e) { throw new RemoteException("Unable to update entity on remote destination", e); } catch(UnsupportedEncodingException e) { throw new RemoteException("Unable to serialize entity", e); } }
@Override public <T extends RestEntity> T deserialize(Class<T> dataType, InputStream inputStream) throws RestException { try { try (JsonParser parser = factory.createParser(inputStream)) { return dataType.cast(new StreamedEntity(new JsonEntityDeserializer().deserializeEntity(parser))); } } catch(IOException | MetadataParseException e) { throw new RestException("Unable to parse entity", e); } }