private static boolean isClientRequest(String requestContext) { if(StringUtils.stringNotEmpty(requestContext)) { if(requestContext.equals("grid")) { return false; } } return true; }
private String getStandardizedPassword(String password) { if(StringUtils.stringEmpty(password)) { return STANDARD_EMPTY_PASS; } else { return password; } }
@Override public boolean hasInstance(String instanceId) { return StringUtils.stringNotEmpty(instanceId) && instances.containsKey(instanceId); }
public static boolean stringNotEmpty(String string) { return !stringEmpty(string); }
public static List<OrderParam> getOrderParams(String orderBy) throws SyntaxException { if(StringUtils.stringNotEmpty(orderBy)) { Matcher orderMatcher = ORDERBY_PATTERN.matcher(orderBy); List<OrderParam> orderParams = new ArrayList<>(); while(orderMatcher.find()) { String ascendingField = orderMatcher.group(2); String descendingField = orderMatcher.group(4); String noSortDirectionField = orderMatcher.group(6); if(StringUtils.stringNotEmpty(ascendingField)) { orderParams.add(new OrderParam(ascendingField, OrderParam.DIRECTION.ASC)); } else if(StringUtils.stringNotEmpty(descendingField)) { orderParams.add(new OrderParam(descendingField, OrderParam.DIRECTION.DESC)); } else if(StringUtils.stringNotEmpty(noSortDirectionField)) { orderParams.add(new OrderParam(noSortDirectionField, OrderParam.DIRECTION.ASC)); } else { throw new SyntaxException("Unexpected order by syntax: " + orderBy); } } return orderParams; } else { return Collections.emptyList(); } } }
@Override public DBInstance getInstance(String instanceId) throws ConfigurationException { if(StringUtils.stringEmpty(instanceId)) { return getInstance(); } else { if(instances.containsKey(instanceId)) { return instances.get(instanceId); } else { throw new ConfigurationException("No instance was found for id: " + instanceId); } } }
@RequestMapping(value = "/Instances({instanceId})/Bags({bagName})/Entities({entityId})", produces = "application/json", method = DELETE) public RestEntity removeEntry(@PathVariable String instanceId, @PathVariable String bagName, @PathVariable String entityId, HttpServletRequest request) throws RestException { if(stringNotEmpty(instanceId) && stringNotEmpty(bagName) && stringNotEmpty(entityId)) { try { LOG.debug("Doing remove of entity with id: {}", entityId); StorageService storageService = storageServiceFactory.getOrCreateStorageService(instanceId, bagName); storageService.removeEntity(getRequestContext(request), entityId); return null; } catch(JasDBStorageException e) { throw new RestException("Unable to remove entity: " + e.getMessage()); } } else { throw new SyntaxException("Cannot remove entity, invalid parameters for delete operation"); } }
private PropertyMetadata loadProperty(PropertyDescriptor propertyDescriptor) throws JasDBStorageException { Method readMethod = propertyDescriptor.getReadMethod(); Method writeMethod = propertyDescriptor.getWriteMethod(); if(readMethod != null && writeMethod != null) { Optional<JasDBProperty> readAnnotation = getOptionalAnnotation(readMethod, JasDBProperty.class); Optional<JasDBProperty> writeAnnotation = getOptionalAnnotation(writeMethod, JasDBProperty.class); Optional<Id> idAnnotation = getOptionalAnnotation(readMethod, Id.class); if (readAnnotation.isPresent() || writeAnnotation.isPresent()) { TypeMapper typeMapper = getTypeMapper(readMethod); //here a number of override for the property name, first check read method, next write else default to property bean name String propertyName = readAnnotation.isPresent() ? readAnnotation.get().name() : ""; propertyName = StringUtils.stringEmpty(propertyName) ? writeAnnotation.isPresent() ? writeAnnotation.get().name() : "" : propertyName; propertyName = StringUtils.stringEmpty(propertyName) ? propertyDescriptor.getName() : propertyName; boolean nullable = readAnnotation.isPresent() ? readAnnotation.get().nullable() : writeAnnotation.get().nullable(); LOG.debug("Found Entity property: {} nullable: {}", propertyDescriptor.getName(), nullable); return new PropertyMetadataImpl(typeMapper, readMethod, writeMethod, propertyName, idAnnotation.isPresent(), nullable); } } else { LOG.debug("Read or Write method not defined for property: {}", propertyDescriptor.getName()); } return null; }
@Override public DBSession createSession() throws JasDBException { if(StringUtils.stringNotEmpty(instance)) { return new LocalDBSession(instance); } else { return new LocalDBSession(); } }
public JasDBConfigurationLoader() throws ConfigurationException { try { String overrideConfigProperty = System.getProperty("jasdb-config"); if(StringUtils.stringEmpty(overrideConfigProperty)) { this.configuration = XMLConfiguration.loadConfiguration(JASDB_CONFIG); } else { LOG.info("Override configuration path specified: {}", overrideConfigProperty); this.configuration = XMLConfiguration.loadConfiguration(overrideConfigProperty); } } catch (CoreConfigException e) { try { this.configuration = XMLConfiguration.loadConfiguration(FALLBACK_JASDB_XML); } catch(CoreConfigException ex) { throw new ConfigurationException("Unable to load Default JasDB configuration file", ex); } } }
private static long convertUnit(String unit, ValueConverterType converter) throws CoreConfigException { if(StringUtils.stringNotEmpty(unit)) { try { char lastDigit = unit.charAt(unit.length() - 1); lastDigit = Character.toLowerCase(lastDigit); long longUnit = -1; if(Character.isDigit(lastDigit)) { longUnit = Long.valueOf(unit); } else { String value = unit.substring(0, unit.length() - 1); longUnit = Long.valueOf(value); } return converter.convertToLong(lastDigit, longUnit); } catch(NumberFormatException e) { throw new CoreConfigException("Unable to parse value in unit: " + unit, e); } } else { throw new CoreConfigException("Could not parse empty unit"); } }
@Override public Entity deserializeEntity(String serializedEntity) throws MetadataParseException { if(StringUtils.stringNotEmpty(serializedEntity)) { try { JsonParser parser = factory.createParser(serializedEntity); return deserializeEntity(parser); } catch(IOException e) { throw new MetadataParseException("Unable to parse entity", e); } } throw new MetadataParseException("Unable to parse entity metadata, empty content"); }
public static KeyFactory[] parseHeader(String headerDescriptor) throws JasDBStorageException { LOG.debug("Parsing header: {}", headerDescriptor); if(StringUtils.stringNotEmpty(headerDescriptor)) { Matcher matcher = KEY_PATTERN.matcher(headerDescriptor); List<KeyFactory> keyFactoryList = new ArrayList<>(); while(matcher.find()) { String keyName = matcher.group(1) != null ? matcher.group(1) : matcher.group(3); String keyValue = matcher.group(2) != null ? matcher.group(2) : matcher.group(4); if("complexType".equals(keyName)) { LOG.debug("Found complex type: {}", keyValue); KeyFactory[] compositeKeyFactories = parseHeader(keyValue); keyFactoryList.add(new CompositeKeyFactory(new MultiKeyLoaderImpl(KeyNameMapperImpl.create(compositeKeyFactories), compositeKeyFactories))); } else { String[] arguments = keyValue.split(":"); String fieldType = arguments[0]; String[] keyArguments = new String[0]; if(arguments.length > 1) { keyArguments = Arrays.copyOfRange(arguments, 1, arguments.length); } keyFactoryList.add(KeyFactoryManager.createKeyFactory(fieldType, keyName, keyArguments)); } LOG.debug("Found field: {} with type info: {}", keyName, keyValue); } return keyFactoryList.toArray(new KeyFactory[keyFactoryList.size()]); } else { return new KeyFactory[0]; } }
@RequestMapping(value = "/Users({userId})", produces = "application/json", consumes = "application/json", method = DELETE) public RestEntity removeEntry(@PathVariable String userId, HttpServletRequest request) throws RestException { if (StringUtils.stringNotEmpty(userId)) { try { RequestContext requestContext = ControllerUtil.getRequestContext(request); userManager.deleteUser(requestContext.getUserSession(), userId); return null; } catch (JasDBStorageException e) { throw new RestException("Unable to remove user", e); } } else { throw new RestException("Unable to delete user, no id specified"); } } }
@RequestMapping(value = "/Grants({grantId})", produces = "application/json", method = DELETE) public RestEntity removeEntry(@RequestBody RestGrant grant, HttpServletRequest request) throws RestException { if(StringUtils.stringNotEmpty(grant.getObjectName()) && StringUtils.stringNotEmpty(grant.getUsername())) { try { RequestContext requestContext = getRequestContext(request); userManager.revoke(requestContext.getUserSession(), grant.getObjectName(), grant.getUsername()); return null; } catch(JasDBStorageException e) { throw new RestException("Unable to revoke grant", e); } } else { throw new RestException("Cannot remove without user and object specified"); } } }
private void checkToken(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws IOException, ServletException { try { String token = httpServletRequest.getHeader("oauth_token"); String sessionId = httpServletRequest.getHeader("sessionid"); LOG.debug("Token: {} for session: {}", token, sessionId); if(StringUtils.stringNotEmpty(token) && StringUtils.stringNotEmpty(sessionId)) { UserSession session = sessionManager.getSession(sessionId); if(session != null) { CryptoEngine cryptoEngine = CryptoFactory.getEngine(); String expectedTokenHash = cryptoEngine.hash(sessionId, token); if (expectedTokenHash.equals(session.getAccessToken())) { httpServletRequest.setAttribute("session", new UserSessionImpl(sessionId, token, session.getEncryptedContentKey(), session.getUser())); filterChain.doFilter(httpServletRequest, httpServletResponse); } else { handleErrorResponse(httpServletResponse, UNAUTHORIZED_CODE, "Invalid token"); } } else { handleErrorResponse(httpServletResponse, UNAUTHORIZED_CODE, "Invalid token"); } } else { handleErrorResponse(httpServletResponse, UNAUTHORIZED_CODE, "No token"); } } catch(JasDBStorageException e) { LOG.error("Unknown error happened when processing token", e); handleErrorResponse(httpServletResponse, 500, "Unknown error"); } }
if(StringUtils.stringNotEmpty(elementName)) { LOG.trace("Element: {} with conditions: {}", elementName, elementConditions); inputElement = new InputElement(elementName); throw new SyntaxException("Invalid path syntax: " + pathElement); } else if(StringUtils.stringNotEmpty(simpleElementName)) { LOG.trace("Element: {} without conditions", simpleElementName); if(pathElement.contains("(") || pathElement.contains(")")) {
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"); } }
public void configure(Configuration configuration) throws ConfigurationException { String maxMemoryValue = null; String monitorIntervalValue = DEFAULT_MONITOR_INTERVAL; if(configuration != null) { maxMemoryValue = configuration.getAttribute("MaxMemory"); monitorIntervalValue = configuration.getAttribute("MemoryMonitorInterval", DEFAULT_MONITOR_INTERVAL); } long monitorInterval; try { monitorInterval = ValueConverterUtil.convertToMilliseconds(monitorIntervalValue); if(StringUtils.stringNotEmpty(maxMemoryValue)) { maximumMemory = ValueConverterUtil.convertToBytes(maxMemoryValue); } else { maximumMemory = Runtime.getRuntime().maxMemory(); } } catch(CoreConfigException e) { throw new ConfigurationException("Unable to load caching settings", e); } LOG.info("Global cache monitor starting with interval: {} and memory limit: {} bytes", monitorInterval, maximumMemory); this.cacheMonitorThread = new CacheMonitorThread(this, monitorInterval, maximumMemory); this.cacheMonitorThread.start(); }
@Override public QueryResult find(RemotingContext context, String instance, String bag, BlockOperation blockOperation, SearchLimit limit, List<SortParameter> sortParams) throws RemoteException { String query = RestQueryGenerator.generatorQuery(blockOperation); String orderParams = RestQueryGenerator.generateOrderParams(sortParams); String connectionString = new RestConnectionBuilder().instance(instance).bag(bag).entities(query).getConnectionString(); Map<String, String> params = new HashMap<>(); if(limit.getBegin() > 0) { params.put("begin", String.valueOf(limit.getBegin())); } if(limit.getMax() > 0) { params.put("top", String.valueOf(limit.getMax())); } if(StringUtils.stringNotEmpty(orderParams)) params.put("orderBy", orderParams); ClientResponse response = doRequest(context, connectionString, params); return parseAsEntityCollection(response); }