Search in sources :

Example 6 with IteratorEnumeration

use of org.apache.commons.collections.iterators.IteratorEnumeration in project atlas by apache.

the class AtlasAuthenticationFilter method init.

/**
 * Initialize the filter.
 *
 * @param filterConfig filter configuration.
 * @throws ServletException thrown if the filter could not be initialized.
 */
@Override
public void init(FilterConfig filterConfig) throws ServletException {
    LOG.info("AtlasAuthenticationFilter initialization started");
    final FilterConfig globalConf = filterConfig;
    final Map<String, String> params = new HashMap<>();
    try {
        configuration = ApplicationProperties.get();
    } catch (Exception e) {
        throw new ServletException(e);
    }
    if (configuration != null) {
        headerProperties = ConfigurationConverter.getProperties(configuration.subset("atlas.headers"));
    }
    String tokenValidityStr = configuration.getString(CONFIG_KERBEROS_TOKEN_VALIDITY);
    if (StringUtils.isNotBlank(tokenValidityStr)) {
        try {
            Long tokenValidity = Long.parseLong(tokenValidityStr);
            if (tokenValidity > 0) {
                params.put(AuthenticationFilter.AUTH_TOKEN_VALIDITY, tokenValidity.toString());
            } else {
                throw new ServletException(tokenValidity + ": invalid value for property '" + CONFIG_KERBEROS_TOKEN_VALIDITY + "'. Must be a positive integer");
            }
        } catch (NumberFormatException e) {
            throw new ServletException(tokenValidityStr + ": invalid value for property '" + CONFIG_KERBEROS_TOKEN_VALIDITY + "'. Must be a positive integer", e);
        }
    }
    FilterConfig filterConfig1 = new FilterConfig() {

        @Override
        public ServletContext getServletContext() {
            if (globalConf != null) {
                return globalConf.getServletContext();
            } else {
                return nullContext;
            }
        }

        @SuppressWarnings("unchecked")
        @Override
        public Enumeration<String> getInitParameterNames() {
            return new IteratorEnumeration(params.keySet().iterator());
        }

        @Override
        public String getInitParameter(String param) {
            return params.get(param);
        }

        @Override
        public String getFilterName() {
            return "AtlasAuthenticationFilter";
        }
    };
    super.init(filterConfig1);
    optionsServlet = new HttpServlet() {
    };
    optionsServlet.init();
}
Also used : ServletException(javax.servlet.ServletException) IteratorEnumeration(org.apache.commons.collections.iterators.IteratorEnumeration) HttpServlet(javax.servlet.http.HttpServlet) FilterConfig(javax.servlet.FilterConfig) AuthenticationException(org.apache.hadoop.security.authentication.client.AuthenticationException) ServletException(javax.servlet.ServletException) SignerException(org.apache.hadoop.security.authentication.util.SignerException) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException)

Example 7 with IteratorEnumeration

use of org.apache.commons.collections.iterators.IteratorEnumeration in project structr by structr.

the class RestDataSource method getData.

// FIXME: this method is needed by the websocket search command because there is no reference node for the above method
public List<GraphObject> getData(final RenderContext renderContext, final String restQuery) throws FrameworkException {
    final Map<Pattern, Class<? extends Resource>> resourceMap = new LinkedHashMap<>();
    final SecurityContext securityContext = renderContext.getSecurityContext();
    ResourceProvider resourceProvider = renderContext.getResourceProvider();
    if (resourceProvider == null) {
        try {
            resourceProvider = UiResourceProvider.class.newInstance();
        } catch (Throwable t) {
            logger.error("Couldn't establish a resource provider", t);
            return Collections.EMPTY_LIST;
        }
    }
    // inject resources
    resourceMap.putAll(resourceProvider.getResources());
    Value<String> propertyView = new ThreadLocalPropertyView();
    propertyView.set(securityContext, PropertyView.Ui);
    HttpServletRequest request = securityContext.getRequest();
    if (request == null) {
        request = renderContext.getRequest();
    }
    // initialize variables
    // mimic HTTP request
    final HttpServletRequest wrappedRequest = new HttpServletRequestWrapper(request) {

        @Override
        public Enumeration<String> getParameterNames() {
            return new IteratorEnumeration(getParameterMap().keySet().iterator());
        }

        @Override
        public String getParameter(final String key) {
            String[] p = getParameterMap().get(key);
            return p != null ? p[0] : null;
        }

        @Override
        public String[] getParameterValues(final String key) {
            return getParameterMap().get(key);
        }

        @Override
        public Map<String, String[]> getParameterMap() {
            String[] parts = StringUtils.split(getQueryString(), "&");
            Map<String, String[]> parameterMap = new HashMap();
            for (String p : parts) {
                String[] kv = StringUtils.split(p, "=");
                if (kv.length > 1) {
                    parameterMap.put(kv[0], new String[] { kv[1] });
                }
            }
            return parameterMap;
        }

        @Override
        public String getQueryString() {
            return StringUtils.substringAfter(restQuery, "?");
        }

        @Override
        public String getPathInfo() {
            return StringUtils.substringBefore(restQuery, "?");
        }

        @Override
        public StringBuffer getRequestURL() {
            return new StringBuffer(restQuery);
        }
    };
    // store original request
    final HttpServletRequest origRequest = securityContext.getRequest();
    // update request in security context
    securityContext.setRequest(wrappedRequest);
    // HttpServletResponse response = renderContext.getResponse();
    Resource resource = null;
    try {
        resource = ResourceHelper.applyViewTransformation(wrappedRequest, securityContext, ResourceHelper.optimizeNestedResourceChain(securityContext, wrappedRequest, resourceMap, propertyView), propertyView);
    } catch (IllegalPathException | NotFoundException e) {
        logger.warn("Illegal path for REST query: {}", restQuery);
    }
    // reset request to old context
    securityContext.setRequest(origRequest);
    if (resource == null) {
        return Collections.EMPTY_LIST;
    }
    // experimental: disable result count, prevents instantiation
    // of large collections just for counting all the objects..
    securityContext.ignoreResultCount(true);
    // TODO: decide if we need to rest the REST request here
    // securityContext.checkResourceAccess(request, resource.getResourceSignature(), resource.getGrant(request, response), PropertyView.Ui);
    // add sorting & paging
    String pageSizeParameter = wrappedRequest.getParameter(JsonRestServlet.REQUEST_PARAMETER_PAGE_SIZE);
    String pageParameter = wrappedRequest.getParameter(JsonRestServlet.REQUEST_PARAMETER_PAGE_NUMBER);
    String sortOrder = wrappedRequest.getParameter(JsonRestServlet.REQUEST_PARAMETER_SORT_ORDER);
    String sortKeyName = wrappedRequest.getParameter(JsonRestServlet.REQUEST_PARAMETER_SORT_KEY);
    boolean sortDescending = (sortOrder != null && "desc".equals(sortOrder.toLowerCase()));
    int pageSize = parseInt(pageSizeParameter, NodeFactory.DEFAULT_PAGE_SIZE);
    int page = parseInt(pageParameter, NodeFactory.DEFAULT_PAGE);
    PropertyKey sortKey = null;
    // set sort key
    if (sortKeyName != null) {
        Class<? extends GraphObject> type = resource.getEntityClass();
        if (type == null) {
            // fallback to default implementation
            // if no type can be determined
            type = AbstractNode.class;
        }
        sortKey = StructrApp.getConfiguration().getPropertyKeyForDatabaseName(type, sortKeyName, false);
    }
    // do action
    Result result = Result.EMPTY_RESULT;
    try {
        result = resource.doGet(sortKey, sortDescending, pageSize, page);
    } catch (NotFoundException nfe) {
        logger.warn("No result from internal REST query: {}", restQuery);
    }
    result.setIsCollection(resource.isCollectionResource());
    result.setIsPrimitiveArray(resource.isPrimitiveArray());
    // Integer rawResultCount = (Integer) Services.getAttribute(NodeFactory.RAW_RESULT_COUNT + Thread.currentThread().getId());
    PagingHelper.addPagingParameter(result, pageSize, page);
    List<GraphObject> res = result.getResults();
    renderContext.setResult(result);
    return res != null ? res : Collections.EMPTY_LIST;
}
Also used : IllegalPathException(org.structr.rest.exception.IllegalPathException) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) NotFoundException(org.structr.rest.exception.NotFoundException) GraphObject(org.structr.core.GraphObject) LinkedHashMap(java.util.LinkedHashMap) Result(org.structr.core.Result) HttpServletRequest(javax.servlet.http.HttpServletRequest) HttpServletRequestWrapper(javax.servlet.http.HttpServletRequestWrapper) ResourceProvider(org.structr.rest.ResourceProvider) UiResourceProvider(org.structr.web.common.UiResourceProvider) Pattern(java.util.regex.Pattern) IteratorEnumeration(org.apache.commons.collections.iterators.IteratorEnumeration) Resource(org.structr.rest.resource.Resource) UiResourceProvider(org.structr.web.common.UiResourceProvider) SecurityContext(org.structr.common.SecurityContext) PropertyKey(org.structr.core.property.PropertyKey)

Example 8 with IteratorEnumeration

use of org.apache.commons.collections.iterators.IteratorEnumeration in project structr by structr.

the class WrappedRestCommand method processMessage.

@Override
public void processMessage(final WebSocketMessage webSocketData) throws FrameworkException {
    final Map<String, Object> nodeData = webSocketData.getNodeData();
    final String method = (String) nodeData.get("method");
    if (method == null || !(method.equals("POST") || method.equals("PUT"))) {
        logger.warn("Method not supported: {}", method);
        getWebSocket().send(MessageBuilder.wrappedRest().code(422).message("Method not supported: " + method).build(), true);
        return;
    }
    ResourceProvider resourceProvider;
    try {
        resourceProvider = UiResourceProvider.class.newInstance();
    } catch (Throwable t) {
        logger.error("Couldn't establish a resource provider", t);
        getWebSocket().send(MessageBuilder.wrappedRest().code(422).message("Couldn't establish a resource provider").build(), true);
        return;
    }
    final Map<Pattern, Class<? extends Resource>> resourceMap = new LinkedHashMap<>();
    resourceMap.putAll(resourceProvider.getResources());
    final StructrWebSocket socket = this.getWebSocket();
    final String url = (String) nodeData.get("url");
    // mimic HTTP request
    final HttpServletRequest wrappedRequest = new HttpServletRequestWrapper(socket.getRequest()) {

        @Override
        public Enumeration<String> getParameterNames() {
            return new IteratorEnumeration(getParameterMap().keySet().iterator());
        }

        @Override
        public String getParameter(String key) {
            String[] p = getParameterMap().get(key);
            return p != null ? p[0] : null;
        }

        @Override
        public Map<String, String[]> getParameterMap() {
            String[] parts = StringUtils.split(getQueryString(), "&");
            Map<String, String[]> parameterMap = new HashMap();
            for (String p : parts) {
                String[] kv = StringUtils.split(p, "=");
                if (kv.length > 1) {
                    parameterMap.put(kv[0], new String[] { kv[1] });
                }
            }
            return parameterMap;
        }

        @Override
        public String getQueryString() {
            return StringUtils.substringAfter(url, "?");
        }

        @Override
        public String getPathInfo() {
            return StringUtils.substringBefore(url, "?");
        }

        @Override
        public StringBuffer getRequestURL() {
            return new StringBuffer(url);
        }
    };
    Resource resource;
    final StaticValue fakePropertyView = new StaticValue(PropertyView.Public);
    try {
        resource = ResourceHelper.applyViewTransformation(wrappedRequest, socket.getSecurityContext(), ResourceHelper.optimizeNestedResourceChain(socket.getSecurityContext(), wrappedRequest, resourceMap, fakePropertyView), fakePropertyView);
    } catch (IllegalPathException | NotFoundException e) {
        logger.warn("Illegal path for REST query");
        getWebSocket().send(MessageBuilder.wrappedRest().code(422).message("Illegal path for REST query").build(), true);
        return;
    }
    final String data = (String) nodeData.get("data");
    final Gson gson = new GsonBuilder().create();
    final Map<String, Object> jsonData = gson.fromJson(data, Map.class);
    RestMethodResult result = null;
    switch(method) {
        case "PUT":
            // we want to update data
            result = resource.doPut(jsonData);
            break;
        case "POST":
            // we either want to create data or call a method on an object
            result = resource.doPost(jsonData);
            break;
    }
    // right now we do not send messages
    if (result != null) {
    // getWebSocket().send(MessageBuilder.wrappedRest().code(result.getResponseCode()).message(result.jsonMessage()).build(), true);
    }
}
Also used : IllegalPathException(org.structr.rest.exception.IllegalPathException) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) StructrWebSocket(org.structr.websocket.StructrWebSocket) NotFoundException(org.structr.rest.exception.NotFoundException) Gson(com.google.gson.Gson) LinkedHashMap(java.util.LinkedHashMap) HttpServletRequest(javax.servlet.http.HttpServletRequest) HttpServletRequestWrapper(javax.servlet.http.HttpServletRequestWrapper) ResourceProvider(org.structr.rest.ResourceProvider) UiResourceProvider(org.structr.web.common.UiResourceProvider) Pattern(java.util.regex.Pattern) IteratorEnumeration(org.apache.commons.collections.iterators.IteratorEnumeration) GsonBuilder(com.google.gson.GsonBuilder) Resource(org.structr.rest.resource.Resource) StaticValue(org.structr.core.StaticValue) UiResourceProvider(org.structr.web.common.UiResourceProvider) RestMethodResult(org.structr.rest.RestMethodResult)

Example 9 with IteratorEnumeration

use of org.apache.commons.collections.iterators.IteratorEnumeration in project incubator-atlas by apache.

the class AtlasAuthenticationFilter method init.

/**
 * Initialize the filter.
 *
 * @param filterConfig filter configuration.
 * @throws ServletException thrown if the filter could not be initialized.
 */
@Override
public void init(FilterConfig filterConfig) throws ServletException {
    LOG.info("AtlasAuthenticationFilter initialization started");
    final FilterConfig globalConf = filterConfig;
    final Map<String, String> params = new HashMap<>();
    try {
        configuration = ApplicationProperties.get();
    } catch (Exception e) {
        throw new ServletException(e);
    }
    if (configuration != null) {
        headerProperties = ConfigurationConverter.getProperties(configuration.subset("atlas.headers"));
    }
    FilterConfig filterConfig1 = new FilterConfig() {

        @Override
        public ServletContext getServletContext() {
            if (globalConf != null) {
                return globalConf.getServletContext();
            } else {
                return nullContext;
            }
        }

        @SuppressWarnings("unchecked")
        @Override
        public Enumeration<String> getInitParameterNames() {
            return new IteratorEnumeration(params.keySet().iterator());
        }

        @Override
        public String getInitParameter(String param) {
            return params.get(param);
        }

        @Override
        public String getFilterName() {
            return "AtlasAuthenticationFilter";
        }
    };
    super.init(filterConfig1);
    optionsServlet = new HttpServlet() {
    };
    optionsServlet.init();
}
Also used : ServletException(javax.servlet.ServletException) IteratorEnumeration(org.apache.commons.collections.iterators.IteratorEnumeration) HttpServlet(javax.servlet.http.HttpServlet) FilterConfig(javax.servlet.FilterConfig) AuthenticationException(org.apache.hadoop.security.authentication.client.AuthenticationException) ServletException(javax.servlet.ServletException) SignerException(org.apache.hadoop.security.authentication.util.SignerException) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException)

Aggregations

IteratorEnumeration (org.apache.commons.collections.iterators.IteratorEnumeration)9 HashMap (java.util.HashMap)5 FilterConfig (javax.servlet.FilterConfig)5 IOException (java.io.IOException)3 UnknownHostException (java.net.UnknownHostException)2 Enumeration (java.util.Enumeration)2 LinkedHashMap (java.util.LinkedHashMap)2 Pattern (java.util.regex.Pattern)2 ServletContext (javax.servlet.ServletContext)2 ServletException (javax.servlet.ServletException)2 HttpServlet (javax.servlet.http.HttpServlet)2 HttpServletRequest (javax.servlet.http.HttpServletRequest)2 HttpServletRequestWrapper (javax.servlet.http.HttpServletRequestWrapper)2 AuthenticationException (org.apache.hadoop.security.authentication.client.AuthenticationException)2 SignerException (org.apache.hadoop.security.authentication.util.SignerException)2 ZkController (org.apache.solr.cloud.ZkController)2 ResourceProvider (org.structr.rest.ResourceProvider)2 IllegalPathException (org.structr.rest.exception.IllegalPathException)2 NotFoundException (org.structr.rest.exception.NotFoundException)2 Resource (org.structr.rest.resource.Resource)2