You are viewing a plain text version of this content. The canonical link for it is here.
Posted to issues@nifi.apache.org by bdesert <gi...@git.apache.org> on 2018/02/17 21:57:37 UTC

[GitHub] nifi pull request #2478: NIFI-4833 Add scanHBase Processor

GitHub user bdesert opened a pull request:

    https://github.com/apache/nifi/pull/2478

    NIFI-4833 Add scanHBase Processor

    Thank you for submitting a contribution to Apache NiFi.
    
    In order to streamline the review of the contribution we ask you
    to ensure the following steps have been taken:
    
    ### For all changes:
    - [x] Is there a JIRA ticket associated with this PR? Is it referenced 
         in the commit message?
    
    - [x] Does your PR title start with NIFI-XXXX where XXXX is the JIRA number you are trying to resolve? Pay particular attention to the hyphen "-" character.
    
    - [x] Has your PR been rebased against the latest commit within the target branch (typically master)?
    
    - [ ] Is your initial contribution a single, squashed commit?
    
    ### For code changes:
    - [x] Have you ensured that the full suite of tests is executed via mvn -Pcontrib-check clean install at the root nifi folder?
    - [x] Have you written or updated unit tests to verify your changes?
    - [ ] If adding new dependencies to the code, are these dependencies licensed in a way that is compatible for inclusion under [ASF 2.0](http://www.apache.org/legal/resolved.html#category-a)? 
    - [ ] If applicable, have you updated the LICENSE file, including the main LICENSE file under nifi-assembly?
    - [ ] If applicable, have you updated the NOTICE file, including the main NOTICE file found under nifi-assembly?
    - [x] If adding new Properties, have you added .displayName in addition to .name (programmatic access) for each of the new properties?
    
    ### For documentation related changes:
    - [ ] Have you ensured that format looks appropriate for the output in which it is rendered?
    
    ### Note:
    Please ensure that once the PR is submitted, you check travis-ci for build issues and submit an update to your PR as soon as possible.


You can merge this pull request into a Git repository by running:

    $ git pull https://github.com/bdesert/nifi NIFI-4833-Add-ScanHBase-processor

Alternatively you can review and apply these changes as the patch at:

    https://github.com/apache/nifi/pull/2478.patch

To close this pull request, make a commit to your master/trunk branch
with (at least) the following in the commit message:

    This closes #2478
    
----
commit 39bd6fb5d02eb7dca63830967823a4bb48c5712c
Author: Ed <ed...@...>
Date:   2018-02-17T21:26:04Z

    Add ScanHBase Processor
    
    New processor for scanning HBase records based on verious params like range of rowkeys, range of timestamps. Supports result limit and reverse scan.

commit d2f5410be14a77f64e7ca5593e6c908620a8da58
Author: Ed <ed...@...>
Date:   2018-02-17T21:27:18Z

    Adds Atlas Support for ScanHBase processor
    
    Adds Atlas Support for ScanHBase processor

----


---

[GitHub] nifi pull request #2478: NIFI-4833 Add scanHBase Processor

Posted by bbende <gi...@git.apache.org>.
Github user bbende commented on a diff in the pull request:

    https://github.com/apache/nifi/pull/2478#discussion_r170684472
  
    --- Diff: nifi-nar-bundles/nifi-hbase-bundle/nifi-hbase-processors/src/main/java/org/apache/nifi/hbase/ScanHBase.java ---
    @@ -0,0 +1,564 @@
    +/*
    + * Licensed to the Apache Software Foundation (ASF) under one or more
    + * contributor license agreements.  See the NOTICE file distributed with
    + * this work for additional information regarding copyright ownership.
    + * The ASF licenses this file to You under the Apache License, Version 2.0
    + * (the "License"); you may not use this file except in compliance with
    + * the License.  You may obtain a copy of the License at
    + *
    + *     http://www.apache.org/licenses/LICENSE-2.0
    + *
    + * Unless required by applicable law or agreed to in writing, software
    + * distributed under the License is distributed on an "AS IS" BASIS,
    + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    + * See the License for the specific language governing permissions and
    + * limitations under the License.
    + */
    +package org.apache.nifi.hbase;
    +
    +import org.apache.commons.lang3.StringUtils;
    +import org.apache.nifi.annotation.behavior.InputRequirement;
    +import org.apache.nifi.annotation.behavior.WritesAttribute;
    +import org.apache.nifi.annotation.behavior.WritesAttributes;
    +import org.apache.nifi.annotation.documentation.CapabilityDescription;
    +import org.apache.nifi.annotation.documentation.Tags;
    +import org.apache.nifi.annotation.lifecycle.OnScheduled;
    +import org.apache.nifi.components.AllowableValue;
    +import org.apache.nifi.components.PropertyDescriptor;
    +import org.apache.nifi.components.ValidationContext;
    +import org.apache.nifi.components.ValidationResult;
    +import org.apache.nifi.flowfile.FlowFile;
    +import org.apache.nifi.flowfile.attributes.CoreAttributes;
    +import org.apache.nifi.hbase.io.JsonFullRowSerializer;
    +import org.apache.nifi.hbase.io.JsonQualifierAndValueRowSerializer;
    +import org.apache.nifi.hbase.io.RowSerializer;
    +import org.apache.nifi.hbase.scan.Column;
    +import org.apache.nifi.hbase.scan.ResultCell;
    +import org.apache.nifi.hbase.scan.ResultHandler;
    +import org.apache.nifi.processor.AbstractProcessor;
    +import org.apache.nifi.processor.ProcessContext;
    +import org.apache.nifi.processor.ProcessSession;
    +import org.apache.nifi.processor.Relationship;
    +import org.apache.nifi.processor.exception.ProcessException;
    +import org.apache.nifi.processor.util.StandardValidators;
    +import org.apache.nifi.util.Tuple;
    +
    +import java.io.IOException;
    +import java.nio.charset.Charset;
    +import java.nio.charset.StandardCharsets;
    +import java.util.ArrayList;
    +import java.util.Collection;
    +import java.util.Collections;
    +import java.util.HashMap;
    +import java.util.HashSet;
    +import java.util.Iterator;
    +import java.util.LinkedList;
    +import java.util.List;
    +import java.util.Map;
    +import java.util.Set;
    +import java.util.concurrent.atomic.AtomicReference;
    +import java.util.regex.Pattern;
    +
    +@InputRequirement(InputRequirement.Requirement.INPUT_REQUIRED)
    +@Tags({"hbase", "scan", "fetch", "get"})
    +@CapabilityDescription("Scans and fetches rows from an HBase table. This processor may be used to fetch rows from hbase table by specifying a range of rowkey values (start and/or end ),"
    +        + "by time range, by filter expression, or any combination of them. "
    +        + "Order of records can be controlled by a property Reversed"
    +        + "Number of rows retrieved by the processor can be limited.")
    +@WritesAttributes({
    +        @WritesAttribute(attribute = "hbase.table", description = "The name of the HBase table that the row was fetched from"),
    +        @WritesAttribute(attribute = "hbase.resultset", description = "A JSON document/s representing the row/s. This property is only written when a Destination of flowfile-attributes is selected."),
    +        @WritesAttribute(attribute = "mime.type", description = "Set to application/json when using a Destination of flowfile-content, not set or modified otherwise"),
    +        @WritesAttribute(attribute = "hbase.rows.count", description = "Number of rows in the content of given flow file"),
    +        @WritesAttribute(attribute = "scanhbase.results.found", description = "Indicates whether at least one row has been found in given hbase table with provided conditions. "
    +                + "Could be null (not present) if transfered to FAILURE")
    +})
    +public class ScanHBase extends AbstractProcessor {
    +    //enhanced regex for columns to allow "-" in column qualifier names
    +    static final Pattern COLUMNS_PATTERN = Pattern.compile("\\w+(:(\\w|-)+)?(?:,\\w+(:(\\w|-)+)?)*");
    +    static final byte[] nl = System.lineSeparator().getBytes();
    +
    +    static final PropertyDescriptor HBASE_CLIENT_SERVICE = new PropertyDescriptor.Builder()
    +            .displayName("HBase Client Service")
    +            .name("scanhbase-client-service")
    +            .description("Specifies the Controller Service to use for accessing HBase.")
    +            .required(true)
    +            .identifiesControllerService(HBaseClientService.class)
    +            .build();
    +
    +    static final PropertyDescriptor TABLE_NAME = new PropertyDescriptor.Builder()
    +            .displayName("Table Name")
    +            .name("scanhbase-table-name")
    +            .description("The name of the HBase Table to fetch from.")
    +            .required(true)
    +            .expressionLanguageSupported(true)
    +            .addValidator(StandardValidators.NON_EMPTY_VALIDATOR)
    +            .build();
    +
    +    static final PropertyDescriptor START_ROW = new PropertyDescriptor.Builder()
    +            .displayName("Start rowkey")
    +            .name("scanhbase-start-rowkey")
    +            .description("The rowkey to start scan from.")
    +            .required(false)
    +            .expressionLanguageSupported(true)
    +            .addValidator(StandardValidators.NON_EMPTY_VALIDATOR)
    +            .build();
    +
    +    static final PropertyDescriptor END_ROW = new PropertyDescriptor.Builder()
    +            .displayName("End rowkey")
    +            .name("scanhbase-end-rowkey")
    +            .description("The row key to end scan by.")
    +            .required(false)
    +            .expressionLanguageSupported(true)
    +            .addValidator(StandardValidators.NON_EMPTY_VALIDATOR)
    +            .build();
    +
    +    static final PropertyDescriptor TIME_RANGE_MIN = new PropertyDescriptor.Builder()
    +            .displayName("Time range min")
    +            .name("scanhbase-time-range-min")
    +            .description("Time range min value. Both min and max values for time range should be either blank or provided.")
    +            .required(false)
    +            .expressionLanguageSupported(true)
    +            .addValidator(StandardValidators.LONG_VALIDATOR)
    +            .build();
    +
    +    static final PropertyDescriptor TIME_RANGE_MAX = new PropertyDescriptor.Builder()
    +            .displayName("Time range max")
    +            .name("scanhbase-time-range-max")
    +            .description("Time range max value. Both min and max values for time range should be either blank or provided.")
    +            .required(false)
    +            .expressionLanguageSupported(true)
    +            .addValidator(StandardValidators.LONG_VALIDATOR)
    +            .build();
    +
    +    static final PropertyDescriptor LIMIT_ROWS = new PropertyDescriptor.Builder()
    +            .displayName("Limit rows")
    +            .name("scanhbase-limit")
    +            .description("Limit number of rows retrieved by scan.")
    +            .required(false)
    +            .expressionLanguageSupported(true)
    +            .addValidator(StandardValidators.INTEGER_VALIDATOR)
    +            .build();
    +
    +    static final PropertyDescriptor BULK_SIZE = new PropertyDescriptor.Builder()
    +            .displayName("Max rows per flow file")
    +            .name("scanhbase-bulk-size")
    +            .description("Limits number of rows in single flow file content. Set to 0 to avoid multiple flow files.")
    +            .required(false)
    +            .expressionLanguageSupported(true)
    +            .defaultValue("0")
    +            .addValidator(StandardValidators.INTEGER_VALIDATOR)
    +            .build();
    +
    +    static final PropertyDescriptor REVERSED_SCAN = new PropertyDescriptor.Builder()
    +            .displayName("Reversed order")
    +            .name("scanhbase-reversed-order")
    +            .description("Set whether this scan is a reversed one. This is false by default which means forward(normal) scan.")
    +            .expressionLanguageSupported(false)
    +            .allowableValues("true", "false")
    +            .required(false)
    +            .defaultValue("false")
    +            .addValidator(StandardValidators.BOOLEAN_VALIDATOR)
    +            .build();
    +
    +    static final PropertyDescriptor FILTER_EXPRESSION = new PropertyDescriptor.Builder()
    +            .displayName("Filter expression")
    +            .name("scanhbase-filter-expression")
    +            .description("An HBase filter expression that will be applied to the scan. This property can not be used when also using the Columns property. "
    +                    + "Example: \"ValueFilter( =, 'binaryprefix:commit' )\"")
    +            .required(false)
    +            .expressionLanguageSupported(true)
    +            .addValidator(StandardValidators.NON_EMPTY_VALIDATOR)
    +            .build();
    +
    +    static final PropertyDescriptor COLUMNS = new PropertyDescriptor.Builder()
    +            .displayName("Columns")
    +            .name("scanhbase-columns")
    +            .description("An optional comma-separated list of \"<colFamily>:<colQualifier>\" pairs to fetch. To return all columns " +
    +                    "for a given family, leave off the qualifier such as \"<colFamily1>,<colFamily2>\".")
    +            .required(false)
    +            .expressionLanguageSupported(true)
    +            .addValidator(StandardValidators.createRegexMatchingValidator(COLUMNS_PATTERN))
    +            .build();
    +
    +    static final AllowableValue JSON_FORMAT_FULL_ROW = new AllowableValue("full-row", "full-row",
    +            "Creates a JSON document with the format: {\"row\":<row-id>, \"cells\":[{\"fam\":<col-fam>, \"qual\":<col-val>, \"val\":<value>, \"ts\":<timestamp>}]}.");
    +    static final AllowableValue JSON_FORMAT_QUALIFIER_AND_VALUE = new AllowableValue("col-qual-and-val", "col-qual-and-val",
    +            "Creates a JSON document with the format: {\"<col-qual>\":\"<value>\", \"<col-qual>\":\"<value>\".");
    +
    +    static final PropertyDescriptor JSON_FORMAT = new PropertyDescriptor.Builder()
    +            .displayName("JSON Format")
    +            .name("scanhbase-json-format")
    +            .description("Specifies how to represent the HBase row as a JSON document.")
    +            .required(true)
    +            .allowableValues(JSON_FORMAT_FULL_ROW, JSON_FORMAT_QUALIFIER_AND_VALUE)
    +            .defaultValue(JSON_FORMAT_FULL_ROW.getValue())
    +            .build();
    +
    +    static final PropertyDescriptor DECODE_CHARSET = new PropertyDescriptor.Builder()
    +            .displayName("Decode Character Set")
    +            .name("scanhbase-decode-charset")
    +            .description("The character set used to decode data from HBase.")
    +            .required(true)
    +            .defaultValue("UTF-8")
    +            .addValidator(StandardValidators.CHARACTER_SET_VALIDATOR)
    +            .build();
    +
    +    static final PropertyDescriptor ENCODE_CHARSET = new PropertyDescriptor.Builder()
    +            .displayName("Encode Character Set")
    +            .name("scanhbase-encode-charset")
    +            .description("The character set used to encode the JSON representation of the row.")
    +            .required(true)
    +            .defaultValue("UTF-8")
    +            .addValidator(StandardValidators.CHARACTER_SET_VALIDATOR)
    +            .build();
    +
    +    public static final Relationship REL_ORIGINAL = new Relationship.Builder()
    +            .name("original")
    +            .description("The original input file will be routed to this destination, even if no rows are retrieved based on provided conditions.")
    +            .build();
    +
    +    static final Relationship REL_SUCCESS = new Relationship.Builder()
    +            .name("success")
    +            .description("All successful fetches are routed to this relationship.")
    +            .build();
    +    static final Relationship REL_FAILURE = new Relationship.Builder()
    +            .name("failure")
    +            .description("All failed fetches are routed to this relationship.")
    +            .build();
    +
    +    static final String HBASE_TABLE_ATTR = "hbase.table";
    +    static final String HBASE_ROWS_COUNT_ATTR = "hbase.rows.count";
    +
    +    static final List<PropertyDescriptor> properties;
    +    static {
    +        List<PropertyDescriptor> props = new ArrayList<>();
    +        props.add(HBASE_CLIENT_SERVICE);
    +        props.add(TABLE_NAME);
    +        props.add(START_ROW);
    +        props.add(END_ROW);
    +        props.add(TIME_RANGE_MIN);
    +        props.add(TIME_RANGE_MAX);
    +        props.add(LIMIT_ROWS);
    +        props.add(REVERSED_SCAN);
    +        props.add(BULK_SIZE);
    +        props.add(FILTER_EXPRESSION);
    +        props.add(COLUMNS);
    +        props.add(JSON_FORMAT);
    +        props.add(ENCODE_CHARSET);
    +        props.add(DECODE_CHARSET);
    +        properties = Collections.unmodifiableList(props);
    +    }
    +
    +    static final Set<Relationship> relationships;
    +    static {
    +        Set<Relationship> rels = new HashSet<>();
    +        rels.add(REL_SUCCESS);
    +        rels.add(REL_ORIGINAL);
    +        rels.add(REL_FAILURE);
    +        relationships = Collections.unmodifiableSet(rels);
    +    }
    +
    +    private volatile Charset decodeCharset;
    +    private volatile Charset encodeCharset;
    +    private RowSerializer serializer = null;
    +
    +    @OnScheduled
    +    public void onScheduled(ProcessContext context) {
    +        this.decodeCharset = Charset.forName(context.getProperty(DECODE_CHARSET).getValue());
    +        this.encodeCharset = Charset.forName(context.getProperty(ENCODE_CHARSET).getValue());
    +
    +        final String jsonFormat = context.getProperty(JSON_FORMAT).getValue();
    +        if (jsonFormat.equals(JSON_FORMAT_FULL_ROW.getValue())) {
    +            this.serializer = new JsonFullRowSerializer(decodeCharset, encodeCharset);
    +        } else {
    +            this.serializer = new JsonQualifierAndValueRowSerializer(decodeCharset, encodeCharset);
    +        }
    +    }
    +
    +    @Override
    +    protected List<PropertyDescriptor> getSupportedPropertyDescriptors() {
    +        return properties;
    +    }
    +
    +    @Override
    +    public Set<Relationship> getRelationships() {
    +        return relationships;
    +    }
    +
    +    @Override
    +    protected Collection<ValidationResult> customValidate(ValidationContext validationContext) {
    +
    +        final List<ValidationResult> problems = new ArrayList<>();
    +
    +        final String columns = validationContext.getProperty(COLUMNS).getValue();
    +        final String filter = validationContext.getProperty(FILTER_EXPRESSION).getValue();
    +
    +        if (!StringUtils.isBlank(columns) && !StringUtils.isBlank(filter)) {
    +            problems.add(new ValidationResult.Builder()
    +                    .subject(FILTER_EXPRESSION.getDisplayName())
    +                    .input(filter).valid(false)
    +                    .explanation("A filter expression can not be used in conjunction with the Columns property")
    +                    .build());
    +        }
    +
    --- End diff --
    
    Should we validate that the min/max time range are both provided or both blank? Based on their description.


---

[GitHub] nifi issue #2478: NIFI-4833 Add scanHBase Processor

Posted by bbende <gi...@git.apache.org>.
Github user bbende commented on the issue:

    https://github.com/apache/nifi/pull/2478
  
    One other question, what do you envision people most likely do with the output of this processor?
    
    The reason I'm asking is because I'm debating if it makes sense to write multiple JSON documents to a single flow file without wrapping them in an array. GetHBase and FetchHBase didn't have this problem because they wrote a row per flow file (which probably wasn't a good idea for GetHBase).
    
    As an example scenario, say we have a bunch of rows coming out of this processor using the col-qual-val format like:
    ```
    {"id":"", "message":"The time is Mon Mar 05 10:20:07 EST 2018"}
    {"id":"", "message":"The time is Mon Mar 05 10:21:03 EST 2018"}
    {"id":"", "message":"The time is Mon Mar 05 10:22:44 EST 2018"}
    {"id":"", "message":"The time is Mon Mar 05 10:22:44 EST 2018"}
    {"id":"", "message":"The time is Mon Mar 05 10:22:44 EST 2018"}
    {"id":"", "message":"The time is Mon Mar 05 10:22:44 EST 2018"}
    {"id":"", "message":"The time is Mon Mar 05 10:22:44 EST 2018"}
    {"id":"", "message":"The time is Mon Mar 05 10:22:44 EST 2018"}
    {"id":"", "message":"The time is Mon Mar 05 10:22:44 EST 2018"}
    ```
    
    If we then created a schema for this:
    ```
    {
      "name": "scan",
      "namespace": "nifi",
      "type": "record",
      "fields": [
        { "name": "id", "type": "string" },
        { "name": "message", "type": "string" }
      ]
    }
    ```
    Then tried to use ConvertRecord with a JsonTreeReader and CsvRecordSetWriter, to convert from JSON to CSV, we get:
    ```
    id,message
    "",The time is Mon Mar 05 10:20:07 EST 2018
    ```
    It only ends up converting the first JSON document because the JsonTreeReader doesn't know how to read multiple records unless its a JSON array.
    
    There may be cases where the current output makes sense so I'm not saying to change it yet, but just trying to think of what the most common scenario will be.


---

[GitHub] nifi pull request #2478: NIFI-4833 Add scanHBase Processor

Posted by bdesert <gi...@git.apache.org>.
Github user bdesert commented on a diff in the pull request:

    https://github.com/apache/nifi/pull/2478#discussion_r169749383
  
    --- Diff: nifi-nar-bundles/nifi-hbase-bundle/nifi-hbase-processors/src/main/java/org/apache/nifi/hbase/ScanHBase.java ---
    @@ -0,0 +1,562 @@
    +/*
    + * Licensed to the Apache Software Foundation (ASF) under one or more
    + * contributor license agreements.  See the NOTICE file distributed with
    + * this work for additional information regarding copyright ownership.
    + * The ASF licenses this file to You under the Apache License, Version 2.0
    + * (the "License"); you may not use this file except in compliance with
    + * the License.  You may obtain a copy of the License at
    + *
    + *     http://www.apache.org/licenses/LICENSE-2.0
    + *
    + * Unless required by applicable law or agreed to in writing, software
    + * distributed under the License is distributed on an "AS IS" BASIS,
    + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    + * See the License for the specific language governing permissions and
    + * limitations under the License.
    + */
    +package org.apache.nifi.hbase;
    +
    +import org.apache.commons.lang3.StringUtils;
    +import org.apache.nifi.annotation.behavior.InputRequirement;
    +import org.apache.nifi.annotation.behavior.WritesAttribute;
    +import org.apache.nifi.annotation.behavior.WritesAttributes;
    +import org.apache.nifi.annotation.documentation.CapabilityDescription;
    +import org.apache.nifi.annotation.documentation.Tags;
    +import org.apache.nifi.annotation.lifecycle.OnScheduled;
    +import org.apache.nifi.components.AllowableValue;
    +import org.apache.nifi.components.PropertyDescriptor;
    +import org.apache.nifi.components.ValidationContext;
    +import org.apache.nifi.components.ValidationResult;
    +import org.apache.nifi.flowfile.FlowFile;
    +import org.apache.nifi.flowfile.attributes.CoreAttributes;
    +import org.apache.nifi.hbase.io.JsonFullRowSerializer;
    +import org.apache.nifi.hbase.io.JsonQualifierAndValueRowSerializer;
    +import org.apache.nifi.hbase.io.RowSerializer;
    +import org.apache.nifi.hbase.scan.Column;
    +import org.apache.nifi.hbase.scan.ResultCell;
    +import org.apache.nifi.hbase.scan.ResultHandler;
    +import org.apache.nifi.processor.AbstractProcessor;
    +import org.apache.nifi.processor.ProcessContext;
    +import org.apache.nifi.processor.ProcessSession;
    +import org.apache.nifi.processor.Relationship;
    +import org.apache.nifi.processor.exception.ProcessException;
    +import org.apache.nifi.processor.util.StandardValidators;
    +import org.apache.nifi.util.Tuple;
    +
    +import java.io.IOException;
    +import java.nio.charset.Charset;
    +import java.nio.charset.StandardCharsets;
    +import java.util.ArrayList;
    +import java.util.Collection;
    +import java.util.Collections;
    +import java.util.HashMap;
    +import java.util.HashSet;
    +import java.util.Iterator;
    +import java.util.LinkedList;
    +import java.util.List;
    +import java.util.Map;
    +import java.util.Set;
    +import java.util.concurrent.atomic.AtomicReference;
    +import java.util.regex.Pattern;
    +
    +@InputRequirement(InputRequirement.Requirement.INPUT_REQUIRED)
    +@Tags({"hbase", "scan", "fetch", "get"})
    +@CapabilityDescription("Scans and fetches rows from an HBase table. This processor may be used to fetch rows from hbase table by specifying a range of rowkey values (start and/or end ),"
    +        + "by time range, by filter expression, or any combination of them. \n"
    +        + "Order of records can be controlled by a property <code>Reversed</code>"
    +        + "Number of rows retrieved by the processor can be limited.")
    +@WritesAttributes({
    +        @WritesAttribute(attribute = "hbase.table", description = "The name of the HBase table that the row was fetched from"),
    +        @WritesAttribute(attribute = "hbase.resultset", description = "A JSON document/s representing the row/s. This property is only written when a Destination of flowfile-attributes is selected."),
    +        @WritesAttribute(attribute = "mime.type", description = "Set to application/json when using a Destination of flowfile-content, not set or modified otherwise"),
    +        @WritesAttribute(attribute = "hbase.rows.count", description = "Number of rows in the content of given flow file"),
    +        @WritesAttribute(attribute = "scanhbase.results.found", description = "Indicates whether at least one row has been found in given hbase table with provided conditions. <br/>"
    +                + "Could be null (not present) if transfered to FAILURE")
    +})
    +public class ScanHBase extends AbstractProcessor {
    +    //enhanced regex for columns to allow "-" in column qualifier names
    +    static final Pattern COLUMNS_PATTERN = Pattern.compile("\\w+(:(\\w|-)+)?(?:,\\w+(:(\\w|-)+)?)*");
    +    static final byte[] nl = System.lineSeparator().getBytes();
    +
    +    static final PropertyDescriptor HBASE_CLIENT_SERVICE = new PropertyDescriptor.Builder()
    +            .displayName("HBase Client Service")
    +            .name("scanhbase-client-service")
    +            .description("Specifies the Controller Service to use for accessing HBase.")
    +            .required(true)
    +            .identifiesControllerService(HBaseClientService.class)
    +            .build();
    +
    +    static final PropertyDescriptor TABLE_NAME = new PropertyDescriptor.Builder()
    +            .displayName("Table Name")
    +            .name("scanhbase-table-name")
    +            .description("The name of the HBase Table to fetch from.")
    +            .required(true)
    +            .expressionLanguageSupported(true)
    +            .addValidator(StandardValidators.NON_EMPTY_VALIDATOR)
    +            .build();
    +
    +    static final PropertyDescriptor START_ROW = new PropertyDescriptor.Builder()
    +            .displayName("Start rowkey")
    +            .name("scanhbase-start-rowkey")
    +            .description("The rowkey to start scan from.")
    +            .required(false)
    +            .expressionLanguageSupported(true)
    +            .addValidator(StandardValidators.NON_EMPTY_VALIDATOR)
    +            .build();
    +
    +    static final PropertyDescriptor END_ROW = new PropertyDescriptor.Builder()
    +            .displayName("End rowkey")
    +            .name("scanhbase-end-rowkey")
    +            .description("The row key to end scan by.")
    +            .required(false)
    +            .expressionLanguageSupported(true)
    +            .addValidator(StandardValidators.NON_EMPTY_VALIDATOR)
    +            .build();
    +
    +    static final PropertyDescriptor TIME_RANGE_MIN = new PropertyDescriptor.Builder()
    +            .displayName("Time range min")
    +            .name("scanhbase-time-range-min")
    +            .description("Time range min value. Both min and max values for time range should be either blank or provided.")
    +            .required(false)
    +            .expressionLanguageSupported(true)
    +            .addValidator(StandardValidators.LONG_VALIDATOR)
    +            .build();
    +
    +    static final PropertyDescriptor TIME_RANGE_MAX = new PropertyDescriptor.Builder()
    +            .displayName("Time range max")
    +            .name("scanhbase-time-range-max")
    +            .description("Time range max value. Both min and max values for time range should be either blank or provided.")
    +            .required(false)
    +            .expressionLanguageSupported(true)
    +            .addValidator(StandardValidators.LONG_VALIDATOR)
    +            .build();
    +
    +    static final PropertyDescriptor LIMIT_ROWS = new PropertyDescriptor.Builder()
    +            .displayName("Limit rows")
    +            .name("scanhbase-limit")
    +            .description("Limit number of rows retrieved by scan.")
    +            .required(false)
    +            .expressionLanguageSupported(true)
    +            .addValidator(StandardValidators.INTEGER_VALIDATOR)
    +            .build();
    +
    +    static final PropertyDescriptor BULK_SIZE = new PropertyDescriptor.Builder()
    +            .displayName("Max rows per flow file")
    +            .name("scanhbase-bulk-size")
    +            .description("Limits number of rows in single flow file content. Set to 0 to avoid multiple flow files.")
    +            .required(false)
    +            .expressionLanguageSupported(true)
    +            .defaultValue("0")
    +            .addValidator(StandardValidators.INTEGER_VALIDATOR)
    +            .build();
    +
    +    static final PropertyDescriptor REVERSED_SCAN = new PropertyDescriptor.Builder()
    +            .displayName("Reversed order")
    +            .name("scanhbase-reversed-order")
    +            .description("Set whether this scan is a reversed one. This is false by default which means forward(normal) scan.")
    +            .expressionLanguageSupported(false)
    +            .allowableValues("true", "false")
    +            .required(false)
    +            .defaultValue("false")
    +            .addValidator(StandardValidators.BOOLEAN_VALIDATOR)
    +            .build();
    +
    +    static final PropertyDescriptor FILTER_EXPRESSION = new PropertyDescriptor.Builder()
    +            .displayName("Filter expression")
    +            .name("scanhbase-filter-expression")
    +            .description("An HBase filter expression that will be applied to the scan. This property can not be used when also using the Columns property.<br/>"
    +                    + "Example: \"ValueFilter( =, 'binaryprefix:commit' )\"")
    +            .required(false)
    +            .expressionLanguageSupported(true)
    +            .addValidator(StandardValidators.NON_EMPTY_VALIDATOR)
    +            .build();
    +
    +    static final PropertyDescriptor COLUMNS = new PropertyDescriptor.Builder()
    +            .displayName("Columns")
    +            .name("scanhbase-columns")
    +            .description("An optional comma-separated list of \"<colFamily>:<colQualifier>\" pairs to fetch. To return all columns " +
    +                    "for a given family, leave off the qualifier such as \"<colFamily1>,<colFamily2>\".")
    +            .required(false)
    +            .expressionLanguageSupported(true)
    +            .addValidator(StandardValidators.createRegexMatchingValidator(COLUMNS_PATTERN))
    +            .build();
    +
    +    static final AllowableValue JSON_FORMAT_FULL_ROW = new AllowableValue("full-row", "full-row",
    +            "Creates a JSON document with the format: {\"row\":<row-id>, \"cells\":[{\"fam\":<col-fam>, \"qual\":<col-val>, \"val\":<value>, \"ts\":<timestamp>}]}.");
    +    static final AllowableValue JSON_FORMAT_QUALIFIER_AND_VALUE = new AllowableValue("col-qual-and-val", "col-qual-and-val",
    +            "Creates a JSON document with the format: {\"<col-qual>\":\"<value>\", \"<col-qual>\":\"<value>\".");
    +
    +    static final PropertyDescriptor JSON_FORMAT = new PropertyDescriptor.Builder()
    +            .displayName("JSON Format")
    +            .name("scanhbase-json-format")
    +            .description("Specifies how to represent the HBase row as a JSON document.")
    +            .required(true)
    +            .allowableValues(JSON_FORMAT_FULL_ROW, JSON_FORMAT_QUALIFIER_AND_VALUE)
    +            .defaultValue(JSON_FORMAT_FULL_ROW.getValue())
    +            .build();
    +
    +    static final PropertyDescriptor DECODE_CHARSET = new PropertyDescriptor.Builder()
    +            .displayName("Decode Character Set")
    +            .name("scanhbase-decode-charset")
    +            .description("The character set used to decode data from HBase.")
    +            .required(true)
    +            .defaultValue("UTF-8")
    +            .addValidator(StandardValidators.CHARACTER_SET_VALIDATOR)
    +            .build();
    +
    +    static final PropertyDescriptor ENCODE_CHARSET = new PropertyDescriptor.Builder()
    +            .displayName("Encode Character Set")
    +            .name("scanhbase-encode-charset")
    +            .description("The character set used to encode the JSON representation of the row.")
    +            .required(true)
    +            .defaultValue("UTF-8")
    +            .addValidator(StandardValidators.CHARACTER_SET_VALIDATOR)
    +            .build();
    +
    +    public static final Relationship REL_ORIGINAL = new Relationship.Builder()
    +            .name("original")
    +            .description("The original input file will be routed to this destination, even if no rows are retrieved based on provided conditions.")
    +            .build();
    +
    +    static final Relationship REL_SUCCESS = new Relationship.Builder()
    +            .name("success")
    +            .description("All successful fetches are routed to this relationship.")
    +            .build();
    +    static final Relationship REL_FAILURE = new Relationship.Builder()
    +            .name("failure")
    +            .description("All failed fetches are routed to this relationship.")
    +            .build();
    +
    +    static final String HBASE_TABLE_ATTR = "hbase.table";
    +    static final String HBASE_ROWS_COUNT_ATTR = "hbase.rows.count";
    +
    +    static final List<PropertyDescriptor> properties;
    +    static {
    +        List<PropertyDescriptor> props = new ArrayList<>();
    +        props.add(HBASE_CLIENT_SERVICE);
    +        props.add(TABLE_NAME);
    +        props.add(START_ROW);
    +        props.add(END_ROW);
    +        props.add(TIME_RANGE_MIN);
    +        props.add(TIME_RANGE_MAX);
    +        props.add(LIMIT_ROWS);
    +        props.add(REVERSED_SCAN);
    +        props.add(BULK_SIZE);
    +        props.add(FILTER_EXPRESSION);
    +        props.add(COLUMNS);
    +        props.add(JSON_FORMAT);
    +        props.add(ENCODE_CHARSET);
    +        props.add(DECODE_CHARSET);
    +        properties = Collections.unmodifiableList(props);
    +    }
    +
    +    static final Set<Relationship> relationships;
    +    static {
    +        Set<Relationship> rels = new HashSet<>();
    +        rels.add(REL_SUCCESS);
    +        rels.add(REL_ORIGINAL);
    +        rels.add(REL_FAILURE);
    +        relationships = Collections.unmodifiableSet(rels);
    +    }
    +
    +    private volatile Charset decodeCharset;
    +    private volatile Charset encodeCharset;
    +    private RowSerializer serializer = null;
    +
    +    @OnScheduled
    +    public void onScheduled(ProcessContext context) {
    +        this.decodeCharset = Charset.forName(context.getProperty(DECODE_CHARSET).getValue());
    +        this.encodeCharset = Charset.forName(context.getProperty(ENCODE_CHARSET).getValue());
    +
    +        final String jsonFormat = context.getProperty(JSON_FORMAT).getValue();
    +        if (jsonFormat.equals(JSON_FORMAT_FULL_ROW.getValue())) {
    +            this.serializer = new JsonFullRowSerializer(decodeCharset, encodeCharset);
    +        } else {
    +            this.serializer = new JsonQualifierAndValueRowSerializer(decodeCharset, encodeCharset);
    +        }
    +    }
    +
    +    @Override
    +    protected List<PropertyDescriptor> getSupportedPropertyDescriptors() {
    +        return properties;
    +    }
    +
    +    @Override
    +    public Set<Relationship> getRelationships() {
    +        return relationships;
    +    }
    +
    +    @Override
    +    protected Collection<ValidationResult> customValidate(ValidationContext validationContext) {
    +
    +        final List<ValidationResult> problems = new ArrayList<>();
    +
    +        final String columns = validationContext.getProperty(COLUMNS).getValue();
    +        final String filter = validationContext.getProperty(FILTER_EXPRESSION).getValue();
    +
    +        if (!StringUtils.isBlank(columns) && !StringUtils.isBlank(filter)) {
    +            problems.add(new ValidationResult.Builder()
    +                    .subject(FILTER_EXPRESSION.getDisplayName())
    +                    .input(filter).valid(false)
    +                    .explanation("A filter expression can not be used in conjunction with the Columns property")
    +                    .build());
    +        }
    +
    +        return problems;
    +    }
    +
    +    @Override
    +    public void onTrigger(ProcessContext context, ProcessSession session) throws ProcessException {
    +        FlowFile flowFile = session.get();
    +        if (flowFile == null) {
    +            return;
    +        }
    +
    +        try{
    +            final String tableName = context.getProperty(TABLE_NAME).evaluateAttributeExpressions(flowFile).getValue();
    +            if (StringUtils.isBlank(tableName)) {
    +                getLogger().error("Table Name is blank or null for {}, transferring to failure", new Object[] {flowFile});
    +                session.transfer(session.penalize(flowFile), REL_FAILURE);
    +                return;
    +            }
    +
    +            final String startRow = context.getProperty(START_ROW).evaluateAttributeExpressions(flowFile).getValue();
    +            final String endRow = context.getProperty(END_ROW).evaluateAttributeExpressions(flowFile).getValue();
    +
    +            final String filterExpression = context.getProperty(FILTER_EXPRESSION).evaluateAttributeExpressions(flowFile).getValue();
    +
    +            //evaluate and validate time range min and max values. They both should be either empty or provided.
    +            Long timerangeMin = null;
    +            Long timerangeMax = null;
    +
    +            try{
    +                timerangeMin = context.getProperty(TIME_RANGE_MIN).evaluateAttributeExpressions(flowFile).asLong();
    +            }catch(Exception e){
    +                getLogger().error("Time range min value is not a number ({}) for {}, transferring to failure",
    +                        new Object[] {context.getProperty(TIME_RANGE_MIN).evaluateAttributeExpressions(flowFile).getValue(), flowFile});
    +                session.transfer(session.penalize(flowFile), REL_FAILURE);
    +                return;
    +            }
    +            try{
    +                timerangeMax = context.getProperty(TIME_RANGE_MAX).evaluateAttributeExpressions(flowFile).asLong();
    +            }catch(Exception e){
    +                getLogger().error("Time range max value is not a number ({}) for {}, transferring to failure",
    +                        new Object[] {context.getProperty(TIME_RANGE_MAX).evaluateAttributeExpressions(flowFile).getValue(), flowFile});
    +                session.transfer(session.penalize(flowFile), REL_FAILURE);
    +                return;
    +            }
    +            if (timerangeMin == null && timerangeMax != null) {
    +                getLogger().error("Time range min value cannot be blank when max value provided for {}, transferring to failure", new Object[] {flowFile});
    +                session.transfer(session.penalize(flowFile), REL_FAILURE);
    +                return;
    +            }else if (timerangeMin != null && timerangeMax == null) {
    +                getLogger().error("Time range max value cannot be blank when min value provided for {}, transferring to failure", new Object[] {flowFile});
    +                session.transfer(session.penalize(flowFile), REL_FAILURE);
    +                return;
    +            }
    +
    +            final Integer limitRows = context.getProperty(LIMIT_ROWS).evaluateAttributeExpressions(flowFile).asInteger();
    +
    +            final Boolean isReversed = context.getProperty(REVERSED_SCAN).asBoolean();
    +
    +            final Integer bulkSize = context.getProperty(BULK_SIZE).evaluateAttributeExpressions(flowFile).asInteger();
    +
    +            final List<Column> columns = getColumns(context.getProperty(COLUMNS).evaluateAttributeExpressions(flowFile).getValue());
    +            final HBaseClientService hBaseClientService = context.getProperty(HBASE_CLIENT_SERVICE).asControllerService(HBaseClientService.class);
    +
    +            final AtomicReference<Long> rowsPulledHolder = new AtomicReference<>(0L);
    +            final AtomicReference<Long> ffCountHolder = new AtomicReference<>(0L);
    +            ScanHBaseResultHandler handler = new ScanHBaseResultHandler(context, session, flowFile, rowsPulledHolder, ffCountHolder, hBaseClientService, tableName, bulkSize);
    +
    +            try {
    +                hBaseClientService.scan(tableName,
    +                                        startRow, endRow,
    +                                        filterExpression,
    +                                        timerangeMin, timerangeMax,
    +                                        limitRows,
    +                                        isReversed,
    +                                        columns,
    +                                        handler);
    +            } catch (IOException e) {
    +                getLogger().error("Unable to fetch rows from HBase table {} due to {}", new Object[] {tableName, e});
    +                flowFile = session.putAttribute(flowFile, "scanhbase.results.found", Boolean.toString(handler.isHandledAny()));
    +                session.transfer(flowFile, REL_FAILURE);
    +                return;
    +            }
    +
    +            LinkedList<Tuple<byte[], ResultCell[]>> hangingRows = handler.getHangingRows();
    +            if (!handler.isHandledAny() ||                                                         // no rows found in hbase
    +                    (handler.isHandledAny() && (hangingRows == null || hangingRows.isEmpty()))     // all the rows are flushed to FF inside handlers
    +                ){
    +                flowFile = session.putAttribute(flowFile, "scanhbase.results.found", Boolean.toString(handler.isHandledAny()));
    +                session.transfer(flowFile, REL_ORIGINAL);
    +                session.commit();
    +                return;
    +            }
    +
    +            if (hangingRows != null && !hangingRows.isEmpty()) {
    +                FlowFile lastFF = session.create(flowFile);
    +                final Map<String, String> attributes = new HashMap<>();
    +                attributes.put(HBASE_TABLE_ATTR, tableName);
    +                attributes.put(HBASE_ROWS_COUNT_ATTR, Long.toString(rowsPulledHolder.get()));
    +                attributes.put(CoreAttributes.MIME_TYPE.key(), "application/json");
    +                attributes.put(HBASE_ROWS_COUNT_ATTR, Long.toString(hangingRows.size()));
    +                lastFF = session.putAllAttributes(lastFF, attributes);
    +
    +                final AtomicReference<IOException> ioe = new AtomicReference<>(null);
    +                lastFF = session.write(lastFF, (out) -> {
    +                    for (Iterator<Tuple<byte[], ResultCell[]>> iter = hangingRows.iterator(); iter.hasNext();){
    +                        Tuple<byte[], ResultCell[]> r = iter.next();
    +                        serializer.serialize(r.getKey(), r.getValue(), out);
    +                        if (iter.hasNext()){
    +                            out.write(nl);
    +                        }
    +                    }
    +                });
    +
    +                Relationship rel = REL_SUCCESS;
    +                IOException error = ioe.get();
    +                if (error != null){
    +                    lastFF = session.putAttribute(lastFF, "scanhbase.error", error.toString());
    +                    rel = REL_FAILURE;
    +                }
    +                session.transfer(lastFF, rel);
    +                flowFile = session.putAttribute(flowFile, "scanhbase.results.found", Boolean.toString(handler.isHandledAny()));
    +                session.transfer(flowFile, REL_ORIGINAL);
    +            }
    +            session.commit();
    +
    +        }catch (final Exception e) {
    +            getLogger().error("Failed to receive data from HBase due to {}", e);
    +            session.rollback();
    +            // if we failed, we want to yield so that we don't hammer hbase.
    +            context.yield();
    +        }
    +    }
    +
    +    /**
    +     * @param columnsValue a String in the form colFam:colQual,colFam:colQual
    +     * @return a list of Columns based on parsing the given String
    +     */
    +    private List<Column> getColumns(final String columnsValue) {
    +        final String[] columns = (columnsValue == null || columnsValue.isEmpty() ? new String[0] : columnsValue.split(","));
    +
    +        List<Column> columnsList = new ArrayList<>(columns.length);
    +
    +        for (final String column : columns) {
    +            if (column.contains(":"))  {
    +                final String[] parts = column.split(":");
    +                final byte[] cf = parts[0].getBytes(StandardCharsets.UTF_8);
    --- End diff --
    
    A charset for data presentation is configurable. It's defined in onScheduled while creating serializer.
    A charset for hbase rowkey and column family/qualifier names is utf-8 intentionally to be consistent with GetHBase and FetchHBase.
    I would prefer to open new JIRA to handle charset used for row key and column family/qualifiers throughout the nifi-hbase package.


---

[GitHub] nifi issue #2478: NIFI-4833 Add scanHBase Processor

Posted by MikeThomsen <gi...@git.apache.org>.
Github user MikeThomsen commented on the issue:

    https://github.com/apache/nifi/pull/2478
  
    I'll try to take a look this weekend.


---

[GitHub] nifi issue #2478: NIFI-4833 Add scanHBase Processor

Posted by bbende <gi...@git.apache.org>.
Github user bbende commented on the issue:

    https://github.com/apache/nifi/pull/2478
  
    @bdesert Thanks for the updates, was reviewing the code again and I think we need to change to way the `ScanHBaseResultHandler` works...
    
    Currently it adds rows to a list in memory until bulk size is reached, and since bulk size defaults to 0, the default case will be that bulk size is never reached and all the rows are left as "hanging" rows. This means if someone scans a table with 1 million rows, all 1 millions will be in memory before being written to the flow file which would not be good for memory usage.
    
    We should be able to write row by row to the flow file and never add them to a list. Inside the handler we can use `session.append(flowFile, (out) ->` to append a row at a time to the flow file. I think we can then do away with the "hanging rows" concept because there won't be anything buffered in memory.


---

[GitHub] nifi issue #2478: NIFI-4833 Add scanHBase Processor

Posted by bdesert <gi...@git.apache.org>.
Github user bdesert commented on the issue:

    https://github.com/apache/nifi/pull/2478
  
    @bbende ,
    Bryan, committed the changes. Tested on a cluster, works as expected.
    When have a time, please review.


---

[GitHub] nifi pull request #2478: NIFI-4833 Add scanHBase Processor

Posted by asfgit <gi...@git.apache.org>.
Github user asfgit closed the pull request at:

    https://github.com/apache/nifi/pull/2478


---

[GitHub] nifi issue #2478: NIFI-4833 Add scanHBase Processor

Posted by bdesert <gi...@git.apache.org>.
Github user bdesert commented on the issue:

    https://github.com/apache/nifi/pull/2478
  
    @MikeThomsen , are you available to re-review this PR? I have addressed you comment regarding branch and the rest (except for labels, which can be added later in bulk for all the HBase related processors)


---

[GitHub] nifi issue #2478: NIFI-4833 Add scanHBase Processor

Posted by MikeThomsen <gi...@git.apache.org>.
Github user MikeThomsen commented on the issue:

    https://github.com/apache/nifi/pull/2478
  
    @bbende @ijokarumawak +1 LGTM but it needs a second look. I tested it with HBase locally and it was able to work just fine with what I threw at it.


---

[GitHub] nifi pull request #2478: NIFI-4833 Add scanHBase Processor

Posted by MikeThomsen <gi...@git.apache.org>.
Github user MikeThomsen commented on a diff in the pull request:

    https://github.com/apache/nifi/pull/2478#discussion_r169622126
  
    --- Diff: nifi-nar-bundles/nifi-hbase-bundle/nifi-hbase-processors/src/test/java/org/apache/nifi/hbase/TestScanHBase.java ---
    @@ -0,0 +1,375 @@
    +/*
    + * Licensed to the Apache Software Foundation (ASF) under one or more
    + * contributor license agreements.  See the NOTICE file distributed with
    + * this work for additional information regarding copyright ownership.
    + * The ASF licenses this file to You under the Apache License, Version 2.0
    + * (the "License"); you may not use this file except in compliance with
    + * the License.  You may obtain a copy of the License at
    + *
    + *     http://www.apache.org/licenses/LICENSE-2.0
    + *
    + * Unless required by applicable law or agreed to in writing, software
    + * distributed under the License is distributed on an "AS IS" BASIS,
    + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    + * See the License for the specific language governing permissions and
    + * limitations under the License.
    + */
    +package org.apache.nifi.hbase;
    +
    +import java.util.HashMap;
    +import java.util.List;
    +import java.util.Map;
    +
    +import org.apache.nifi.reporting.InitializationException;
    +import org.apache.nifi.util.MockFlowFile;
    +import org.apache.nifi.util.TestRunner;
    +import org.apache.nifi.util.TestRunners;
    +import org.junit.Assert;
    +import org.junit.Before;
    +import org.junit.Test;
    +
    +public class TestScanHBase {
    +
    +    private ScanHBase proc;
    +    private MockHBaseClientService hBaseClientService;
    +    private TestRunner runner;
    +
    +    @Before
    +    public void setup() throws InitializationException {
    +        proc = new ScanHBase();
    +        runner = TestRunners.newTestRunner(proc);
    +
    +        hBaseClientService = new MockHBaseClientService();
    +        runner.addControllerService("hbaseClient", hBaseClientService);
    +        runner.enableControllerService(hBaseClientService);
    +        runner.setProperty(ScanHBase.HBASE_CLIENT_SERVICE, "hbaseClient");
    +    }
    +
    +    @Test
    +    public void testColumnsValidation() {
    +        runner.setProperty(ScanHBase.TABLE_NAME, "table1");
    +        runner.setProperty(ScanHBase.START_ROW, "row1");
    +        runner.setProperty(ScanHBase.END_ROW, "row1");
    +        runner.assertValid();
    +
    +        runner.setProperty(ScanHBase.COLUMNS, "cf1:cq1");
    +        runner.assertValid();
    +
    +        runner.setProperty(ScanHBase.COLUMNS, "cf1");
    +        runner.assertValid();
    +
    +        runner.setProperty(ScanHBase.COLUMNS, "cf1:cq1,cf2:cq2,cf3:cq3");
    +        runner.assertValid();
    +
    +        runner.setProperty(ScanHBase.COLUMNS, "cf1,cf2:cq1,cf3");
    +        runner.assertValid();
    +
    +        runner.setProperty(ScanHBase.COLUMNS, "cf1 cf2,cf3");
    +        runner.assertNotValid();
    +
    +        runner.setProperty(ScanHBase.COLUMNS, "cf1:,cf2,cf3");
    +        runner.assertNotValid();
    +
    +        runner.setProperty(ScanHBase.COLUMNS, "cf1:cq1,");
    +        runner.assertNotValid();
    +    }
    +
    +    @Test
    +    public void testNoIncomingFlowFile() {
    +        runner.setProperty(ScanHBase.TABLE_NAME, "table1");
    +        runner.setProperty(ScanHBase.START_ROW, "row1");
    +        runner.setProperty(ScanHBase.END_ROW, "row1");
    +
    +        runner.run();
    +        runner.assertTransferCount(ScanHBase.REL_FAILURE, 0);
    +        runner.assertTransferCount(ScanHBase.REL_SUCCESS, 0);
    +        runner.assertTransferCount(ScanHBase.REL_ORIGINAL, 0);
    +
    +        Assert.assertEquals(0, hBaseClientService.getNumScans());
    +    }
    +
    +    @Test
    +    public void testInvalidTableName() {
    +        runner.setProperty(ScanHBase.TABLE_NAME, "${hbase.table}");
    +        runner.setProperty(ScanHBase.START_ROW, "row1");
    +        runner.setProperty(ScanHBase.END_ROW, "row1");
    +
    +        runner.enqueue("trigger flow file");
    +        runner.run();
    +
    +        runner.assertTransferCount(ScanHBase.REL_FAILURE, 1);
    +        runner.assertTransferCount(ScanHBase.REL_SUCCESS, 0);
    +        runner.assertTransferCount(ScanHBase.REL_ORIGINAL, 0);
    +
    +        Assert.assertEquals(0, hBaseClientService.getNumScans());
    +    }
    +
    +    @Test
    +    public void testResultsNotFound() {
    +        runner.setProperty(ScanHBase.TABLE_NAME, "table1");
    +        runner.setProperty(ScanHBase.START_ROW, "row1");
    +        runner.setProperty(ScanHBase.END_ROW, "row1");
    +
    +        runner.enqueue("trigger flow file");
    +        runner.run();
    +
    +        runner.assertTransferCount(ScanHBase.REL_FAILURE, 0);
    +        runner.assertTransferCount(ScanHBase.REL_SUCCESS, 0);
    +        runner.assertTransferCount(ScanHBase.REL_ORIGINAL, 1);
    +
    +        MockFlowFile flowFile = runner.getFlowFilesForRelationship(ScanHBase.REL_ORIGINAL).get(0);
    +        flowFile.assertAttributeEquals("scanhbase.results.found", Boolean.FALSE.toString());
    +
    +        Assert.assertEquals(1, hBaseClientService.getNumScans());
    +    }
    +
    +    @Test
    +    public void testScanToContentWithStringValues() {
    +        final Map<String, String> cells = new HashMap<>();
    +        cells.put("cq1", "val1");
    +        cells.put("cq2", "val2");
    +
    +        final long ts1 = 123456789;
    +        hBaseClientService.addResult("row1", cells, ts1);
    +        hBaseClientService.addResult("row2", cells, ts1);
    +
    +        runner.setProperty(ScanHBase.TABLE_NAME, "table1");
    +        runner.setProperty(ScanHBase.START_ROW, "row1");
    +        runner.setProperty(ScanHBase.END_ROW, "row2");
    +        runner.setProperty(ScanHBase.TIME_RANGE_MIN, "0");
    +        runner.setProperty(ScanHBase.TIME_RANGE_MAX, "1111111110");
    +        runner.setProperty(ScanHBase.LIMIT_ROWS, "10");
    +        runner.setProperty(ScanHBase.REVERSED_SCAN, "false");
    +        runner.setProperty(ScanHBase.BULK_SIZE, "10");
    +
    +        runner.enqueue("trigger flow file");
    +        runner.run();
    +
    +        runner.assertTransferCount(ScanHBase.REL_FAILURE, 0);
    +        runner.assertTransferCount(ScanHBase.REL_SUCCESS, 1);
    +        runner.assertTransferCount(ScanHBase.REL_ORIGINAL, 1);
    +
    +        MockFlowFile flowFile = runner.getFlowFilesForRelationship(ScanHBase.REL_SUCCESS).get(0);
    +        flowFile.assertContentEquals("{\"row\":\"row1\", \"cells\": [" +
    --- End diff --
    
    You might want to turn this into a test against two `Map` objects using a JSON parser to evaluate that since things like formatting could hypothetically change between HBase versions.


---

[GitHub] nifi pull request #2478: NIFI-4833 Add scanHBase Processor

Posted by MikeThomsen <gi...@git.apache.org>.
Github user MikeThomsen commented on a diff in the pull request:

    https://github.com/apache/nifi/pull/2478#discussion_r169622591
  
    --- Diff: nifi-nar-bundles/nifi-standard-services/nifi-hbase_1_1_2-client-service-bundle/nifi-hbase_1_1_2-client-service/src/main/java/org/apache/nifi/hbase/HBase_1_1_2_ClientService.java ---
    @@ -430,6 +430,78 @@ public void scan(final String tableName, final byte[] startRow, final byte[] end
             }
         }
     
    +    @Override
    +    public void scan(final String tableName, final String startRow, final String endRow, String filterExpression,
    +            final Long timerangeMin, final Long timerangeMax, final Integer limitRows, final Boolean isReversed,
    +            final Collection<Column> columns, final ResultHandler handler) throws IOException {
    +
    +        try (final Table table = connection.getTable(TableName.valueOf(tableName));
    +                final ResultScanner scanner = getResults(table, startRow, endRow, filterExpression, timerangeMin,
    +                        timerangeMax, limitRows, isReversed, columns)) {
    +
    +            int cnt = 0;
    +            final int lim = limitRows != null ? limitRows : 0;
    +            for (final Result result : scanner) {
    +
    +                if (lim > 0 && cnt++ > lim) break;
    +
    +                final byte[] rowKey = result.getRow();
    +                final Cell[] cells = result.rawCells();
    +
    +                if (cells == null) {
    +                    continue;
    +                }
    +
    +                // convert HBase cells to NiFi cells
    +                final ResultCell[] resultCells = new ResultCell[cells.length];
    +                for (int i = 0; i < cells.length; i++) {
    +                    final Cell cell = cells[i];
    +                    final ResultCell resultCell = getResultCell(cell);
    +                    resultCells[i] = resultCell;
    +                }
    +
    +                // delegate to the handler
    +                handler.handle(rowKey, resultCells);
    +            }
    +        }
    +
    +    }
    +
    +    //
    +    protected ResultScanner getResults(final Table table, final String startRow, final String endRow, final String filterExpression, final Long timerangeMin, final Long timerangeMax,
    +            final Integer limitRows, final Boolean isReversed, final Collection<Column> columns)  throws IOException {
    +        final Scan scan = new Scan();
    +        if (!StringUtils.isBlank(startRow)) scan.setStartRow(startRow.getBytes(StandardCharsets.UTF_8));
    +        if (!StringUtils.isBlank(endRow))   scan.setStopRow(   endRow.getBytes(StandardCharsets.UTF_8));
    --- End diff --
    
    See above.


---

[GitHub] nifi pull request #2478: NIFI-4833 Add scanHBase Processor

Posted by bbende <gi...@git.apache.org>.
Github user bbende commented on a diff in the pull request:

    https://github.com/apache/nifi/pull/2478#discussion_r170688235
  
    --- Diff: nifi-nar-bundles/nifi-hbase-bundle/nifi-hbase-processors/src/main/java/org/apache/nifi/hbase/ScanHBase.java ---
    @@ -0,0 +1,564 @@
    +/*
    + * Licensed to the Apache Software Foundation (ASF) under one or more
    + * contributor license agreements.  See the NOTICE file distributed with
    + * this work for additional information regarding copyright ownership.
    + * The ASF licenses this file to You under the Apache License, Version 2.0
    + * (the "License"); you may not use this file except in compliance with
    + * the License.  You may obtain a copy of the License at
    + *
    + *     http://www.apache.org/licenses/LICENSE-2.0
    + *
    + * Unless required by applicable law or agreed to in writing, software
    + * distributed under the License is distributed on an "AS IS" BASIS,
    + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    + * See the License for the specific language governing permissions and
    + * limitations under the License.
    + */
    +package org.apache.nifi.hbase;
    +
    +import org.apache.commons.lang3.StringUtils;
    +import org.apache.nifi.annotation.behavior.InputRequirement;
    +import org.apache.nifi.annotation.behavior.WritesAttribute;
    +import org.apache.nifi.annotation.behavior.WritesAttributes;
    +import org.apache.nifi.annotation.documentation.CapabilityDescription;
    +import org.apache.nifi.annotation.documentation.Tags;
    +import org.apache.nifi.annotation.lifecycle.OnScheduled;
    +import org.apache.nifi.components.AllowableValue;
    +import org.apache.nifi.components.PropertyDescriptor;
    +import org.apache.nifi.components.ValidationContext;
    +import org.apache.nifi.components.ValidationResult;
    +import org.apache.nifi.flowfile.FlowFile;
    +import org.apache.nifi.flowfile.attributes.CoreAttributes;
    +import org.apache.nifi.hbase.io.JsonFullRowSerializer;
    +import org.apache.nifi.hbase.io.JsonQualifierAndValueRowSerializer;
    +import org.apache.nifi.hbase.io.RowSerializer;
    +import org.apache.nifi.hbase.scan.Column;
    +import org.apache.nifi.hbase.scan.ResultCell;
    +import org.apache.nifi.hbase.scan.ResultHandler;
    +import org.apache.nifi.processor.AbstractProcessor;
    +import org.apache.nifi.processor.ProcessContext;
    +import org.apache.nifi.processor.ProcessSession;
    +import org.apache.nifi.processor.Relationship;
    +import org.apache.nifi.processor.exception.ProcessException;
    +import org.apache.nifi.processor.util.StandardValidators;
    +import org.apache.nifi.util.Tuple;
    +
    +import java.io.IOException;
    +import java.nio.charset.Charset;
    +import java.nio.charset.StandardCharsets;
    +import java.util.ArrayList;
    +import java.util.Collection;
    +import java.util.Collections;
    +import java.util.HashMap;
    +import java.util.HashSet;
    +import java.util.Iterator;
    +import java.util.LinkedList;
    +import java.util.List;
    +import java.util.Map;
    +import java.util.Set;
    +import java.util.concurrent.atomic.AtomicReference;
    +import java.util.regex.Pattern;
    +
    +@InputRequirement(InputRequirement.Requirement.INPUT_REQUIRED)
    +@Tags({"hbase", "scan", "fetch", "get"})
    +@CapabilityDescription("Scans and fetches rows from an HBase table. This processor may be used to fetch rows from hbase table by specifying a range of rowkey values (start and/or end ),"
    +        + "by time range, by filter expression, or any combination of them. "
    +        + "Order of records can be controlled by a property Reversed"
    +        + "Number of rows retrieved by the processor can be limited.")
    +@WritesAttributes({
    +        @WritesAttribute(attribute = "hbase.table", description = "The name of the HBase table that the row was fetched from"),
    +        @WritesAttribute(attribute = "hbase.resultset", description = "A JSON document/s representing the row/s. This property is only written when a Destination of flowfile-attributes is selected."),
    +        @WritesAttribute(attribute = "mime.type", description = "Set to application/json when using a Destination of flowfile-content, not set or modified otherwise"),
    +        @WritesAttribute(attribute = "hbase.rows.count", description = "Number of rows in the content of given flow file"),
    +        @WritesAttribute(attribute = "scanhbase.results.found", description = "Indicates whether at least one row has been found in given hbase table with provided conditions. "
    +                + "Could be null (not present) if transfered to FAILURE")
    +})
    +public class ScanHBase extends AbstractProcessor {
    +    //enhanced regex for columns to allow "-" in column qualifier names
    +    static final Pattern COLUMNS_PATTERN = Pattern.compile("\\w+(:(\\w|-)+)?(?:,\\w+(:(\\w|-)+)?)*");
    +    static final byte[] nl = System.lineSeparator().getBytes();
    +
    +    static final PropertyDescriptor HBASE_CLIENT_SERVICE = new PropertyDescriptor.Builder()
    +            .displayName("HBase Client Service")
    +            .name("scanhbase-client-service")
    +            .description("Specifies the Controller Service to use for accessing HBase.")
    +            .required(true)
    +            .identifiesControllerService(HBaseClientService.class)
    +            .build();
    +
    +    static final PropertyDescriptor TABLE_NAME = new PropertyDescriptor.Builder()
    +            .displayName("Table Name")
    +            .name("scanhbase-table-name")
    +            .description("The name of the HBase Table to fetch from.")
    +            .required(true)
    +            .expressionLanguageSupported(true)
    +            .addValidator(StandardValidators.NON_EMPTY_VALIDATOR)
    +            .build();
    +
    +    static final PropertyDescriptor START_ROW = new PropertyDescriptor.Builder()
    +            .displayName("Start rowkey")
    +            .name("scanhbase-start-rowkey")
    +            .description("The rowkey to start scan from.")
    +            .required(false)
    +            .expressionLanguageSupported(true)
    +            .addValidator(StandardValidators.NON_EMPTY_VALIDATOR)
    +            .build();
    +
    +    static final PropertyDescriptor END_ROW = new PropertyDescriptor.Builder()
    +            .displayName("End rowkey")
    +            .name("scanhbase-end-rowkey")
    +            .description("The row key to end scan by.")
    +            .required(false)
    +            .expressionLanguageSupported(true)
    +            .addValidator(StandardValidators.NON_EMPTY_VALIDATOR)
    +            .build();
    +
    +    static final PropertyDescriptor TIME_RANGE_MIN = new PropertyDescriptor.Builder()
    +            .displayName("Time range min")
    +            .name("scanhbase-time-range-min")
    +            .description("Time range min value. Both min and max values for time range should be either blank or provided.")
    +            .required(false)
    +            .expressionLanguageSupported(true)
    +            .addValidator(StandardValidators.LONG_VALIDATOR)
    +            .build();
    +
    +    static final PropertyDescriptor TIME_RANGE_MAX = new PropertyDescriptor.Builder()
    +            .displayName("Time range max")
    +            .name("scanhbase-time-range-max")
    +            .description("Time range max value. Both min and max values for time range should be either blank or provided.")
    +            .required(false)
    +            .expressionLanguageSupported(true)
    +            .addValidator(StandardValidators.LONG_VALIDATOR)
    +            .build();
    +
    +    static final PropertyDescriptor LIMIT_ROWS = new PropertyDescriptor.Builder()
    +            .displayName("Limit rows")
    +            .name("scanhbase-limit")
    +            .description("Limit number of rows retrieved by scan.")
    +            .required(false)
    +            .expressionLanguageSupported(true)
    +            .addValidator(StandardValidators.INTEGER_VALIDATOR)
    +            .build();
    +
    +    static final PropertyDescriptor BULK_SIZE = new PropertyDescriptor.Builder()
    +            .displayName("Max rows per flow file")
    +            .name("scanhbase-bulk-size")
    +            .description("Limits number of rows in single flow file content. Set to 0 to avoid multiple flow files.")
    +            .required(false)
    +            .expressionLanguageSupported(true)
    +            .defaultValue("0")
    +            .addValidator(StandardValidators.INTEGER_VALIDATOR)
    +            .build();
    +
    +    static final PropertyDescriptor REVERSED_SCAN = new PropertyDescriptor.Builder()
    +            .displayName("Reversed order")
    +            .name("scanhbase-reversed-order")
    +            .description("Set whether this scan is a reversed one. This is false by default which means forward(normal) scan.")
    +            .expressionLanguageSupported(false)
    +            .allowableValues("true", "false")
    +            .required(false)
    +            .defaultValue("false")
    +            .addValidator(StandardValidators.BOOLEAN_VALIDATOR)
    +            .build();
    +
    +    static final PropertyDescriptor FILTER_EXPRESSION = new PropertyDescriptor.Builder()
    +            .displayName("Filter expression")
    +            .name("scanhbase-filter-expression")
    +            .description("An HBase filter expression that will be applied to the scan. This property can not be used when also using the Columns property. "
    +                    + "Example: \"ValueFilter( =, 'binaryprefix:commit' )\"")
    +            .required(false)
    +            .expressionLanguageSupported(true)
    +            .addValidator(StandardValidators.NON_EMPTY_VALIDATOR)
    +            .build();
    +
    +    static final PropertyDescriptor COLUMNS = new PropertyDescriptor.Builder()
    +            .displayName("Columns")
    +            .name("scanhbase-columns")
    +            .description("An optional comma-separated list of \"<colFamily>:<colQualifier>\" pairs to fetch. To return all columns " +
    +                    "for a given family, leave off the qualifier such as \"<colFamily1>,<colFamily2>\".")
    +            .required(false)
    +            .expressionLanguageSupported(true)
    +            .addValidator(StandardValidators.createRegexMatchingValidator(COLUMNS_PATTERN))
    +            .build();
    +
    +    static final AllowableValue JSON_FORMAT_FULL_ROW = new AllowableValue("full-row", "full-row",
    +            "Creates a JSON document with the format: {\"row\":<row-id>, \"cells\":[{\"fam\":<col-fam>, \"qual\":<col-val>, \"val\":<value>, \"ts\":<timestamp>}]}.");
    +    static final AllowableValue JSON_FORMAT_QUALIFIER_AND_VALUE = new AllowableValue("col-qual-and-val", "col-qual-and-val",
    +            "Creates a JSON document with the format: {\"<col-qual>\":\"<value>\", \"<col-qual>\":\"<value>\".");
    +
    +    static final PropertyDescriptor JSON_FORMAT = new PropertyDescriptor.Builder()
    +            .displayName("JSON Format")
    +            .name("scanhbase-json-format")
    +            .description("Specifies how to represent the HBase row as a JSON document.")
    +            .required(true)
    +            .allowableValues(JSON_FORMAT_FULL_ROW, JSON_FORMAT_QUALIFIER_AND_VALUE)
    +            .defaultValue(JSON_FORMAT_FULL_ROW.getValue())
    +            .build();
    +
    +    static final PropertyDescriptor DECODE_CHARSET = new PropertyDescriptor.Builder()
    +            .displayName("Decode Character Set")
    +            .name("scanhbase-decode-charset")
    +            .description("The character set used to decode data from HBase.")
    +            .required(true)
    +            .defaultValue("UTF-8")
    +            .addValidator(StandardValidators.CHARACTER_SET_VALIDATOR)
    +            .build();
    +
    +    static final PropertyDescriptor ENCODE_CHARSET = new PropertyDescriptor.Builder()
    +            .displayName("Encode Character Set")
    +            .name("scanhbase-encode-charset")
    +            .description("The character set used to encode the JSON representation of the row.")
    +            .required(true)
    +            .defaultValue("UTF-8")
    +            .addValidator(StandardValidators.CHARACTER_SET_VALIDATOR)
    +            .build();
    +
    +    public static final Relationship REL_ORIGINAL = new Relationship.Builder()
    +            .name("original")
    +            .description("The original input file will be routed to this destination, even if no rows are retrieved based on provided conditions.")
    +            .build();
    +
    +    static final Relationship REL_SUCCESS = new Relationship.Builder()
    +            .name("success")
    +            .description("All successful fetches are routed to this relationship.")
    +            .build();
    +    static final Relationship REL_FAILURE = new Relationship.Builder()
    +            .name("failure")
    +            .description("All failed fetches are routed to this relationship.")
    +            .build();
    +
    +    static final String HBASE_TABLE_ATTR = "hbase.table";
    +    static final String HBASE_ROWS_COUNT_ATTR = "hbase.rows.count";
    +
    +    static final List<PropertyDescriptor> properties;
    +    static {
    +        List<PropertyDescriptor> props = new ArrayList<>();
    +        props.add(HBASE_CLIENT_SERVICE);
    +        props.add(TABLE_NAME);
    +        props.add(START_ROW);
    +        props.add(END_ROW);
    +        props.add(TIME_RANGE_MIN);
    +        props.add(TIME_RANGE_MAX);
    +        props.add(LIMIT_ROWS);
    +        props.add(REVERSED_SCAN);
    +        props.add(BULK_SIZE);
    +        props.add(FILTER_EXPRESSION);
    +        props.add(COLUMNS);
    +        props.add(JSON_FORMAT);
    +        props.add(ENCODE_CHARSET);
    +        props.add(DECODE_CHARSET);
    +        properties = Collections.unmodifiableList(props);
    +    }
    +
    +    static final Set<Relationship> relationships;
    +    static {
    +        Set<Relationship> rels = new HashSet<>();
    +        rels.add(REL_SUCCESS);
    +        rels.add(REL_ORIGINAL);
    +        rels.add(REL_FAILURE);
    +        relationships = Collections.unmodifiableSet(rels);
    +    }
    +
    +    private volatile Charset decodeCharset;
    +    private volatile Charset encodeCharset;
    +    private RowSerializer serializer = null;
    +
    +    @OnScheduled
    +    public void onScheduled(ProcessContext context) {
    +        this.decodeCharset = Charset.forName(context.getProperty(DECODE_CHARSET).getValue());
    +        this.encodeCharset = Charset.forName(context.getProperty(ENCODE_CHARSET).getValue());
    +
    +        final String jsonFormat = context.getProperty(JSON_FORMAT).getValue();
    +        if (jsonFormat.equals(JSON_FORMAT_FULL_ROW.getValue())) {
    +            this.serializer = new JsonFullRowSerializer(decodeCharset, encodeCharset);
    +        } else {
    +            this.serializer = new JsonQualifierAndValueRowSerializer(decodeCharset, encodeCharset);
    +        }
    +    }
    +
    +    @Override
    +    protected List<PropertyDescriptor> getSupportedPropertyDescriptors() {
    +        return properties;
    +    }
    +
    +    @Override
    +    public Set<Relationship> getRelationships() {
    +        return relationships;
    +    }
    +
    +    @Override
    +    protected Collection<ValidationResult> customValidate(ValidationContext validationContext) {
    +
    +        final List<ValidationResult> problems = new ArrayList<>();
    +
    +        final String columns = validationContext.getProperty(COLUMNS).getValue();
    +        final String filter = validationContext.getProperty(FILTER_EXPRESSION).getValue();
    +
    +        if (!StringUtils.isBlank(columns) && !StringUtils.isBlank(filter)) {
    +            problems.add(new ValidationResult.Builder()
    +                    .subject(FILTER_EXPRESSION.getDisplayName())
    +                    .input(filter).valid(false)
    +                    .explanation("A filter expression can not be used in conjunction with the Columns property")
    +                    .build());
    +        }
    +
    +        return problems;
    +    }
    +
    +    @Override
    +    public void onTrigger(ProcessContext context, ProcessSession session) throws ProcessException {
    +        FlowFile flowFile = session.get();
    +        if (flowFile == null) {
    +            return;
    +        }
    +
    +        try{
    +            final String tableName = context.getProperty(TABLE_NAME).evaluateAttributeExpressions(flowFile).getValue();
    +            if (StringUtils.isBlank(tableName)) {
    +                getLogger().error("Table Name is blank or null for {}, transferring to failure", new Object[] {flowFile});
    +                session.transfer(session.penalize(flowFile), REL_FAILURE);
    +                return;
    +            }
    +
    +            final String startRow = context.getProperty(START_ROW).evaluateAttributeExpressions(flowFile).getValue();
    +            final String endRow = context.getProperty(END_ROW).evaluateAttributeExpressions(flowFile).getValue();
    +
    +            final String filterExpression = context.getProperty(FILTER_EXPRESSION).evaluateAttributeExpressions(flowFile).getValue();
    +
    +            //evaluate and validate time range min and max values. They both should be either empty or provided.
    +            Long timerangeMin = null;
    +            Long timerangeMax = null;
    +
    +            try{
    +                timerangeMin = context.getProperty(TIME_RANGE_MIN).evaluateAttributeExpressions(flowFile).asLong();
    +            }catch(Exception e){
    +                getLogger().error("Time range min value is not a number ({}) for {}, transferring to failure",
    +                        new Object[] {context.getProperty(TIME_RANGE_MIN).evaluateAttributeExpressions(flowFile).getValue(), flowFile});
    +                session.transfer(session.penalize(flowFile), REL_FAILURE);
    +                return;
    +            }
    +            try{
    +                timerangeMax = context.getProperty(TIME_RANGE_MAX).evaluateAttributeExpressions(flowFile).asLong();
    +            }catch(Exception e){
    +                getLogger().error("Time range max value is not a number ({}) for {}, transferring to failure",
    +                        new Object[] {context.getProperty(TIME_RANGE_MAX).evaluateAttributeExpressions(flowFile).getValue(), flowFile});
    +                session.transfer(session.penalize(flowFile), REL_FAILURE);
    +                return;
    +            }
    +            if (timerangeMin == null && timerangeMax != null) {
    +                getLogger().error("Time range min value cannot be blank when max value provided for {}, transferring to failure", new Object[] {flowFile});
    +                session.transfer(session.penalize(flowFile), REL_FAILURE);
    +                return;
    +            }else if (timerangeMin != null && timerangeMax == null) {
    +                getLogger().error("Time range max value cannot be blank when min value provided for {}, transferring to failure", new Object[] {flowFile});
    +                session.transfer(session.penalize(flowFile), REL_FAILURE);
    +                return;
    +            }
    +
    +            final Integer limitRows = context.getProperty(LIMIT_ROWS).evaluateAttributeExpressions(flowFile).asInteger();
    +
    +            final Boolean isReversed = context.getProperty(REVERSED_SCAN).asBoolean();
    +
    +            final Integer bulkSize = context.getProperty(BULK_SIZE).evaluateAttributeExpressions(flowFile).asInteger();
    +
    +            final List<Column> columns = getColumns(context.getProperty(COLUMNS).evaluateAttributeExpressions(flowFile).getValue());
    +            final HBaseClientService hBaseClientService = context.getProperty(HBASE_CLIENT_SERVICE).asControllerService(HBaseClientService.class);
    +
    +            final AtomicReference<Long> rowsPulledHolder = new AtomicReference<>(0L);
    +            final AtomicReference<Long> ffCountHolder = new AtomicReference<>(0L);
    +            ScanHBaseResultHandler handler = new ScanHBaseResultHandler(context, session, flowFile, rowsPulledHolder, ffCountHolder, hBaseClientService, tableName, bulkSize);
    +
    +            try {
    +                hBaseClientService.scan(tableName,
    +                                        startRow, endRow,
    +                                        filterExpression,
    +                                        timerangeMin, timerangeMax,
    +                                        limitRows,
    +                                        isReversed,
    +                                        columns,
    +                                        handler);
    +            } catch (IOException e) {
    +                getLogger().error("Unable to fetch rows from HBase table {} due to {}", new Object[] {tableName, e});
    +                flowFile = session.putAttribute(flowFile, "scanhbase.results.found", Boolean.toString(handler.isHandledAny()));
    +                session.transfer(flowFile, REL_FAILURE);
    +                return;
    +            }
    +
    +            LinkedList<Tuple<byte[], ResultCell[]>> hangingRows = handler.getHangingRows();
    +            if (!handler.isHandledAny() ||                                                         // no rows found in hbase
    +                    (handler.isHandledAny() && (hangingRows == null || hangingRows.isEmpty()))     // all the rows are flushed to FF inside handlers
    +                ){
    +                flowFile = session.putAttribute(flowFile, "scanhbase.results.found", Boolean.toString(handler.isHandledAny()));
    +                session.transfer(flowFile, REL_ORIGINAL);
    +                session.commit();
    +                return;
    +            }
    +
    +            if (hangingRows != null && !hangingRows.isEmpty()) {
    +                FlowFile lastFF = session.create(flowFile);
    +                final Map<String, String> attributes = new HashMap<>();
    +                attributes.put(HBASE_TABLE_ATTR, tableName);
    +                attributes.put(HBASE_ROWS_COUNT_ATTR, Long.toString(rowsPulledHolder.get()));
    +                attributes.put(CoreAttributes.MIME_TYPE.key(), "application/json");
    +                attributes.put(HBASE_ROWS_COUNT_ATTR, Long.toString(hangingRows.size()));
    +                lastFF = session.putAllAttributes(lastFF, attributes);
    +
    +                final AtomicReference<IOException> ioe = new AtomicReference<>(null);
    +                lastFF = session.write(lastFF, (out) -> {
    +                    for (Iterator<Tuple<byte[], ResultCell[]>> iter = hangingRows.iterator(); iter.hasNext();){
    +                        Tuple<byte[], ResultCell[]> r = iter.next();
    +                        serializer.serialize(r.getKey(), r.getValue(), out);
    +                        if (iter.hasNext()){
    +                            out.write(nl);
    +                        }
    +                    }
    +                });
    +
    +                Relationship rel = REL_SUCCESS;
    +                IOException error = ioe.get();
    +                if (error != null){
    +                    lastFF = session.putAttribute(lastFF, "scanhbase.error", error.toString());
    +                    rel = REL_FAILURE;
    +                }
    +                session.transfer(lastFF, rel);
    --- End diff --
    
    Looking at the code later, it seems like lines 398-423 are the same as 513-539, except there is no generation of a provenance event in this part and there is in the later part.
    
    Assuming we do want a provenance event here and they are the same, then it might make sense to separate this code out into a private method that is called from both places.


---

[GitHub] nifi issue #2478: NIFI-4833 Add scanHBase Processor

Posted by bdesert <gi...@git.apache.org>.
Github user bdesert commented on the issue:

    https://github.com/apache/nifi/pull/2478
  
    @bbende , I addressed all the comments. Thank you and let me know if you see more issues or have some recommendations/suggestions.


---

[GitHub] nifi pull request #2478: NIFI-4833 Add scanHBase Processor

Posted by bdesert <gi...@git.apache.org>.
Github user bdesert commented on a diff in the pull request:

    https://github.com/apache/nifi/pull/2478#discussion_r170697126
  
    --- Diff: nifi-nar-bundles/nifi-hbase-bundle/nifi-hbase-processors/src/main/java/org/apache/nifi/hbase/ScanHBase.java ---
    @@ -0,0 +1,564 @@
    +/*
    + * Licensed to the Apache Software Foundation (ASF) under one or more
    + * contributor license agreements.  See the NOTICE file distributed with
    + * this work for additional information regarding copyright ownership.
    + * The ASF licenses this file to You under the Apache License, Version 2.0
    + * (the "License"); you may not use this file except in compliance with
    + * the License.  You may obtain a copy of the License at
    + *
    + *     http://www.apache.org/licenses/LICENSE-2.0
    + *
    + * Unless required by applicable law or agreed to in writing, software
    + * distributed under the License is distributed on an "AS IS" BASIS,
    + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    + * See the License for the specific language governing permissions and
    + * limitations under the License.
    + */
    +package org.apache.nifi.hbase;
    +
    +import org.apache.commons.lang3.StringUtils;
    +import org.apache.nifi.annotation.behavior.InputRequirement;
    +import org.apache.nifi.annotation.behavior.WritesAttribute;
    +import org.apache.nifi.annotation.behavior.WritesAttributes;
    +import org.apache.nifi.annotation.documentation.CapabilityDescription;
    +import org.apache.nifi.annotation.documentation.Tags;
    +import org.apache.nifi.annotation.lifecycle.OnScheduled;
    +import org.apache.nifi.components.AllowableValue;
    +import org.apache.nifi.components.PropertyDescriptor;
    +import org.apache.nifi.components.ValidationContext;
    +import org.apache.nifi.components.ValidationResult;
    +import org.apache.nifi.flowfile.FlowFile;
    +import org.apache.nifi.flowfile.attributes.CoreAttributes;
    +import org.apache.nifi.hbase.io.JsonFullRowSerializer;
    +import org.apache.nifi.hbase.io.JsonQualifierAndValueRowSerializer;
    +import org.apache.nifi.hbase.io.RowSerializer;
    +import org.apache.nifi.hbase.scan.Column;
    +import org.apache.nifi.hbase.scan.ResultCell;
    +import org.apache.nifi.hbase.scan.ResultHandler;
    +import org.apache.nifi.processor.AbstractProcessor;
    +import org.apache.nifi.processor.ProcessContext;
    +import org.apache.nifi.processor.ProcessSession;
    +import org.apache.nifi.processor.Relationship;
    +import org.apache.nifi.processor.exception.ProcessException;
    +import org.apache.nifi.processor.util.StandardValidators;
    +import org.apache.nifi.util.Tuple;
    +
    +import java.io.IOException;
    +import java.nio.charset.Charset;
    +import java.nio.charset.StandardCharsets;
    +import java.util.ArrayList;
    +import java.util.Collection;
    +import java.util.Collections;
    +import java.util.HashMap;
    +import java.util.HashSet;
    +import java.util.Iterator;
    +import java.util.LinkedList;
    +import java.util.List;
    +import java.util.Map;
    +import java.util.Set;
    +import java.util.concurrent.atomic.AtomicReference;
    +import java.util.regex.Pattern;
    +
    +@InputRequirement(InputRequirement.Requirement.INPUT_REQUIRED)
    +@Tags({"hbase", "scan", "fetch", "get"})
    +@CapabilityDescription("Scans and fetches rows from an HBase table. This processor may be used to fetch rows from hbase table by specifying a range of rowkey values (start and/or end ),"
    +        + "by time range, by filter expression, or any combination of them. "
    +        + "Order of records can be controlled by a property Reversed"
    +        + "Number of rows retrieved by the processor can be limited.")
    +@WritesAttributes({
    +        @WritesAttribute(attribute = "hbase.table", description = "The name of the HBase table that the row was fetched from"),
    +        @WritesAttribute(attribute = "hbase.resultset", description = "A JSON document/s representing the row/s. This property is only written when a Destination of flowfile-attributes is selected."),
    +        @WritesAttribute(attribute = "mime.type", description = "Set to application/json when using a Destination of flowfile-content, not set or modified otherwise"),
    +        @WritesAttribute(attribute = "hbase.rows.count", description = "Number of rows in the content of given flow file"),
    +        @WritesAttribute(attribute = "scanhbase.results.found", description = "Indicates whether at least one row has been found in given hbase table with provided conditions. "
    +                + "Could be null (not present) if transfered to FAILURE")
    +})
    +public class ScanHBase extends AbstractProcessor {
    +    //enhanced regex for columns to allow "-" in column qualifier names
    +    static final Pattern COLUMNS_PATTERN = Pattern.compile("\\w+(:(\\w|-)+)?(?:,\\w+(:(\\w|-)+)?)*");
    +    static final byte[] nl = System.lineSeparator().getBytes();
    +
    +    static final PropertyDescriptor HBASE_CLIENT_SERVICE = new PropertyDescriptor.Builder()
    +            .displayName("HBase Client Service")
    +            .name("scanhbase-client-service")
    +            .description("Specifies the Controller Service to use for accessing HBase.")
    +            .required(true)
    +            .identifiesControllerService(HBaseClientService.class)
    +            .build();
    +
    +    static final PropertyDescriptor TABLE_NAME = new PropertyDescriptor.Builder()
    +            .displayName("Table Name")
    +            .name("scanhbase-table-name")
    +            .description("The name of the HBase Table to fetch from.")
    +            .required(true)
    +            .expressionLanguageSupported(true)
    +            .addValidator(StandardValidators.NON_EMPTY_VALIDATOR)
    +            .build();
    +
    +    static final PropertyDescriptor START_ROW = new PropertyDescriptor.Builder()
    +            .displayName("Start rowkey")
    +            .name("scanhbase-start-rowkey")
    +            .description("The rowkey to start scan from.")
    +            .required(false)
    +            .expressionLanguageSupported(true)
    +            .addValidator(StandardValidators.NON_EMPTY_VALIDATOR)
    +            .build();
    +
    +    static final PropertyDescriptor END_ROW = new PropertyDescriptor.Builder()
    +            .displayName("End rowkey")
    +            .name("scanhbase-end-rowkey")
    +            .description("The row key to end scan by.")
    +            .required(false)
    +            .expressionLanguageSupported(true)
    +            .addValidator(StandardValidators.NON_EMPTY_VALIDATOR)
    +            .build();
    +
    +    static final PropertyDescriptor TIME_RANGE_MIN = new PropertyDescriptor.Builder()
    +            .displayName("Time range min")
    +            .name("scanhbase-time-range-min")
    +            .description("Time range min value. Both min and max values for time range should be either blank or provided.")
    +            .required(false)
    +            .expressionLanguageSupported(true)
    +            .addValidator(StandardValidators.LONG_VALIDATOR)
    +            .build();
    +
    +    static final PropertyDescriptor TIME_RANGE_MAX = new PropertyDescriptor.Builder()
    +            .displayName("Time range max")
    +            .name("scanhbase-time-range-max")
    +            .description("Time range max value. Both min and max values for time range should be either blank or provided.")
    +            .required(false)
    +            .expressionLanguageSupported(true)
    +            .addValidator(StandardValidators.LONG_VALIDATOR)
    +            .build();
    +
    +    static final PropertyDescriptor LIMIT_ROWS = new PropertyDescriptor.Builder()
    +            .displayName("Limit rows")
    +            .name("scanhbase-limit")
    +            .description("Limit number of rows retrieved by scan.")
    +            .required(false)
    +            .expressionLanguageSupported(true)
    +            .addValidator(StandardValidators.INTEGER_VALIDATOR)
    +            .build();
    +
    +    static final PropertyDescriptor BULK_SIZE = new PropertyDescriptor.Builder()
    +            .displayName("Max rows per flow file")
    +            .name("scanhbase-bulk-size")
    +            .description("Limits number of rows in single flow file content. Set to 0 to avoid multiple flow files.")
    +            .required(false)
    +            .expressionLanguageSupported(true)
    +            .defaultValue("0")
    +            .addValidator(StandardValidators.INTEGER_VALIDATOR)
    +            .build();
    +
    +    static final PropertyDescriptor REVERSED_SCAN = new PropertyDescriptor.Builder()
    +            .displayName("Reversed order")
    +            .name("scanhbase-reversed-order")
    +            .description("Set whether this scan is a reversed one. This is false by default which means forward(normal) scan.")
    +            .expressionLanguageSupported(false)
    +            .allowableValues("true", "false")
    +            .required(false)
    +            .defaultValue("false")
    +            .addValidator(StandardValidators.BOOLEAN_VALIDATOR)
    +            .build();
    +
    +    static final PropertyDescriptor FILTER_EXPRESSION = new PropertyDescriptor.Builder()
    +            .displayName("Filter expression")
    +            .name("scanhbase-filter-expression")
    +            .description("An HBase filter expression that will be applied to the scan. This property can not be used when also using the Columns property. "
    +                    + "Example: \"ValueFilter( =, 'binaryprefix:commit' )\"")
    +            .required(false)
    +            .expressionLanguageSupported(true)
    +            .addValidator(StandardValidators.NON_EMPTY_VALIDATOR)
    +            .build();
    +
    +    static final PropertyDescriptor COLUMNS = new PropertyDescriptor.Builder()
    +            .displayName("Columns")
    +            .name("scanhbase-columns")
    +            .description("An optional comma-separated list of \"<colFamily>:<colQualifier>\" pairs to fetch. To return all columns " +
    +                    "for a given family, leave off the qualifier such as \"<colFamily1>,<colFamily2>\".")
    +            .required(false)
    +            .expressionLanguageSupported(true)
    +            .addValidator(StandardValidators.createRegexMatchingValidator(COLUMNS_PATTERN))
    +            .build();
    +
    +    static final AllowableValue JSON_FORMAT_FULL_ROW = new AllowableValue("full-row", "full-row",
    +            "Creates a JSON document with the format: {\"row\":<row-id>, \"cells\":[{\"fam\":<col-fam>, \"qual\":<col-val>, \"val\":<value>, \"ts\":<timestamp>}]}.");
    +    static final AllowableValue JSON_FORMAT_QUALIFIER_AND_VALUE = new AllowableValue("col-qual-and-val", "col-qual-and-val",
    +            "Creates a JSON document with the format: {\"<col-qual>\":\"<value>\", \"<col-qual>\":\"<value>\".");
    +
    +    static final PropertyDescriptor JSON_FORMAT = new PropertyDescriptor.Builder()
    +            .displayName("JSON Format")
    +            .name("scanhbase-json-format")
    +            .description("Specifies how to represent the HBase row as a JSON document.")
    +            .required(true)
    +            .allowableValues(JSON_FORMAT_FULL_ROW, JSON_FORMAT_QUALIFIER_AND_VALUE)
    +            .defaultValue(JSON_FORMAT_FULL_ROW.getValue())
    +            .build();
    +
    +    static final PropertyDescriptor DECODE_CHARSET = new PropertyDescriptor.Builder()
    +            .displayName("Decode Character Set")
    +            .name("scanhbase-decode-charset")
    +            .description("The character set used to decode data from HBase.")
    +            .required(true)
    +            .defaultValue("UTF-8")
    +            .addValidator(StandardValidators.CHARACTER_SET_VALIDATOR)
    +            .build();
    +
    +    static final PropertyDescriptor ENCODE_CHARSET = new PropertyDescriptor.Builder()
    +            .displayName("Encode Character Set")
    +            .name("scanhbase-encode-charset")
    +            .description("The character set used to encode the JSON representation of the row.")
    +            .required(true)
    +            .defaultValue("UTF-8")
    +            .addValidator(StandardValidators.CHARACTER_SET_VALIDATOR)
    +            .build();
    +
    +    public static final Relationship REL_ORIGINAL = new Relationship.Builder()
    +            .name("original")
    +            .description("The original input file will be routed to this destination, even if no rows are retrieved based on provided conditions.")
    +            .build();
    +
    +    static final Relationship REL_SUCCESS = new Relationship.Builder()
    +            .name("success")
    +            .description("All successful fetches are routed to this relationship.")
    +            .build();
    +    static final Relationship REL_FAILURE = new Relationship.Builder()
    +            .name("failure")
    +            .description("All failed fetches are routed to this relationship.")
    +            .build();
    +
    +    static final String HBASE_TABLE_ATTR = "hbase.table";
    +    static final String HBASE_ROWS_COUNT_ATTR = "hbase.rows.count";
    +
    +    static final List<PropertyDescriptor> properties;
    +    static {
    +        List<PropertyDescriptor> props = new ArrayList<>();
    +        props.add(HBASE_CLIENT_SERVICE);
    +        props.add(TABLE_NAME);
    +        props.add(START_ROW);
    +        props.add(END_ROW);
    +        props.add(TIME_RANGE_MIN);
    +        props.add(TIME_RANGE_MAX);
    +        props.add(LIMIT_ROWS);
    +        props.add(REVERSED_SCAN);
    +        props.add(BULK_SIZE);
    +        props.add(FILTER_EXPRESSION);
    +        props.add(COLUMNS);
    +        props.add(JSON_FORMAT);
    +        props.add(ENCODE_CHARSET);
    +        props.add(DECODE_CHARSET);
    +        properties = Collections.unmodifiableList(props);
    +    }
    +
    +    static final Set<Relationship> relationships;
    +    static {
    +        Set<Relationship> rels = new HashSet<>();
    +        rels.add(REL_SUCCESS);
    +        rels.add(REL_ORIGINAL);
    +        rels.add(REL_FAILURE);
    +        relationships = Collections.unmodifiableSet(rels);
    +    }
    +
    +    private volatile Charset decodeCharset;
    +    private volatile Charset encodeCharset;
    +    private RowSerializer serializer = null;
    +
    +    @OnScheduled
    +    public void onScheduled(ProcessContext context) {
    +        this.decodeCharset = Charset.forName(context.getProperty(DECODE_CHARSET).getValue());
    +        this.encodeCharset = Charset.forName(context.getProperty(ENCODE_CHARSET).getValue());
    +
    +        final String jsonFormat = context.getProperty(JSON_FORMAT).getValue();
    +        if (jsonFormat.equals(JSON_FORMAT_FULL_ROW.getValue())) {
    +            this.serializer = new JsonFullRowSerializer(decodeCharset, encodeCharset);
    +        } else {
    +            this.serializer = new JsonQualifierAndValueRowSerializer(decodeCharset, encodeCharset);
    +        }
    +    }
    +
    +    @Override
    +    protected List<PropertyDescriptor> getSupportedPropertyDescriptors() {
    +        return properties;
    +    }
    +
    +    @Override
    +    public Set<Relationship> getRelationships() {
    +        return relationships;
    +    }
    +
    +    @Override
    +    protected Collection<ValidationResult> customValidate(ValidationContext validationContext) {
    +
    +        final List<ValidationResult> problems = new ArrayList<>();
    +
    +        final String columns = validationContext.getProperty(COLUMNS).getValue();
    +        final String filter = validationContext.getProperty(FILTER_EXPRESSION).getValue();
    +
    +        if (!StringUtils.isBlank(columns) && !StringUtils.isBlank(filter)) {
    +            problems.add(new ValidationResult.Builder()
    +                    .subject(FILTER_EXPRESSION.getDisplayName())
    +                    .input(filter).valid(false)
    +                    .explanation("A filter expression can not be used in conjunction with the Columns property")
    +                    .build());
    +        }
    +
    --- End diff --
    
    Since it supports EL, I validate this condition in onTrigger (lines 348-356). If you think we should add it also to customValidate, I can add it


---

[GitHub] nifi issue #2478: NIFI-4833 Add scanHBase Processor

Posted by bbende <gi...@git.apache.org>.
Github user bbende commented on the issue:

    https://github.com/apache/nifi/pull/2478
  
    Latest update looks good, going to merge


---

[GitHub] nifi pull request #2478: NIFI-4833 Add scanHBase Processor

Posted by bbende <gi...@git.apache.org>.
Github user bbende commented on a diff in the pull request:

    https://github.com/apache/nifi/pull/2478#discussion_r170686168
  
    --- Diff: nifi-nar-bundles/nifi-hbase-bundle/nifi-hbase-processors/src/main/java/org/apache/nifi/hbase/ScanHBase.java ---
    @@ -0,0 +1,564 @@
    +/*
    + * Licensed to the Apache Software Foundation (ASF) under one or more
    + * contributor license agreements.  See the NOTICE file distributed with
    + * this work for additional information regarding copyright ownership.
    + * The ASF licenses this file to You under the Apache License, Version 2.0
    + * (the "License"); you may not use this file except in compliance with
    + * the License.  You may obtain a copy of the License at
    + *
    + *     http://www.apache.org/licenses/LICENSE-2.0
    + *
    + * Unless required by applicable law or agreed to in writing, software
    + * distributed under the License is distributed on an "AS IS" BASIS,
    + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    + * See the License for the specific language governing permissions and
    + * limitations under the License.
    + */
    +package org.apache.nifi.hbase;
    +
    +import org.apache.commons.lang3.StringUtils;
    +import org.apache.nifi.annotation.behavior.InputRequirement;
    +import org.apache.nifi.annotation.behavior.WritesAttribute;
    +import org.apache.nifi.annotation.behavior.WritesAttributes;
    +import org.apache.nifi.annotation.documentation.CapabilityDescription;
    +import org.apache.nifi.annotation.documentation.Tags;
    +import org.apache.nifi.annotation.lifecycle.OnScheduled;
    +import org.apache.nifi.components.AllowableValue;
    +import org.apache.nifi.components.PropertyDescriptor;
    +import org.apache.nifi.components.ValidationContext;
    +import org.apache.nifi.components.ValidationResult;
    +import org.apache.nifi.flowfile.FlowFile;
    +import org.apache.nifi.flowfile.attributes.CoreAttributes;
    +import org.apache.nifi.hbase.io.JsonFullRowSerializer;
    +import org.apache.nifi.hbase.io.JsonQualifierAndValueRowSerializer;
    +import org.apache.nifi.hbase.io.RowSerializer;
    +import org.apache.nifi.hbase.scan.Column;
    +import org.apache.nifi.hbase.scan.ResultCell;
    +import org.apache.nifi.hbase.scan.ResultHandler;
    +import org.apache.nifi.processor.AbstractProcessor;
    +import org.apache.nifi.processor.ProcessContext;
    +import org.apache.nifi.processor.ProcessSession;
    +import org.apache.nifi.processor.Relationship;
    +import org.apache.nifi.processor.exception.ProcessException;
    +import org.apache.nifi.processor.util.StandardValidators;
    +import org.apache.nifi.util.Tuple;
    +
    +import java.io.IOException;
    +import java.nio.charset.Charset;
    +import java.nio.charset.StandardCharsets;
    +import java.util.ArrayList;
    +import java.util.Collection;
    +import java.util.Collections;
    +import java.util.HashMap;
    +import java.util.HashSet;
    +import java.util.Iterator;
    +import java.util.LinkedList;
    +import java.util.List;
    +import java.util.Map;
    +import java.util.Set;
    +import java.util.concurrent.atomic.AtomicReference;
    +import java.util.regex.Pattern;
    +
    +@InputRequirement(InputRequirement.Requirement.INPUT_REQUIRED)
    +@Tags({"hbase", "scan", "fetch", "get"})
    +@CapabilityDescription("Scans and fetches rows from an HBase table. This processor may be used to fetch rows from hbase table by specifying a range of rowkey values (start and/or end ),"
    +        + "by time range, by filter expression, or any combination of them. "
    +        + "Order of records can be controlled by a property Reversed"
    +        + "Number of rows retrieved by the processor can be limited.")
    +@WritesAttributes({
    +        @WritesAttribute(attribute = "hbase.table", description = "The name of the HBase table that the row was fetched from"),
    +        @WritesAttribute(attribute = "hbase.resultset", description = "A JSON document/s representing the row/s. This property is only written when a Destination of flowfile-attributes is selected."),
    +        @WritesAttribute(attribute = "mime.type", description = "Set to application/json when using a Destination of flowfile-content, not set or modified otherwise"),
    +        @WritesAttribute(attribute = "hbase.rows.count", description = "Number of rows in the content of given flow file"),
    +        @WritesAttribute(attribute = "scanhbase.results.found", description = "Indicates whether at least one row has been found in given hbase table with provided conditions. "
    +                + "Could be null (not present) if transfered to FAILURE")
    +})
    +public class ScanHBase extends AbstractProcessor {
    +    //enhanced regex for columns to allow "-" in column qualifier names
    +    static final Pattern COLUMNS_PATTERN = Pattern.compile("\\w+(:(\\w|-)+)?(?:,\\w+(:(\\w|-)+)?)*");
    +    static final byte[] nl = System.lineSeparator().getBytes();
    +
    +    static final PropertyDescriptor HBASE_CLIENT_SERVICE = new PropertyDescriptor.Builder()
    +            .displayName("HBase Client Service")
    +            .name("scanhbase-client-service")
    +            .description("Specifies the Controller Service to use for accessing HBase.")
    +            .required(true)
    +            .identifiesControllerService(HBaseClientService.class)
    +            .build();
    +
    +    static final PropertyDescriptor TABLE_NAME = new PropertyDescriptor.Builder()
    +            .displayName("Table Name")
    +            .name("scanhbase-table-name")
    +            .description("The name of the HBase Table to fetch from.")
    +            .required(true)
    +            .expressionLanguageSupported(true)
    +            .addValidator(StandardValidators.NON_EMPTY_VALIDATOR)
    +            .build();
    +
    +    static final PropertyDescriptor START_ROW = new PropertyDescriptor.Builder()
    +            .displayName("Start rowkey")
    +            .name("scanhbase-start-rowkey")
    +            .description("The rowkey to start scan from.")
    +            .required(false)
    +            .expressionLanguageSupported(true)
    +            .addValidator(StandardValidators.NON_EMPTY_VALIDATOR)
    +            .build();
    +
    +    static final PropertyDescriptor END_ROW = new PropertyDescriptor.Builder()
    +            .displayName("End rowkey")
    +            .name("scanhbase-end-rowkey")
    +            .description("The row key to end scan by.")
    +            .required(false)
    +            .expressionLanguageSupported(true)
    +            .addValidator(StandardValidators.NON_EMPTY_VALIDATOR)
    +            .build();
    +
    +    static final PropertyDescriptor TIME_RANGE_MIN = new PropertyDescriptor.Builder()
    +            .displayName("Time range min")
    +            .name("scanhbase-time-range-min")
    +            .description("Time range min value. Both min and max values for time range should be either blank or provided.")
    +            .required(false)
    +            .expressionLanguageSupported(true)
    +            .addValidator(StandardValidators.LONG_VALIDATOR)
    +            .build();
    +
    +    static final PropertyDescriptor TIME_RANGE_MAX = new PropertyDescriptor.Builder()
    +            .displayName("Time range max")
    +            .name("scanhbase-time-range-max")
    +            .description("Time range max value. Both min and max values for time range should be either blank or provided.")
    +            .required(false)
    +            .expressionLanguageSupported(true)
    +            .addValidator(StandardValidators.LONG_VALIDATOR)
    +            .build();
    +
    +    static final PropertyDescriptor LIMIT_ROWS = new PropertyDescriptor.Builder()
    +            .displayName("Limit rows")
    +            .name("scanhbase-limit")
    +            .description("Limit number of rows retrieved by scan.")
    +            .required(false)
    +            .expressionLanguageSupported(true)
    +            .addValidator(StandardValidators.INTEGER_VALIDATOR)
    +            .build();
    +
    +    static final PropertyDescriptor BULK_SIZE = new PropertyDescriptor.Builder()
    +            .displayName("Max rows per flow file")
    +            .name("scanhbase-bulk-size")
    +            .description("Limits number of rows in single flow file content. Set to 0 to avoid multiple flow files.")
    +            .required(false)
    +            .expressionLanguageSupported(true)
    +            .defaultValue("0")
    +            .addValidator(StandardValidators.INTEGER_VALIDATOR)
    +            .build();
    +
    +    static final PropertyDescriptor REVERSED_SCAN = new PropertyDescriptor.Builder()
    +            .displayName("Reversed order")
    +            .name("scanhbase-reversed-order")
    +            .description("Set whether this scan is a reversed one. This is false by default which means forward(normal) scan.")
    +            .expressionLanguageSupported(false)
    +            .allowableValues("true", "false")
    +            .required(false)
    +            .defaultValue("false")
    +            .addValidator(StandardValidators.BOOLEAN_VALIDATOR)
    +            .build();
    +
    +    static final PropertyDescriptor FILTER_EXPRESSION = new PropertyDescriptor.Builder()
    +            .displayName("Filter expression")
    +            .name("scanhbase-filter-expression")
    +            .description("An HBase filter expression that will be applied to the scan. This property can not be used when also using the Columns property. "
    +                    + "Example: \"ValueFilter( =, 'binaryprefix:commit' )\"")
    +            .required(false)
    +            .expressionLanguageSupported(true)
    +            .addValidator(StandardValidators.NON_EMPTY_VALIDATOR)
    +            .build();
    +
    +    static final PropertyDescriptor COLUMNS = new PropertyDescriptor.Builder()
    +            .displayName("Columns")
    +            .name("scanhbase-columns")
    +            .description("An optional comma-separated list of \"<colFamily>:<colQualifier>\" pairs to fetch. To return all columns " +
    +                    "for a given family, leave off the qualifier such as \"<colFamily1>,<colFamily2>\".")
    +            .required(false)
    +            .expressionLanguageSupported(true)
    +            .addValidator(StandardValidators.createRegexMatchingValidator(COLUMNS_PATTERN))
    +            .build();
    +
    +    static final AllowableValue JSON_FORMAT_FULL_ROW = new AllowableValue("full-row", "full-row",
    +            "Creates a JSON document with the format: {\"row\":<row-id>, \"cells\":[{\"fam\":<col-fam>, \"qual\":<col-val>, \"val\":<value>, \"ts\":<timestamp>}]}.");
    +    static final AllowableValue JSON_FORMAT_QUALIFIER_AND_VALUE = new AllowableValue("col-qual-and-val", "col-qual-and-val",
    +            "Creates a JSON document with the format: {\"<col-qual>\":\"<value>\", \"<col-qual>\":\"<value>\".");
    +
    +    static final PropertyDescriptor JSON_FORMAT = new PropertyDescriptor.Builder()
    +            .displayName("JSON Format")
    +            .name("scanhbase-json-format")
    +            .description("Specifies how to represent the HBase row as a JSON document.")
    +            .required(true)
    +            .allowableValues(JSON_FORMAT_FULL_ROW, JSON_FORMAT_QUALIFIER_AND_VALUE)
    +            .defaultValue(JSON_FORMAT_FULL_ROW.getValue())
    +            .build();
    +
    +    static final PropertyDescriptor DECODE_CHARSET = new PropertyDescriptor.Builder()
    +            .displayName("Decode Character Set")
    +            .name("scanhbase-decode-charset")
    +            .description("The character set used to decode data from HBase.")
    +            .required(true)
    +            .defaultValue("UTF-8")
    +            .addValidator(StandardValidators.CHARACTER_SET_VALIDATOR)
    +            .build();
    +
    +    static final PropertyDescriptor ENCODE_CHARSET = new PropertyDescriptor.Builder()
    +            .displayName("Encode Character Set")
    +            .name("scanhbase-encode-charset")
    +            .description("The character set used to encode the JSON representation of the row.")
    +            .required(true)
    +            .defaultValue("UTF-8")
    +            .addValidator(StandardValidators.CHARACTER_SET_VALIDATOR)
    +            .build();
    +
    +    public static final Relationship REL_ORIGINAL = new Relationship.Builder()
    +            .name("original")
    +            .description("The original input file will be routed to this destination, even if no rows are retrieved based on provided conditions.")
    +            .build();
    +
    +    static final Relationship REL_SUCCESS = new Relationship.Builder()
    +            .name("success")
    +            .description("All successful fetches are routed to this relationship.")
    +            .build();
    +    static final Relationship REL_FAILURE = new Relationship.Builder()
    +            .name("failure")
    +            .description("All failed fetches are routed to this relationship.")
    +            .build();
    +
    +    static final String HBASE_TABLE_ATTR = "hbase.table";
    +    static final String HBASE_ROWS_COUNT_ATTR = "hbase.rows.count";
    +
    +    static final List<PropertyDescriptor> properties;
    +    static {
    +        List<PropertyDescriptor> props = new ArrayList<>();
    +        props.add(HBASE_CLIENT_SERVICE);
    +        props.add(TABLE_NAME);
    +        props.add(START_ROW);
    +        props.add(END_ROW);
    +        props.add(TIME_RANGE_MIN);
    +        props.add(TIME_RANGE_MAX);
    +        props.add(LIMIT_ROWS);
    +        props.add(REVERSED_SCAN);
    +        props.add(BULK_SIZE);
    +        props.add(FILTER_EXPRESSION);
    +        props.add(COLUMNS);
    +        props.add(JSON_FORMAT);
    +        props.add(ENCODE_CHARSET);
    +        props.add(DECODE_CHARSET);
    +        properties = Collections.unmodifiableList(props);
    +    }
    +
    +    static final Set<Relationship> relationships;
    +    static {
    +        Set<Relationship> rels = new HashSet<>();
    +        rels.add(REL_SUCCESS);
    +        rels.add(REL_ORIGINAL);
    +        rels.add(REL_FAILURE);
    +        relationships = Collections.unmodifiableSet(rels);
    +    }
    +
    +    private volatile Charset decodeCharset;
    +    private volatile Charset encodeCharset;
    +    private RowSerializer serializer = null;
    +
    +    @OnScheduled
    +    public void onScheduled(ProcessContext context) {
    +        this.decodeCharset = Charset.forName(context.getProperty(DECODE_CHARSET).getValue());
    +        this.encodeCharset = Charset.forName(context.getProperty(ENCODE_CHARSET).getValue());
    +
    +        final String jsonFormat = context.getProperty(JSON_FORMAT).getValue();
    +        if (jsonFormat.equals(JSON_FORMAT_FULL_ROW.getValue())) {
    +            this.serializer = new JsonFullRowSerializer(decodeCharset, encodeCharset);
    +        } else {
    +            this.serializer = new JsonQualifierAndValueRowSerializer(decodeCharset, encodeCharset);
    +        }
    +    }
    +
    +    @Override
    +    protected List<PropertyDescriptor> getSupportedPropertyDescriptors() {
    +        return properties;
    +    }
    +
    +    @Override
    +    public Set<Relationship> getRelationships() {
    +        return relationships;
    +    }
    +
    +    @Override
    +    protected Collection<ValidationResult> customValidate(ValidationContext validationContext) {
    +
    +        final List<ValidationResult> problems = new ArrayList<>();
    +
    +        final String columns = validationContext.getProperty(COLUMNS).getValue();
    +        final String filter = validationContext.getProperty(FILTER_EXPRESSION).getValue();
    +
    +        if (!StringUtils.isBlank(columns) && !StringUtils.isBlank(filter)) {
    +            problems.add(new ValidationResult.Builder()
    +                    .subject(FILTER_EXPRESSION.getDisplayName())
    +                    .input(filter).valid(false)
    +                    .explanation("A filter expression can not be used in conjunction with the Columns property")
    +                    .build());
    +        }
    +
    +        return problems;
    +    }
    +
    +    @Override
    +    public void onTrigger(ProcessContext context, ProcessSession session) throws ProcessException {
    +        FlowFile flowFile = session.get();
    +        if (flowFile == null) {
    +            return;
    +        }
    +
    +        try{
    +            final String tableName = context.getProperty(TABLE_NAME).evaluateAttributeExpressions(flowFile).getValue();
    +            if (StringUtils.isBlank(tableName)) {
    +                getLogger().error("Table Name is blank or null for {}, transferring to failure", new Object[] {flowFile});
    +                session.transfer(session.penalize(flowFile), REL_FAILURE);
    +                return;
    +            }
    +
    +            final String startRow = context.getProperty(START_ROW).evaluateAttributeExpressions(flowFile).getValue();
    +            final String endRow = context.getProperty(END_ROW).evaluateAttributeExpressions(flowFile).getValue();
    +
    +            final String filterExpression = context.getProperty(FILTER_EXPRESSION).evaluateAttributeExpressions(flowFile).getValue();
    +
    +            //evaluate and validate time range min and max values. They both should be either empty or provided.
    +            Long timerangeMin = null;
    +            Long timerangeMax = null;
    +
    +            try{
    +                timerangeMin = context.getProperty(TIME_RANGE_MIN).evaluateAttributeExpressions(flowFile).asLong();
    +            }catch(Exception e){
    +                getLogger().error("Time range min value is not a number ({}) for {}, transferring to failure",
    +                        new Object[] {context.getProperty(TIME_RANGE_MIN).evaluateAttributeExpressions(flowFile).getValue(), flowFile});
    +                session.transfer(session.penalize(flowFile), REL_FAILURE);
    +                return;
    +            }
    +            try{
    +                timerangeMax = context.getProperty(TIME_RANGE_MAX).evaluateAttributeExpressions(flowFile).asLong();
    +            }catch(Exception e){
    +                getLogger().error("Time range max value is not a number ({}) for {}, transferring to failure",
    +                        new Object[] {context.getProperty(TIME_RANGE_MAX).evaluateAttributeExpressions(flowFile).getValue(), flowFile});
    +                session.transfer(session.penalize(flowFile), REL_FAILURE);
    +                return;
    +            }
    +            if (timerangeMin == null && timerangeMax != null) {
    +                getLogger().error("Time range min value cannot be blank when max value provided for {}, transferring to failure", new Object[] {flowFile});
    +                session.transfer(session.penalize(flowFile), REL_FAILURE);
    +                return;
    +            }else if (timerangeMin != null && timerangeMax == null) {
    +                getLogger().error("Time range max value cannot be blank when min value provided for {}, transferring to failure", new Object[] {flowFile});
    +                session.transfer(session.penalize(flowFile), REL_FAILURE);
    +                return;
    +            }
    +
    +            final Integer limitRows = context.getProperty(LIMIT_ROWS).evaluateAttributeExpressions(flowFile).asInteger();
    +
    +            final Boolean isReversed = context.getProperty(REVERSED_SCAN).asBoolean();
    +
    +            final Integer bulkSize = context.getProperty(BULK_SIZE).evaluateAttributeExpressions(flowFile).asInteger();
    --- End diff --
    
    What happens if limitRows or bulkSize reference an attribute that doesn't exist?
    
    I think these will end up as null and I can't tell if the rest of the code protects against that case.


---

[GitHub] nifi pull request #2478: NIFI-4833 Add scanHBase Processor

Posted by MikeThomsen <gi...@git.apache.org>.
Github user MikeThomsen commented on a diff in the pull request:

    https://github.com/apache/nifi/pull/2478#discussion_r169623164
  
    --- Diff: nifi-nar-bundles/nifi-hbase-bundle/nifi-hbase-processors/src/main/java/org/apache/nifi/hbase/ScanHBase.java ---
    @@ -0,0 +1,562 @@
    +/*
    + * Licensed to the Apache Software Foundation (ASF) under one or more
    + * contributor license agreements.  See the NOTICE file distributed with
    + * this work for additional information regarding copyright ownership.
    + * The ASF licenses this file to You under the Apache License, Version 2.0
    + * (the "License"); you may not use this file except in compliance with
    + * the License.  You may obtain a copy of the License at
    + *
    + *     http://www.apache.org/licenses/LICENSE-2.0
    + *
    + * Unless required by applicable law or agreed to in writing, software
    + * distributed under the License is distributed on an "AS IS" BASIS,
    + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    + * See the License for the specific language governing permissions and
    + * limitations under the License.
    + */
    +package org.apache.nifi.hbase;
    +
    +import org.apache.commons.lang3.StringUtils;
    +import org.apache.nifi.annotation.behavior.InputRequirement;
    +import org.apache.nifi.annotation.behavior.WritesAttribute;
    +import org.apache.nifi.annotation.behavior.WritesAttributes;
    +import org.apache.nifi.annotation.documentation.CapabilityDescription;
    +import org.apache.nifi.annotation.documentation.Tags;
    +import org.apache.nifi.annotation.lifecycle.OnScheduled;
    +import org.apache.nifi.components.AllowableValue;
    +import org.apache.nifi.components.PropertyDescriptor;
    +import org.apache.nifi.components.ValidationContext;
    +import org.apache.nifi.components.ValidationResult;
    +import org.apache.nifi.flowfile.FlowFile;
    +import org.apache.nifi.flowfile.attributes.CoreAttributes;
    +import org.apache.nifi.hbase.io.JsonFullRowSerializer;
    +import org.apache.nifi.hbase.io.JsonQualifierAndValueRowSerializer;
    +import org.apache.nifi.hbase.io.RowSerializer;
    +import org.apache.nifi.hbase.scan.Column;
    +import org.apache.nifi.hbase.scan.ResultCell;
    +import org.apache.nifi.hbase.scan.ResultHandler;
    +import org.apache.nifi.processor.AbstractProcessor;
    +import org.apache.nifi.processor.ProcessContext;
    +import org.apache.nifi.processor.ProcessSession;
    +import org.apache.nifi.processor.Relationship;
    +import org.apache.nifi.processor.exception.ProcessException;
    +import org.apache.nifi.processor.util.StandardValidators;
    +import org.apache.nifi.util.Tuple;
    +
    +import java.io.IOException;
    +import java.nio.charset.Charset;
    +import java.nio.charset.StandardCharsets;
    +import java.util.ArrayList;
    +import java.util.Collection;
    +import java.util.Collections;
    +import java.util.HashMap;
    +import java.util.HashSet;
    +import java.util.Iterator;
    +import java.util.LinkedList;
    +import java.util.List;
    +import java.util.Map;
    +import java.util.Set;
    +import java.util.concurrent.atomic.AtomicReference;
    +import java.util.regex.Pattern;
    +
    +@InputRequirement(InputRequirement.Requirement.INPUT_REQUIRED)
    --- End diff --
    
    Are you sure you don't want to do `INPUT_ALLOWED`? I can see good reasons not to do that. If you want to make it optional, see `ExecuteSQL` for some code you can steal to make it not do processing on flowfile input AND time interval.


---

[GitHub] nifi pull request #2478: NIFI-4833 Add scanHBase Processor

Posted by bdesert <gi...@git.apache.org>.
Github user bdesert commented on a diff in the pull request:

    https://github.com/apache/nifi/pull/2478#discussion_r170700319
  
    --- Diff: nifi-nar-bundles/nifi-hbase-bundle/nifi-hbase-processors/src/main/java/org/apache/nifi/hbase/ScanHBase.java ---
    @@ -0,0 +1,564 @@
    +/*
    + * Licensed to the Apache Software Foundation (ASF) under one or more
    + * contributor license agreements.  See the NOTICE file distributed with
    + * this work for additional information regarding copyright ownership.
    + * The ASF licenses this file to You under the Apache License, Version 2.0
    + * (the "License"); you may not use this file except in compliance with
    + * the License.  You may obtain a copy of the License at
    + *
    + *     http://www.apache.org/licenses/LICENSE-2.0
    + *
    + * Unless required by applicable law or agreed to in writing, software
    + * distributed under the License is distributed on an "AS IS" BASIS,
    + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    + * See the License for the specific language governing permissions and
    + * limitations under the License.
    + */
    +package org.apache.nifi.hbase;
    +
    +import org.apache.commons.lang3.StringUtils;
    +import org.apache.nifi.annotation.behavior.InputRequirement;
    +import org.apache.nifi.annotation.behavior.WritesAttribute;
    +import org.apache.nifi.annotation.behavior.WritesAttributes;
    +import org.apache.nifi.annotation.documentation.CapabilityDescription;
    +import org.apache.nifi.annotation.documentation.Tags;
    +import org.apache.nifi.annotation.lifecycle.OnScheduled;
    +import org.apache.nifi.components.AllowableValue;
    +import org.apache.nifi.components.PropertyDescriptor;
    +import org.apache.nifi.components.ValidationContext;
    +import org.apache.nifi.components.ValidationResult;
    +import org.apache.nifi.flowfile.FlowFile;
    +import org.apache.nifi.flowfile.attributes.CoreAttributes;
    +import org.apache.nifi.hbase.io.JsonFullRowSerializer;
    +import org.apache.nifi.hbase.io.JsonQualifierAndValueRowSerializer;
    +import org.apache.nifi.hbase.io.RowSerializer;
    +import org.apache.nifi.hbase.scan.Column;
    +import org.apache.nifi.hbase.scan.ResultCell;
    +import org.apache.nifi.hbase.scan.ResultHandler;
    +import org.apache.nifi.processor.AbstractProcessor;
    +import org.apache.nifi.processor.ProcessContext;
    +import org.apache.nifi.processor.ProcessSession;
    +import org.apache.nifi.processor.Relationship;
    +import org.apache.nifi.processor.exception.ProcessException;
    +import org.apache.nifi.processor.util.StandardValidators;
    +import org.apache.nifi.util.Tuple;
    +
    +import java.io.IOException;
    +import java.nio.charset.Charset;
    +import java.nio.charset.StandardCharsets;
    +import java.util.ArrayList;
    +import java.util.Collection;
    +import java.util.Collections;
    +import java.util.HashMap;
    +import java.util.HashSet;
    +import java.util.Iterator;
    +import java.util.LinkedList;
    +import java.util.List;
    +import java.util.Map;
    +import java.util.Set;
    +import java.util.concurrent.atomic.AtomicReference;
    +import java.util.regex.Pattern;
    +
    +@InputRequirement(InputRequirement.Requirement.INPUT_REQUIRED)
    +@Tags({"hbase", "scan", "fetch", "get"})
    +@CapabilityDescription("Scans and fetches rows from an HBase table. This processor may be used to fetch rows from hbase table by specifying a range of rowkey values (start and/or end ),"
    +        + "by time range, by filter expression, or any combination of them. "
    +        + "Order of records can be controlled by a property Reversed"
    +        + "Number of rows retrieved by the processor can be limited.")
    +@WritesAttributes({
    +        @WritesAttribute(attribute = "hbase.table", description = "The name of the HBase table that the row was fetched from"),
    +        @WritesAttribute(attribute = "hbase.resultset", description = "A JSON document/s representing the row/s. This property is only written when a Destination of flowfile-attributes is selected."),
    +        @WritesAttribute(attribute = "mime.type", description = "Set to application/json when using a Destination of flowfile-content, not set or modified otherwise"),
    +        @WritesAttribute(attribute = "hbase.rows.count", description = "Number of rows in the content of given flow file"),
    +        @WritesAttribute(attribute = "scanhbase.results.found", description = "Indicates whether at least one row has been found in given hbase table with provided conditions. "
    +                + "Could be null (not present) if transfered to FAILURE")
    +})
    +public class ScanHBase extends AbstractProcessor {
    +    //enhanced regex for columns to allow "-" in column qualifier names
    +    static final Pattern COLUMNS_PATTERN = Pattern.compile("\\w+(:(\\w|-)+)?(?:,\\w+(:(\\w|-)+)?)*");
    +    static final byte[] nl = System.lineSeparator().getBytes();
    +
    +    static final PropertyDescriptor HBASE_CLIENT_SERVICE = new PropertyDescriptor.Builder()
    +            .displayName("HBase Client Service")
    +            .name("scanhbase-client-service")
    +            .description("Specifies the Controller Service to use for accessing HBase.")
    +            .required(true)
    +            .identifiesControllerService(HBaseClientService.class)
    +            .build();
    +
    +    static final PropertyDescriptor TABLE_NAME = new PropertyDescriptor.Builder()
    +            .displayName("Table Name")
    +            .name("scanhbase-table-name")
    +            .description("The name of the HBase Table to fetch from.")
    +            .required(true)
    +            .expressionLanguageSupported(true)
    +            .addValidator(StandardValidators.NON_EMPTY_VALIDATOR)
    +            .build();
    +
    +    static final PropertyDescriptor START_ROW = new PropertyDescriptor.Builder()
    +            .displayName("Start rowkey")
    +            .name("scanhbase-start-rowkey")
    +            .description("The rowkey to start scan from.")
    +            .required(false)
    +            .expressionLanguageSupported(true)
    +            .addValidator(StandardValidators.NON_EMPTY_VALIDATOR)
    +            .build();
    +
    +    static final PropertyDescriptor END_ROW = new PropertyDescriptor.Builder()
    +            .displayName("End rowkey")
    +            .name("scanhbase-end-rowkey")
    +            .description("The row key to end scan by.")
    +            .required(false)
    +            .expressionLanguageSupported(true)
    +            .addValidator(StandardValidators.NON_EMPTY_VALIDATOR)
    +            .build();
    +
    +    static final PropertyDescriptor TIME_RANGE_MIN = new PropertyDescriptor.Builder()
    +            .displayName("Time range min")
    +            .name("scanhbase-time-range-min")
    +            .description("Time range min value. Both min and max values for time range should be either blank or provided.")
    +            .required(false)
    +            .expressionLanguageSupported(true)
    +            .addValidator(StandardValidators.LONG_VALIDATOR)
    +            .build();
    +
    +    static final PropertyDescriptor TIME_RANGE_MAX = new PropertyDescriptor.Builder()
    +            .displayName("Time range max")
    +            .name("scanhbase-time-range-max")
    +            .description("Time range max value. Both min and max values for time range should be either blank or provided.")
    +            .required(false)
    +            .expressionLanguageSupported(true)
    +            .addValidator(StandardValidators.LONG_VALIDATOR)
    +            .build();
    +
    +    static final PropertyDescriptor LIMIT_ROWS = new PropertyDescriptor.Builder()
    +            .displayName("Limit rows")
    +            .name("scanhbase-limit")
    +            .description("Limit number of rows retrieved by scan.")
    +            .required(false)
    +            .expressionLanguageSupported(true)
    +            .addValidator(StandardValidators.INTEGER_VALIDATOR)
    +            .build();
    +
    +    static final PropertyDescriptor BULK_SIZE = new PropertyDescriptor.Builder()
    +            .displayName("Max rows per flow file")
    +            .name("scanhbase-bulk-size")
    +            .description("Limits number of rows in single flow file content. Set to 0 to avoid multiple flow files.")
    +            .required(false)
    +            .expressionLanguageSupported(true)
    +            .defaultValue("0")
    +            .addValidator(StandardValidators.INTEGER_VALIDATOR)
    +            .build();
    +
    +    static final PropertyDescriptor REVERSED_SCAN = new PropertyDescriptor.Builder()
    +            .displayName("Reversed order")
    +            .name("scanhbase-reversed-order")
    +            .description("Set whether this scan is a reversed one. This is false by default which means forward(normal) scan.")
    +            .expressionLanguageSupported(false)
    +            .allowableValues("true", "false")
    +            .required(false)
    +            .defaultValue("false")
    +            .addValidator(StandardValidators.BOOLEAN_VALIDATOR)
    +            .build();
    +
    +    static final PropertyDescriptor FILTER_EXPRESSION = new PropertyDescriptor.Builder()
    +            .displayName("Filter expression")
    +            .name("scanhbase-filter-expression")
    +            .description("An HBase filter expression that will be applied to the scan. This property can not be used when also using the Columns property. "
    +                    + "Example: \"ValueFilter( =, 'binaryprefix:commit' )\"")
    +            .required(false)
    +            .expressionLanguageSupported(true)
    +            .addValidator(StandardValidators.NON_EMPTY_VALIDATOR)
    +            .build();
    +
    +    static final PropertyDescriptor COLUMNS = new PropertyDescriptor.Builder()
    +            .displayName("Columns")
    +            .name("scanhbase-columns")
    +            .description("An optional comma-separated list of \"<colFamily>:<colQualifier>\" pairs to fetch. To return all columns " +
    +                    "for a given family, leave off the qualifier such as \"<colFamily1>,<colFamily2>\".")
    +            .required(false)
    +            .expressionLanguageSupported(true)
    +            .addValidator(StandardValidators.createRegexMatchingValidator(COLUMNS_PATTERN))
    +            .build();
    +
    +    static final AllowableValue JSON_FORMAT_FULL_ROW = new AllowableValue("full-row", "full-row",
    +            "Creates a JSON document with the format: {\"row\":<row-id>, \"cells\":[{\"fam\":<col-fam>, \"qual\":<col-val>, \"val\":<value>, \"ts\":<timestamp>}]}.");
    +    static final AllowableValue JSON_FORMAT_QUALIFIER_AND_VALUE = new AllowableValue("col-qual-and-val", "col-qual-and-val",
    +            "Creates a JSON document with the format: {\"<col-qual>\":\"<value>\", \"<col-qual>\":\"<value>\".");
    +
    +    static final PropertyDescriptor JSON_FORMAT = new PropertyDescriptor.Builder()
    +            .displayName("JSON Format")
    +            .name("scanhbase-json-format")
    +            .description("Specifies how to represent the HBase row as a JSON document.")
    +            .required(true)
    +            .allowableValues(JSON_FORMAT_FULL_ROW, JSON_FORMAT_QUALIFIER_AND_VALUE)
    +            .defaultValue(JSON_FORMAT_FULL_ROW.getValue())
    +            .build();
    +
    +    static final PropertyDescriptor DECODE_CHARSET = new PropertyDescriptor.Builder()
    +            .displayName("Decode Character Set")
    +            .name("scanhbase-decode-charset")
    +            .description("The character set used to decode data from HBase.")
    +            .required(true)
    +            .defaultValue("UTF-8")
    +            .addValidator(StandardValidators.CHARACTER_SET_VALIDATOR)
    +            .build();
    +
    +    static final PropertyDescriptor ENCODE_CHARSET = new PropertyDescriptor.Builder()
    +            .displayName("Encode Character Set")
    +            .name("scanhbase-encode-charset")
    +            .description("The character set used to encode the JSON representation of the row.")
    +            .required(true)
    +            .defaultValue("UTF-8")
    +            .addValidator(StandardValidators.CHARACTER_SET_VALIDATOR)
    +            .build();
    +
    +    public static final Relationship REL_ORIGINAL = new Relationship.Builder()
    +            .name("original")
    +            .description("The original input file will be routed to this destination, even if no rows are retrieved based on provided conditions.")
    +            .build();
    +
    +    static final Relationship REL_SUCCESS = new Relationship.Builder()
    +            .name("success")
    +            .description("All successful fetches are routed to this relationship.")
    +            .build();
    +    static final Relationship REL_FAILURE = new Relationship.Builder()
    +            .name("failure")
    +            .description("All failed fetches are routed to this relationship.")
    +            .build();
    +
    +    static final String HBASE_TABLE_ATTR = "hbase.table";
    +    static final String HBASE_ROWS_COUNT_ATTR = "hbase.rows.count";
    +
    +    static final List<PropertyDescriptor> properties;
    +    static {
    +        List<PropertyDescriptor> props = new ArrayList<>();
    +        props.add(HBASE_CLIENT_SERVICE);
    +        props.add(TABLE_NAME);
    +        props.add(START_ROW);
    +        props.add(END_ROW);
    +        props.add(TIME_RANGE_MIN);
    +        props.add(TIME_RANGE_MAX);
    +        props.add(LIMIT_ROWS);
    +        props.add(REVERSED_SCAN);
    +        props.add(BULK_SIZE);
    +        props.add(FILTER_EXPRESSION);
    +        props.add(COLUMNS);
    +        props.add(JSON_FORMAT);
    +        props.add(ENCODE_CHARSET);
    +        props.add(DECODE_CHARSET);
    +        properties = Collections.unmodifiableList(props);
    +    }
    +
    +    static final Set<Relationship> relationships;
    +    static {
    +        Set<Relationship> rels = new HashSet<>();
    +        rels.add(REL_SUCCESS);
    +        rels.add(REL_ORIGINAL);
    +        rels.add(REL_FAILURE);
    +        relationships = Collections.unmodifiableSet(rels);
    +    }
    +
    +    private volatile Charset decodeCharset;
    +    private volatile Charset encodeCharset;
    +    private RowSerializer serializer = null;
    +
    +    @OnScheduled
    +    public void onScheduled(ProcessContext context) {
    +        this.decodeCharset = Charset.forName(context.getProperty(DECODE_CHARSET).getValue());
    +        this.encodeCharset = Charset.forName(context.getProperty(ENCODE_CHARSET).getValue());
    +
    +        final String jsonFormat = context.getProperty(JSON_FORMAT).getValue();
    +        if (jsonFormat.equals(JSON_FORMAT_FULL_ROW.getValue())) {
    +            this.serializer = new JsonFullRowSerializer(decodeCharset, encodeCharset);
    +        } else {
    +            this.serializer = new JsonQualifierAndValueRowSerializer(decodeCharset, encodeCharset);
    +        }
    +    }
    +
    +    @Override
    +    protected List<PropertyDescriptor> getSupportedPropertyDescriptors() {
    +        return properties;
    +    }
    +
    +    @Override
    +    public Set<Relationship> getRelationships() {
    +        return relationships;
    +    }
    +
    +    @Override
    +    protected Collection<ValidationResult> customValidate(ValidationContext validationContext) {
    +
    +        final List<ValidationResult> problems = new ArrayList<>();
    +
    +        final String columns = validationContext.getProperty(COLUMNS).getValue();
    +        final String filter = validationContext.getProperty(FILTER_EXPRESSION).getValue();
    +
    +        if (!StringUtils.isBlank(columns) && !StringUtils.isBlank(filter)) {
    +            problems.add(new ValidationResult.Builder()
    +                    .subject(FILTER_EXPRESSION.getDisplayName())
    +                    .input(filter).valid(false)
    +                    .explanation("A filter expression can not be used in conjunction with the Columns property")
    +                    .build());
    +        }
    +
    +        return problems;
    +    }
    +
    +    @Override
    +    public void onTrigger(ProcessContext context, ProcessSession session) throws ProcessException {
    +        FlowFile flowFile = session.get();
    +        if (flowFile == null) {
    +            return;
    +        }
    +
    +        try{
    +            final String tableName = context.getProperty(TABLE_NAME).evaluateAttributeExpressions(flowFile).getValue();
    +            if (StringUtils.isBlank(tableName)) {
    +                getLogger().error("Table Name is blank or null for {}, transferring to failure", new Object[] {flowFile});
    +                session.transfer(session.penalize(flowFile), REL_FAILURE);
    +                return;
    +            }
    +
    +            final String startRow = context.getProperty(START_ROW).evaluateAttributeExpressions(flowFile).getValue();
    +            final String endRow = context.getProperty(END_ROW).evaluateAttributeExpressions(flowFile).getValue();
    +
    +            final String filterExpression = context.getProperty(FILTER_EXPRESSION).evaluateAttributeExpressions(flowFile).getValue();
    +
    +            //evaluate and validate time range min and max values. They both should be either empty or provided.
    +            Long timerangeMin = null;
    +            Long timerangeMax = null;
    +
    +            try{
    +                timerangeMin = context.getProperty(TIME_RANGE_MIN).evaluateAttributeExpressions(flowFile).asLong();
    +            }catch(Exception e){
    +                getLogger().error("Time range min value is not a number ({}) for {}, transferring to failure",
    +                        new Object[] {context.getProperty(TIME_RANGE_MIN).evaluateAttributeExpressions(flowFile).getValue(), flowFile});
    +                session.transfer(session.penalize(flowFile), REL_FAILURE);
    +                return;
    +            }
    +            try{
    +                timerangeMax = context.getProperty(TIME_RANGE_MAX).evaluateAttributeExpressions(flowFile).asLong();
    +            }catch(Exception e){
    +                getLogger().error("Time range max value is not a number ({}) for {}, transferring to failure",
    +                        new Object[] {context.getProperty(TIME_RANGE_MAX).evaluateAttributeExpressions(flowFile).getValue(), flowFile});
    +                session.transfer(session.penalize(flowFile), REL_FAILURE);
    +                return;
    +            }
    +            if (timerangeMin == null && timerangeMax != null) {
    +                getLogger().error("Time range min value cannot be blank when max value provided for {}, transferring to failure", new Object[] {flowFile});
    +                session.transfer(session.penalize(flowFile), REL_FAILURE);
    +                return;
    +            }else if (timerangeMin != null && timerangeMax == null) {
    +                getLogger().error("Time range max value cannot be blank when min value provided for {}, transferring to failure", new Object[] {flowFile});
    +                session.transfer(session.penalize(flowFile), REL_FAILURE);
    +                return;
    +            }
    +
    +            final Integer limitRows = context.getProperty(LIMIT_ROWS).evaluateAttributeExpressions(flowFile).asInteger();
    +
    +            final Boolean isReversed = context.getProperty(REVERSED_SCAN).asBoolean();
    +
    +            final Integer bulkSize = context.getProperty(BULK_SIZE).evaluateAttributeExpressions(flowFile).asInteger();
    --- End diff --
    
    limitRows handled: HBase_1_1_2_ClientService.scan line 443
    bulkSize missed :-O   (fixing)


---

[GitHub] nifi issue #2478: NIFI-4833 Add scanHBase Processor

Posted by bbende <gi...@git.apache.org>.
Github user bbende commented on the issue:

    https://github.com/apache/nifi/pull/2478
  
    @bdesert thanks for the updates, there is one error case I think we need to handle and then we should be good to go...
    
    The case is if an exception happens half-way through handling the results and gets caught in the try-catch on lines 385-389, we currently only transfer the original flow file to failure and return, but the handler may have a flow file it created and was writing results to, and this would need to be removed from the session.
    
    The reason this isn't caught in the JUnit tests is because currently MockHBaseClientService lets you set throwException which throws an exception right at the beginning of scan before the handler has ever been called. If you want to create a way to test this you could introduce a new boolean like throwExceptionAfterNumResults and also take in an integer number of results. 
    
    For quick testing I hacked a change into the MockHBaseClientService so that it throws an exception after the first result:
    
     ```
    @Override
        public void scan(String tableName, String startRow, String endRow, String filterExpression, Long timerangeMin,
                Long timerangeMax, Integer limitRows, Boolean isReversed, Collection<Column> columns, ResultHandler handler)
                throws IOException {
    //        if (throwException) {
    //            throw new IOException("exception");
    //        }
    
            // pass all the staged data to the handler
            int resultCount = 0;
            for (final Map.Entry<String,ResultCell[]> entry : results.entrySet()) {
                handler.handle(entry.getKey().getBytes(StandardCharsets.UTF_8), entry.getValue());
                resultCount++;
    
                if (resultCount > 0) {
                    throw new IOException("exception");
                }
            }
    
            // delegate to the handler
    
            numScans++;
        }
    ```
    Then updated the test case:
    ```
    @Test
        public void testScanWhenScanThrowsException() {
            //hBaseClientService.setThrowException(true);
    
            final Map<String, String> cells = new HashMap<>();
            cells.put("cq1", "val1");
            cells.put("cq2", "val2");
    
            final long ts1 = 123456789;
            hBaseClientService.addResult("row1", cells, ts1);
            hBaseClientService.addResult("row2", cells, ts1);
    
            runner.setProperty(ScanHBase.TABLE_NAME, "table1");
            runner.setProperty(ScanHBase.START_ROW, "row1");
            runner.setProperty(ScanHBase.END_ROW, "row1");
    
            runner.enqueue("trigger flow file");
            runner.run();
    
            runner.assertTransferCount(ScanHBase.REL_FAILURE, 1);
            runner.assertTransferCount(ScanHBase.REL_SUCCESS, 0);
            runner.assertTransferCount(ScanHBase.REL_ORIGINAL, 0);
    
            Assert.assertEquals(0, hBaseClientService.getNumScans());
        }
    ```


---

[GitHub] nifi pull request #2478: NIFI-4833 Add scanHBase Processor

Posted by MikeThomsen <gi...@git.apache.org>.
Github user MikeThomsen commented on a diff in the pull request:

    https://github.com/apache/nifi/pull/2478#discussion_r169622730
  
    --- Diff: nifi-nar-bundles/nifi-standard-services/nifi-hbase_1_1_2-client-service-bundle/nifi-hbase_1_1_2-client-service/src/main/java/org/apache/nifi/hbase/HBase_1_1_2_ClientService.java ---
    @@ -430,6 +430,78 @@ public void scan(final String tableName, final byte[] startRow, final byte[] end
             }
         }
     
    +    @Override
    +    public void scan(final String tableName, final String startRow, final String endRow, String filterExpression,
    +            final Long timerangeMin, final Long timerangeMax, final Integer limitRows, final Boolean isReversed,
    +            final Collection<Column> columns, final ResultHandler handler) throws IOException {
    +
    +        try (final Table table = connection.getTable(TableName.valueOf(tableName));
    +                final ResultScanner scanner = getResults(table, startRow, endRow, filterExpression, timerangeMin,
    +                        timerangeMax, limitRows, isReversed, columns)) {
    +
    +            int cnt = 0;
    +            final int lim = limitRows != null ? limitRows : 0;
    +            for (final Result result : scanner) {
    +
    +                if (lim > 0 && cnt++ > lim) break;
    +
    +                final byte[] rowKey = result.getRow();
    +                final Cell[] cells = result.rawCells();
    +
    +                if (cells == null) {
    +                    continue;
    +                }
    +
    +                // convert HBase cells to NiFi cells
    +                final ResultCell[] resultCells = new ResultCell[cells.length];
    +                for (int i = 0; i < cells.length; i++) {
    +                    final Cell cell = cells[i];
    +                    final ResultCell resultCell = getResultCell(cell);
    +                    resultCells[i] = resultCell;
    +                }
    +
    +                // delegate to the handler
    +                handler.handle(rowKey, resultCells);
    +            }
    +        }
    +
    +    }
    +
    +    //
    +    protected ResultScanner getResults(final Table table, final String startRow, final String endRow, final String filterExpression, final Long timerangeMin, final Long timerangeMax,
    +            final Integer limitRows, final Boolean isReversed, final Collection<Column> columns)  throws IOException {
    +        final Scan scan = new Scan();
    +        if (!StringUtils.isBlank(startRow)) scan.setStartRow(startRow.getBytes(StandardCharsets.UTF_8));
    +        if (!StringUtils.isBlank(endRow))   scan.setStopRow(   endRow.getBytes(StandardCharsets.UTF_8));
    +
    +
    +        Filter filter = null;
    +        if (columns != null) {
    +            for (Column col : columns) {
    +                if (col.getQualifier() == null) {
    +                    scan.addFamily(col.getFamily());
    +                } else {
    +                    scan.addColumn(col.getFamily(), col.getQualifier());
    +                }
    +            }
    +        }else if (!StringUtils.isBlank(filterExpression)) {
    +            ParseFilter parseFilter = new ParseFilter();
    +            filter = parseFilter.parseFilterString(filterExpression);
    +        }
    +        if (filter != null) scan.setFilter(filter);
    +
    +        if (timerangeMin != null && timerangeMax != null) scan.setTimeRange(timerangeMin, timerangeMax);
    --- End diff --
    
    Separate lines please.


---

[GitHub] nifi pull request #2478: NIFI-4833 Add scanHBase Processor

Posted by bdesert <gi...@git.apache.org>.
Github user bdesert commented on a diff in the pull request:

    https://github.com/apache/nifi/pull/2478#discussion_r169176478
  
    --- Diff: nifi-nar-bundles/nifi-hbase-bundle/nifi-hbase-processors/src/main/java/org/apache/nifi/hbase/ScanHBase.java ---
    @@ -0,0 +1,562 @@
    +/*
    + * Licensed to the Apache Software Foundation (ASF) under one or more
    + * contributor license agreements.  See the NOTICE file distributed with
    + * this work for additional information regarding copyright ownership.
    + * The ASF licenses this file to You under the Apache License, Version 2.0
    + * (the "License"); you may not use this file except in compliance with
    + * the License.  You may obtain a copy of the License at
    + *
    + *     http://www.apache.org/licenses/LICENSE-2.0
    + *
    + * Unless required by applicable law or agreed to in writing, software
    + * distributed under the License is distributed on an "AS IS" BASIS,
    + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    + * See the License for the specific language governing permissions and
    + * limitations under the License.
    + */
    +package org.apache.nifi.hbase;
    +
    +import org.apache.commons.lang3.StringUtils;
    +import org.apache.nifi.annotation.behavior.InputRequirement;
    +import org.apache.nifi.annotation.behavior.WritesAttribute;
    +import org.apache.nifi.annotation.behavior.WritesAttributes;
    +import org.apache.nifi.annotation.documentation.CapabilityDescription;
    +import org.apache.nifi.annotation.documentation.Tags;
    +import org.apache.nifi.annotation.lifecycle.OnScheduled;
    +import org.apache.nifi.components.AllowableValue;
    +import org.apache.nifi.components.PropertyDescriptor;
    +import org.apache.nifi.components.ValidationContext;
    +import org.apache.nifi.components.ValidationResult;
    +import org.apache.nifi.flowfile.FlowFile;
    +import org.apache.nifi.flowfile.attributes.CoreAttributes;
    +import org.apache.nifi.hbase.io.JsonFullRowSerializer;
    +import org.apache.nifi.hbase.io.JsonQualifierAndValueRowSerializer;
    +import org.apache.nifi.hbase.io.RowSerializer;
    +import org.apache.nifi.hbase.scan.Column;
    +import org.apache.nifi.hbase.scan.ResultCell;
    +import org.apache.nifi.hbase.scan.ResultHandler;
    +import org.apache.nifi.processor.AbstractProcessor;
    +import org.apache.nifi.processor.ProcessContext;
    +import org.apache.nifi.processor.ProcessSession;
    +import org.apache.nifi.processor.Relationship;
    +import org.apache.nifi.processor.exception.ProcessException;
    +import org.apache.nifi.processor.util.StandardValidators;
    +import org.apache.nifi.util.Tuple;
    +
    +import java.io.IOException;
    +import java.nio.charset.Charset;
    +import java.nio.charset.StandardCharsets;
    +import java.util.ArrayList;
    +import java.util.Collection;
    +import java.util.Collections;
    +import java.util.HashMap;
    +import java.util.HashSet;
    +import java.util.Iterator;
    +import java.util.LinkedList;
    +import java.util.List;
    +import java.util.Map;
    +import java.util.Set;
    +import java.util.concurrent.atomic.AtomicReference;
    +import java.util.regex.Pattern;
    +
    +@InputRequirement(InputRequirement.Requirement.INPUT_REQUIRED)
    +@Tags({"hbase", "scan", "fetch", "get"})
    +@CapabilityDescription("Scans and fetches rows from an HBase table. This processor may be used to fetch rows from hbase table by specifying a range of rowkey values (start and/or end ),"
    +        + "by time range, by filter expression, or any combination of them. \n"
    +        + "Order of records can be controlled by a property <code>Reversed</code>"
    +        + "Number of rows retrieved by the processor can be limited.")
    +@WritesAttributes({
    +        @WritesAttribute(attribute = "hbase.table", description = "The name of the HBase table that the row was fetched from"),
    +        @WritesAttribute(attribute = "hbase.resultset", description = "A JSON document/s representing the row/s. This property is only written when a Destination of flowfile-attributes is selected."),
    +        @WritesAttribute(attribute = "mime.type", description = "Set to application/json when using a Destination of flowfile-content, not set or modified otherwise"),
    +        @WritesAttribute(attribute = "hbase.rows.count", description = "Number of rows in the content of given flow file"),
    +        @WritesAttribute(attribute = "scanhbase.results.found", description = "Indicates whether at least one row has been found in given hbase table with provided conditions. <br/>"
    +                + "Could be null (not present) if transfered to FAILURE")
    +})
    +public class ScanHBase extends AbstractProcessor {
    +    //enhanced regex for columns to allow "-" in column qualifier names
    +    static final Pattern COLUMNS_PATTERN = Pattern.compile("\\w+(:(\\w|-)+)?(?:,\\w+(:(\\w|-)+)?)*");
    +    static final byte[] nl = System.lineSeparator().getBytes();
    +
    +    static final PropertyDescriptor HBASE_CLIENT_SERVICE = new PropertyDescriptor.Builder()
    +            .displayName("HBase Client Service")
    +            .name("scanhbase-client-service")
    +            .description("Specifies the Controller Service to use for accessing HBase.")
    +            .required(true)
    +            .identifiesControllerService(HBaseClientService.class)
    +            .build();
    +
    +    static final PropertyDescriptor TABLE_NAME = new PropertyDescriptor.Builder()
    +            .displayName("Table Name")
    +            .name("scanhbase-table-name")
    +            .description("The name of the HBase Table to fetch from.")
    +            .required(true)
    +            .expressionLanguageSupported(true)
    +            .addValidator(StandardValidators.NON_EMPTY_VALIDATOR)
    +            .build();
    +
    +    static final PropertyDescriptor START_ROW = new PropertyDescriptor.Builder()
    +            .displayName("Start rowkey")
    +            .name("scanhbase-start-rowkey")
    +            .description("The rowkey to start scan from.")
    +            .required(false)
    +            .expressionLanguageSupported(true)
    +            .addValidator(StandardValidators.NON_EMPTY_VALIDATOR)
    +            .build();
    +
    +    static final PropertyDescriptor END_ROW = new PropertyDescriptor.Builder()
    +            .displayName("End rowkey")
    +            .name("scanhbase-end-rowkey")
    +            .description("The row key to end scan by.")
    +            .required(false)
    +            .expressionLanguageSupported(true)
    +            .addValidator(StandardValidators.NON_EMPTY_VALIDATOR)
    +            .build();
    +
    +    static final PropertyDescriptor TIME_RANGE_MIN = new PropertyDescriptor.Builder()
    +            .displayName("Time range min")
    +            .name("scanhbase-time-range-min")
    +            .description("Time range min value. Both min and max values for time range should be either blank or provided.")
    +            .required(false)
    +            .expressionLanguageSupported(true)
    +            .addValidator(StandardValidators.LONG_VALIDATOR)
    +            .build();
    +
    +    static final PropertyDescriptor TIME_RANGE_MAX = new PropertyDescriptor.Builder()
    +            .displayName("Time range max")
    +            .name("scanhbase-time-range-max")
    +            .description("Time range max value. Both min and max values for time range should be either blank or provided.")
    +            .required(false)
    +            .expressionLanguageSupported(true)
    +            .addValidator(StandardValidators.LONG_VALIDATOR)
    +            .build();
    +
    +    static final PropertyDescriptor LIMIT_ROWS = new PropertyDescriptor.Builder()
    +            .displayName("Limit rows")
    +            .name("scanhbase-limit")
    +            .description("Limit number of rows retrieved by scan.")
    +            .required(false)
    +            .expressionLanguageSupported(true)
    +            .addValidator(StandardValidators.INTEGER_VALIDATOR)
    +            .build();
    +
    +    static final PropertyDescriptor BULK_SIZE = new PropertyDescriptor.Builder()
    +            .displayName("Max rows per flow file")
    +            .name("scanhbase-bulk-size")
    +            .description("Limits number of rows in single flow file content. Set to 0 to avoid multiple flow files.")
    +            .required(false)
    +            .expressionLanguageSupported(true)
    +            .defaultValue("0")
    +            .addValidator(StandardValidators.INTEGER_VALIDATOR)
    +            .build();
    +
    +    static final PropertyDescriptor REVERSED_SCAN = new PropertyDescriptor.Builder()
    +            .displayName("Reversed order")
    +            .name("scanhbase-reversed-order")
    +            .description("Set whether this scan is a reversed one. This is false by default which means forward(normal) scan.")
    +            .expressionLanguageSupported(false)
    +            .allowableValues("true", "false")
    +            .required(false)
    +            .defaultValue("false")
    +            .addValidator(StandardValidators.BOOLEAN_VALIDATOR)
    +            .build();
    +
    +    static final PropertyDescriptor FILTER_EXPRESSION = new PropertyDescriptor.Builder()
    +            .displayName("Filter expression")
    +            .name("scanhbase-filter-expression")
    +            .description("An HBase filter expression that will be applied to the scan. This property can not be used when also using the Columns property.<br/>"
    +                    + "Example: \"ValueFilter( =, 'binaryprefix:commit' )\"")
    +            .required(false)
    +            .expressionLanguageSupported(true)
    +            .addValidator(StandardValidators.NON_EMPTY_VALIDATOR)
    +            .build();
    +
    +    static final PropertyDescriptor COLUMNS = new PropertyDescriptor.Builder()
    +            .displayName("Columns")
    +            .name("scanhbase-columns")
    +            .description("An optional comma-separated list of \"<colFamily>:<colQualifier>\" pairs to fetch. To return all columns " +
    +                    "for a given family, leave off the qualifier such as \"<colFamily1>,<colFamily2>\".")
    +            .required(false)
    +            .expressionLanguageSupported(true)
    +            .addValidator(StandardValidators.createRegexMatchingValidator(COLUMNS_PATTERN))
    +            .build();
    +
    +    static final AllowableValue JSON_FORMAT_FULL_ROW = new AllowableValue("full-row", "full-row",
    +            "Creates a JSON document with the format: {\"row\":<row-id>, \"cells\":[{\"fam\":<col-fam>, \"qual\":<col-val>, \"val\":<value>, \"ts\":<timestamp>}]}.");
    +    static final AllowableValue JSON_FORMAT_QUALIFIER_AND_VALUE = new AllowableValue("col-qual-and-val", "col-qual-and-val",
    +            "Creates a JSON document with the format: {\"<col-qual>\":\"<value>\", \"<col-qual>\":\"<value>\".");
    +
    +    static final PropertyDescriptor JSON_FORMAT = new PropertyDescriptor.Builder()
    +            .displayName("JSON Format")
    +            .name("scanhbase-json-format")
    +            .description("Specifies how to represent the HBase row as a JSON document.")
    +            .required(true)
    +            .allowableValues(JSON_FORMAT_FULL_ROW, JSON_FORMAT_QUALIFIER_AND_VALUE)
    +            .defaultValue(JSON_FORMAT_FULL_ROW.getValue())
    +            .build();
    +
    +    static final PropertyDescriptor DECODE_CHARSET = new PropertyDescriptor.Builder()
    +            .displayName("Decode Character Set")
    +            .name("scanhbase-decode-charset")
    +            .description("The character set used to decode data from HBase.")
    +            .required(true)
    +            .defaultValue("UTF-8")
    +            .addValidator(StandardValidators.CHARACTER_SET_VALIDATOR)
    +            .build();
    +
    +    static final PropertyDescriptor ENCODE_CHARSET = new PropertyDescriptor.Builder()
    +            .displayName("Encode Character Set")
    +            .name("scanhbase-encode-charset")
    +            .description("The character set used to encode the JSON representation of the row.")
    +            .required(true)
    +            .defaultValue("UTF-8")
    +            .addValidator(StandardValidators.CHARACTER_SET_VALIDATOR)
    +            .build();
    +
    +    public static final Relationship REL_ORIGINAL = new Relationship.Builder()
    +            .name("original")
    +            .description("The original input file will be routed to this destination, even if no rows are retrieved based on provided conditions.")
    +            .build();
    +
    +    static final Relationship REL_SUCCESS = new Relationship.Builder()
    +            .name("success")
    +            .description("All successful fetches are routed to this relationship.")
    +            .build();
    +    static final Relationship REL_FAILURE = new Relationship.Builder()
    +            .name("failure")
    +            .description("All failed fetches are routed to this relationship.")
    +            .build();
    +
    +    static final String HBASE_TABLE_ATTR = "hbase.table";
    +    static final String HBASE_ROWS_COUNT_ATTR = "hbase.rows.count";
    +
    +    static final List<PropertyDescriptor> properties;
    +    static {
    +        List<PropertyDescriptor> props = new ArrayList<>();
    +        props.add(HBASE_CLIENT_SERVICE);
    +        props.add(TABLE_NAME);
    +        props.add(START_ROW);
    +        props.add(END_ROW);
    +        props.add(TIME_RANGE_MIN);
    +        props.add(TIME_RANGE_MAX);
    +        props.add(LIMIT_ROWS);
    +        props.add(REVERSED_SCAN);
    +        props.add(BULK_SIZE);
    +        props.add(FILTER_EXPRESSION);
    +        props.add(COLUMNS);
    +        props.add(JSON_FORMAT);
    +        props.add(ENCODE_CHARSET);
    +        props.add(DECODE_CHARSET);
    +        properties = Collections.unmodifiableList(props);
    +    }
    +
    +    static final Set<Relationship> relationships;
    +    static {
    +        Set<Relationship> rels = new HashSet<>();
    +        rels.add(REL_SUCCESS);
    +        rels.add(REL_ORIGINAL);
    +        rels.add(REL_FAILURE);
    +        relationships = Collections.unmodifiableSet(rels);
    +    }
    +
    +    private volatile Charset decodeCharset;
    +    private volatile Charset encodeCharset;
    +    private RowSerializer serializer = null;
    +
    +    @OnScheduled
    +    public void onScheduled(ProcessContext context) {
    +        this.decodeCharset = Charset.forName(context.getProperty(DECODE_CHARSET).getValue());
    +        this.encodeCharset = Charset.forName(context.getProperty(ENCODE_CHARSET).getValue());
    +
    +        final String jsonFormat = context.getProperty(JSON_FORMAT).getValue();
    +        if (jsonFormat.equals(JSON_FORMAT_FULL_ROW.getValue())) {
    +            this.serializer = new JsonFullRowSerializer(decodeCharset, encodeCharset);
    +        } else {
    +            this.serializer = new JsonQualifierAndValueRowSerializer(decodeCharset, encodeCharset);
    +        }
    +    }
    +
    +    @Override
    +    protected List<PropertyDescriptor> getSupportedPropertyDescriptors() {
    +        return properties;
    +    }
    +
    +    @Override
    +    public Set<Relationship> getRelationships() {
    +        return relationships;
    +    }
    +
    +    @Override
    +    protected Collection<ValidationResult> customValidate(ValidationContext validationContext) {
    +
    +        final List<ValidationResult> problems = new ArrayList<>();
    +
    +        final String columns = validationContext.getProperty(COLUMNS).getValue();
    +        final String filter = validationContext.getProperty(FILTER_EXPRESSION).getValue();
    +
    +        if (!StringUtils.isBlank(columns) && !StringUtils.isBlank(filter)) {
    +            problems.add(new ValidationResult.Builder()
    +                    .subject(FILTER_EXPRESSION.getDisplayName())
    +                    .input(filter).valid(false)
    +                    .explanation("A filter expression can not be used in conjunction with the Columns property")
    +                    .build());
    +        }
    +
    +        return problems;
    +    }
    +
    +    @Override
    +    public void onTrigger(ProcessContext context, ProcessSession session) throws ProcessException {
    +        FlowFile flowFile = session.get();
    +        if (flowFile == null) {
    +            return;
    +        }
    +
    +        try{
    +            final String tableName = context.getProperty(TABLE_NAME).evaluateAttributeExpressions(flowFile).getValue();
    +            if (StringUtils.isBlank(tableName)) {
    +                getLogger().error("Table Name is blank or null for {}, transferring to failure", new Object[] {flowFile});
    +                session.transfer(session.penalize(flowFile), REL_FAILURE);
    +                return;
    +            }
    +
    +            final String startRow = context.getProperty(START_ROW).evaluateAttributeExpressions(flowFile).getValue();
    +            final String endRow = context.getProperty(END_ROW).evaluateAttributeExpressions(flowFile).getValue();
    +
    +            final String filterExpression = context.getProperty(FILTER_EXPRESSION).evaluateAttributeExpressions(flowFile).getValue();
    +
    +            //evaluate and validate time range min and max values. They both should be either empty or provided.
    +            Long timerangeMin = null;
    +            Long timerangeMax = null;
    +
    +            try{
    +                timerangeMin = context.getProperty(TIME_RANGE_MIN).evaluateAttributeExpressions(flowFile).asLong();
    +            }catch(Exception e){
    +                getLogger().error("Time range min value is not a number ({}) for {}, transferring to failure",
    +                        new Object[] {context.getProperty(TIME_RANGE_MIN).evaluateAttributeExpressions(flowFile).getValue(), flowFile});
    +                session.transfer(session.penalize(flowFile), REL_FAILURE);
    +                return;
    +            }
    +            try{
    +                timerangeMax = context.getProperty(TIME_RANGE_MAX).evaluateAttributeExpressions(flowFile).asLong();
    +            }catch(Exception e){
    +                getLogger().error("Time range max value is not a number ({}) for {}, transferring to failure",
    +                        new Object[] {context.getProperty(TIME_RANGE_MAX).evaluateAttributeExpressions(flowFile).getValue(), flowFile});
    +                session.transfer(session.penalize(flowFile), REL_FAILURE);
    +                return;
    +            }
    +            if (timerangeMin == null && timerangeMax != null) {
    +                getLogger().error("Time range min value cannot be blank when max value provided for {}, transferring to failure", new Object[] {flowFile});
    +                session.transfer(session.penalize(flowFile), REL_FAILURE);
    +                return;
    +            }else if (timerangeMin != null && timerangeMax == null) {
    +                getLogger().error("Time range max value cannot be blank when min value provided for {}, transferring to failure", new Object[] {flowFile});
    +                session.transfer(session.penalize(flowFile), REL_FAILURE);
    +                return;
    +            }
    +
    +            final Integer limitRows = context.getProperty(LIMIT_ROWS).evaluateAttributeExpressions(flowFile).asInteger();
    +
    +            final Boolean isReversed = context.getProperty(REVERSED_SCAN).asBoolean();
    +
    +            final Integer bulkSize = context.getProperty(BULK_SIZE).evaluateAttributeExpressions(flowFile).asInteger();
    +
    +            final List<Column> columns = getColumns(context.getProperty(COLUMNS).evaluateAttributeExpressions(flowFile).getValue());
    +            final HBaseClientService hBaseClientService = context.getProperty(HBASE_CLIENT_SERVICE).asControllerService(HBaseClientService.class);
    +
    +            final AtomicReference<Long> rowsPulledHolder = new AtomicReference<>(0L);
    +            final AtomicReference<Long> ffCountHolder = new AtomicReference<>(0L);
    +            ScanHBaseResultHandler handler = new ScanHBaseResultHandler(context, session, flowFile, rowsPulledHolder, ffCountHolder, hBaseClientService, tableName, bulkSize);
    +
    +            try {
    +                hBaseClientService.scan(tableName,
    +                                        filterExpression,
    --- End diff --
    
    good catch. thanks.


---

[GitHub] nifi pull request #2478: NIFI-4833 Add scanHBase Processor

Posted by bdesert <gi...@git.apache.org>.
Github user bdesert commented on a diff in the pull request:

    https://github.com/apache/nifi/pull/2478#discussion_r169677516
  
    --- Diff: nifi-nar-bundles/nifi-hbase-bundle/nifi-hbase-processors/src/test/java/org/apache/nifi/hbase/TestScanHBase.java ---
    @@ -0,0 +1,375 @@
    +/*
    + * Licensed to the Apache Software Foundation (ASF) under one or more
    + * contributor license agreements.  See the NOTICE file distributed with
    + * this work for additional information regarding copyright ownership.
    + * The ASF licenses this file to You under the Apache License, Version 2.0
    + * (the "License"); you may not use this file except in compliance with
    + * the License.  You may obtain a copy of the License at
    + *
    + *     http://www.apache.org/licenses/LICENSE-2.0
    + *
    + * Unless required by applicable law or agreed to in writing, software
    + * distributed under the License is distributed on an "AS IS" BASIS,
    + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    + * See the License for the specific language governing permissions and
    + * limitations under the License.
    + */
    +package org.apache.nifi.hbase;
    +
    +import java.util.HashMap;
    +import java.util.List;
    +import java.util.Map;
    +
    +import org.apache.nifi.reporting.InitializationException;
    +import org.apache.nifi.util.MockFlowFile;
    +import org.apache.nifi.util.TestRunner;
    +import org.apache.nifi.util.TestRunners;
    +import org.junit.Assert;
    +import org.junit.Before;
    +import org.junit.Test;
    +
    +public class TestScanHBase {
    +
    +    private ScanHBase proc;
    +    private MockHBaseClientService hBaseClientService;
    +    private TestRunner runner;
    +
    +    @Before
    +    public void setup() throws InitializationException {
    +        proc = new ScanHBase();
    +        runner = TestRunners.newTestRunner(proc);
    +
    +        hBaseClientService = new MockHBaseClientService();
    +        runner.addControllerService("hbaseClient", hBaseClientService);
    +        runner.enableControllerService(hBaseClientService);
    +        runner.setProperty(ScanHBase.HBASE_CLIENT_SERVICE, "hbaseClient");
    +    }
    +
    +    @Test
    +    public void testColumnsValidation() {
    +        runner.setProperty(ScanHBase.TABLE_NAME, "table1");
    +        runner.setProperty(ScanHBase.START_ROW, "row1");
    +        runner.setProperty(ScanHBase.END_ROW, "row1");
    +        runner.assertValid();
    +
    +        runner.setProperty(ScanHBase.COLUMNS, "cf1:cq1");
    +        runner.assertValid();
    +
    +        runner.setProperty(ScanHBase.COLUMNS, "cf1");
    +        runner.assertValid();
    +
    +        runner.setProperty(ScanHBase.COLUMNS, "cf1:cq1,cf2:cq2,cf3:cq3");
    +        runner.assertValid();
    +
    +        runner.setProperty(ScanHBase.COLUMNS, "cf1,cf2:cq1,cf3");
    +        runner.assertValid();
    +
    +        runner.setProperty(ScanHBase.COLUMNS, "cf1 cf2,cf3");
    +        runner.assertNotValid();
    +
    +        runner.setProperty(ScanHBase.COLUMNS, "cf1:,cf2,cf3");
    +        runner.assertNotValid();
    +
    +        runner.setProperty(ScanHBase.COLUMNS, "cf1:cq1,");
    +        runner.assertNotValid();
    +    }
    +
    +    @Test
    +    public void testNoIncomingFlowFile() {
    +        runner.setProperty(ScanHBase.TABLE_NAME, "table1");
    +        runner.setProperty(ScanHBase.START_ROW, "row1");
    +        runner.setProperty(ScanHBase.END_ROW, "row1");
    +
    +        runner.run();
    +        runner.assertTransferCount(ScanHBase.REL_FAILURE, 0);
    +        runner.assertTransferCount(ScanHBase.REL_SUCCESS, 0);
    +        runner.assertTransferCount(ScanHBase.REL_ORIGINAL, 0);
    +
    +        Assert.assertEquals(0, hBaseClientService.getNumScans());
    +    }
    +
    +    @Test
    +    public void testInvalidTableName() {
    +        runner.setProperty(ScanHBase.TABLE_NAME, "${hbase.table}");
    --- End diff --
    
    Not setting a value for "hbase.table" is intentional. This test is for failure handling if expression is invalid (cannot be evaluated). You can see that FF expected at REL_FAILURE without scans. If I just didn't understand what you meant, please let me know.


---

[GitHub] nifi pull request #2478: NIFI-4833 Add scanHBase Processor

Posted by bbende <gi...@git.apache.org>.
Github user bbende commented on a diff in the pull request:

    https://github.com/apache/nifi/pull/2478#discussion_r170687174
  
    --- Diff: nifi-nar-bundles/nifi-hbase-bundle/nifi-hbase-processors/src/main/java/org/apache/nifi/hbase/ScanHBase.java ---
    @@ -0,0 +1,564 @@
    +/*
    + * Licensed to the Apache Software Foundation (ASF) under one or more
    + * contributor license agreements.  See the NOTICE file distributed with
    + * this work for additional information regarding copyright ownership.
    + * The ASF licenses this file to You under the Apache License, Version 2.0
    + * (the "License"); you may not use this file except in compliance with
    + * the License.  You may obtain a copy of the License at
    + *
    + *     http://www.apache.org/licenses/LICENSE-2.0
    + *
    + * Unless required by applicable law or agreed to in writing, software
    + * distributed under the License is distributed on an "AS IS" BASIS,
    + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    + * See the License for the specific language governing permissions and
    + * limitations under the License.
    + */
    +package org.apache.nifi.hbase;
    +
    +import org.apache.commons.lang3.StringUtils;
    +import org.apache.nifi.annotation.behavior.InputRequirement;
    +import org.apache.nifi.annotation.behavior.WritesAttribute;
    +import org.apache.nifi.annotation.behavior.WritesAttributes;
    +import org.apache.nifi.annotation.documentation.CapabilityDescription;
    +import org.apache.nifi.annotation.documentation.Tags;
    +import org.apache.nifi.annotation.lifecycle.OnScheduled;
    +import org.apache.nifi.components.AllowableValue;
    +import org.apache.nifi.components.PropertyDescriptor;
    +import org.apache.nifi.components.ValidationContext;
    +import org.apache.nifi.components.ValidationResult;
    +import org.apache.nifi.flowfile.FlowFile;
    +import org.apache.nifi.flowfile.attributes.CoreAttributes;
    +import org.apache.nifi.hbase.io.JsonFullRowSerializer;
    +import org.apache.nifi.hbase.io.JsonQualifierAndValueRowSerializer;
    +import org.apache.nifi.hbase.io.RowSerializer;
    +import org.apache.nifi.hbase.scan.Column;
    +import org.apache.nifi.hbase.scan.ResultCell;
    +import org.apache.nifi.hbase.scan.ResultHandler;
    +import org.apache.nifi.processor.AbstractProcessor;
    +import org.apache.nifi.processor.ProcessContext;
    +import org.apache.nifi.processor.ProcessSession;
    +import org.apache.nifi.processor.Relationship;
    +import org.apache.nifi.processor.exception.ProcessException;
    +import org.apache.nifi.processor.util.StandardValidators;
    +import org.apache.nifi.util.Tuple;
    +
    +import java.io.IOException;
    +import java.nio.charset.Charset;
    +import java.nio.charset.StandardCharsets;
    +import java.util.ArrayList;
    +import java.util.Collection;
    +import java.util.Collections;
    +import java.util.HashMap;
    +import java.util.HashSet;
    +import java.util.Iterator;
    +import java.util.LinkedList;
    +import java.util.List;
    +import java.util.Map;
    +import java.util.Set;
    +import java.util.concurrent.atomic.AtomicReference;
    +import java.util.regex.Pattern;
    +
    +@InputRequirement(InputRequirement.Requirement.INPUT_REQUIRED)
    +@Tags({"hbase", "scan", "fetch", "get"})
    +@CapabilityDescription("Scans and fetches rows from an HBase table. This processor may be used to fetch rows from hbase table by specifying a range of rowkey values (start and/or end ),"
    +        + "by time range, by filter expression, or any combination of them. "
    +        + "Order of records can be controlled by a property Reversed"
    +        + "Number of rows retrieved by the processor can be limited.")
    +@WritesAttributes({
    +        @WritesAttribute(attribute = "hbase.table", description = "The name of the HBase table that the row was fetched from"),
    +        @WritesAttribute(attribute = "hbase.resultset", description = "A JSON document/s representing the row/s. This property is only written when a Destination of flowfile-attributes is selected."),
    +        @WritesAttribute(attribute = "mime.type", description = "Set to application/json when using a Destination of flowfile-content, not set or modified otherwise"),
    +        @WritesAttribute(attribute = "hbase.rows.count", description = "Number of rows in the content of given flow file"),
    +        @WritesAttribute(attribute = "scanhbase.results.found", description = "Indicates whether at least one row has been found in given hbase table with provided conditions. "
    +                + "Could be null (not present) if transfered to FAILURE")
    +})
    +public class ScanHBase extends AbstractProcessor {
    +    //enhanced regex for columns to allow "-" in column qualifier names
    +    static final Pattern COLUMNS_PATTERN = Pattern.compile("\\w+(:(\\w|-)+)?(?:,\\w+(:(\\w|-)+)?)*");
    +    static final byte[] nl = System.lineSeparator().getBytes();
    +
    +    static final PropertyDescriptor HBASE_CLIENT_SERVICE = new PropertyDescriptor.Builder()
    +            .displayName("HBase Client Service")
    +            .name("scanhbase-client-service")
    +            .description("Specifies the Controller Service to use for accessing HBase.")
    +            .required(true)
    +            .identifiesControllerService(HBaseClientService.class)
    +            .build();
    +
    +    static final PropertyDescriptor TABLE_NAME = new PropertyDescriptor.Builder()
    +            .displayName("Table Name")
    +            .name("scanhbase-table-name")
    +            .description("The name of the HBase Table to fetch from.")
    +            .required(true)
    +            .expressionLanguageSupported(true)
    +            .addValidator(StandardValidators.NON_EMPTY_VALIDATOR)
    +            .build();
    +
    +    static final PropertyDescriptor START_ROW = new PropertyDescriptor.Builder()
    +            .displayName("Start rowkey")
    +            .name("scanhbase-start-rowkey")
    +            .description("The rowkey to start scan from.")
    +            .required(false)
    +            .expressionLanguageSupported(true)
    +            .addValidator(StandardValidators.NON_EMPTY_VALIDATOR)
    +            .build();
    +
    +    static final PropertyDescriptor END_ROW = new PropertyDescriptor.Builder()
    +            .displayName("End rowkey")
    +            .name("scanhbase-end-rowkey")
    +            .description("The row key to end scan by.")
    +            .required(false)
    +            .expressionLanguageSupported(true)
    +            .addValidator(StandardValidators.NON_EMPTY_VALIDATOR)
    +            .build();
    +
    +    static final PropertyDescriptor TIME_RANGE_MIN = new PropertyDescriptor.Builder()
    +            .displayName("Time range min")
    +            .name("scanhbase-time-range-min")
    +            .description("Time range min value. Both min and max values for time range should be either blank or provided.")
    +            .required(false)
    +            .expressionLanguageSupported(true)
    +            .addValidator(StandardValidators.LONG_VALIDATOR)
    +            .build();
    +
    +    static final PropertyDescriptor TIME_RANGE_MAX = new PropertyDescriptor.Builder()
    +            .displayName("Time range max")
    +            .name("scanhbase-time-range-max")
    +            .description("Time range max value. Both min and max values for time range should be either blank or provided.")
    +            .required(false)
    +            .expressionLanguageSupported(true)
    +            .addValidator(StandardValidators.LONG_VALIDATOR)
    +            .build();
    +
    +    static final PropertyDescriptor LIMIT_ROWS = new PropertyDescriptor.Builder()
    +            .displayName("Limit rows")
    +            .name("scanhbase-limit")
    +            .description("Limit number of rows retrieved by scan.")
    +            .required(false)
    +            .expressionLanguageSupported(true)
    +            .addValidator(StandardValidators.INTEGER_VALIDATOR)
    +            .build();
    +
    +    static final PropertyDescriptor BULK_SIZE = new PropertyDescriptor.Builder()
    +            .displayName("Max rows per flow file")
    +            .name("scanhbase-bulk-size")
    +            .description("Limits number of rows in single flow file content. Set to 0 to avoid multiple flow files.")
    +            .required(false)
    +            .expressionLanguageSupported(true)
    +            .defaultValue("0")
    +            .addValidator(StandardValidators.INTEGER_VALIDATOR)
    +            .build();
    +
    +    static final PropertyDescriptor REVERSED_SCAN = new PropertyDescriptor.Builder()
    +            .displayName("Reversed order")
    +            .name("scanhbase-reversed-order")
    +            .description("Set whether this scan is a reversed one. This is false by default which means forward(normal) scan.")
    +            .expressionLanguageSupported(false)
    +            .allowableValues("true", "false")
    +            .required(false)
    +            .defaultValue("false")
    +            .addValidator(StandardValidators.BOOLEAN_VALIDATOR)
    +            .build();
    +
    +    static final PropertyDescriptor FILTER_EXPRESSION = new PropertyDescriptor.Builder()
    +            .displayName("Filter expression")
    +            .name("scanhbase-filter-expression")
    +            .description("An HBase filter expression that will be applied to the scan. This property can not be used when also using the Columns property. "
    +                    + "Example: \"ValueFilter( =, 'binaryprefix:commit' )\"")
    +            .required(false)
    +            .expressionLanguageSupported(true)
    +            .addValidator(StandardValidators.NON_EMPTY_VALIDATOR)
    +            .build();
    +
    +    static final PropertyDescriptor COLUMNS = new PropertyDescriptor.Builder()
    +            .displayName("Columns")
    +            .name("scanhbase-columns")
    +            .description("An optional comma-separated list of \"<colFamily>:<colQualifier>\" pairs to fetch. To return all columns " +
    +                    "for a given family, leave off the qualifier such as \"<colFamily1>,<colFamily2>\".")
    +            .required(false)
    +            .expressionLanguageSupported(true)
    +            .addValidator(StandardValidators.createRegexMatchingValidator(COLUMNS_PATTERN))
    +            .build();
    +
    +    static final AllowableValue JSON_FORMAT_FULL_ROW = new AllowableValue("full-row", "full-row",
    +            "Creates a JSON document with the format: {\"row\":<row-id>, \"cells\":[{\"fam\":<col-fam>, \"qual\":<col-val>, \"val\":<value>, \"ts\":<timestamp>}]}.");
    +    static final AllowableValue JSON_FORMAT_QUALIFIER_AND_VALUE = new AllowableValue("col-qual-and-val", "col-qual-and-val",
    +            "Creates a JSON document with the format: {\"<col-qual>\":\"<value>\", \"<col-qual>\":\"<value>\".");
    +
    +    static final PropertyDescriptor JSON_FORMAT = new PropertyDescriptor.Builder()
    +            .displayName("JSON Format")
    +            .name("scanhbase-json-format")
    +            .description("Specifies how to represent the HBase row as a JSON document.")
    +            .required(true)
    +            .allowableValues(JSON_FORMAT_FULL_ROW, JSON_FORMAT_QUALIFIER_AND_VALUE)
    +            .defaultValue(JSON_FORMAT_FULL_ROW.getValue())
    +            .build();
    +
    +    static final PropertyDescriptor DECODE_CHARSET = new PropertyDescriptor.Builder()
    +            .displayName("Decode Character Set")
    +            .name("scanhbase-decode-charset")
    +            .description("The character set used to decode data from HBase.")
    +            .required(true)
    +            .defaultValue("UTF-8")
    +            .addValidator(StandardValidators.CHARACTER_SET_VALIDATOR)
    +            .build();
    +
    +    static final PropertyDescriptor ENCODE_CHARSET = new PropertyDescriptor.Builder()
    +            .displayName("Encode Character Set")
    +            .name("scanhbase-encode-charset")
    +            .description("The character set used to encode the JSON representation of the row.")
    +            .required(true)
    +            .defaultValue("UTF-8")
    +            .addValidator(StandardValidators.CHARACTER_SET_VALIDATOR)
    +            .build();
    +
    +    public static final Relationship REL_ORIGINAL = new Relationship.Builder()
    +            .name("original")
    +            .description("The original input file will be routed to this destination, even if no rows are retrieved based on provided conditions.")
    +            .build();
    +
    +    static final Relationship REL_SUCCESS = new Relationship.Builder()
    +            .name("success")
    +            .description("All successful fetches are routed to this relationship.")
    +            .build();
    +    static final Relationship REL_FAILURE = new Relationship.Builder()
    +            .name("failure")
    +            .description("All failed fetches are routed to this relationship.")
    +            .build();
    +
    +    static final String HBASE_TABLE_ATTR = "hbase.table";
    +    static final String HBASE_ROWS_COUNT_ATTR = "hbase.rows.count";
    +
    +    static final List<PropertyDescriptor> properties;
    +    static {
    +        List<PropertyDescriptor> props = new ArrayList<>();
    +        props.add(HBASE_CLIENT_SERVICE);
    +        props.add(TABLE_NAME);
    +        props.add(START_ROW);
    +        props.add(END_ROW);
    +        props.add(TIME_RANGE_MIN);
    +        props.add(TIME_RANGE_MAX);
    +        props.add(LIMIT_ROWS);
    +        props.add(REVERSED_SCAN);
    +        props.add(BULK_SIZE);
    +        props.add(FILTER_EXPRESSION);
    +        props.add(COLUMNS);
    +        props.add(JSON_FORMAT);
    +        props.add(ENCODE_CHARSET);
    +        props.add(DECODE_CHARSET);
    +        properties = Collections.unmodifiableList(props);
    +    }
    +
    +    static final Set<Relationship> relationships;
    +    static {
    +        Set<Relationship> rels = new HashSet<>();
    +        rels.add(REL_SUCCESS);
    +        rels.add(REL_ORIGINAL);
    +        rels.add(REL_FAILURE);
    +        relationships = Collections.unmodifiableSet(rels);
    +    }
    +
    +    private volatile Charset decodeCharset;
    +    private volatile Charset encodeCharset;
    +    private RowSerializer serializer = null;
    +
    +    @OnScheduled
    +    public void onScheduled(ProcessContext context) {
    +        this.decodeCharset = Charset.forName(context.getProperty(DECODE_CHARSET).getValue());
    +        this.encodeCharset = Charset.forName(context.getProperty(ENCODE_CHARSET).getValue());
    +
    +        final String jsonFormat = context.getProperty(JSON_FORMAT).getValue();
    +        if (jsonFormat.equals(JSON_FORMAT_FULL_ROW.getValue())) {
    +            this.serializer = new JsonFullRowSerializer(decodeCharset, encodeCharset);
    +        } else {
    +            this.serializer = new JsonQualifierAndValueRowSerializer(decodeCharset, encodeCharset);
    +        }
    +    }
    +
    +    @Override
    +    protected List<PropertyDescriptor> getSupportedPropertyDescriptors() {
    +        return properties;
    +    }
    +
    +    @Override
    +    public Set<Relationship> getRelationships() {
    +        return relationships;
    +    }
    +
    +    @Override
    +    protected Collection<ValidationResult> customValidate(ValidationContext validationContext) {
    +
    +        final List<ValidationResult> problems = new ArrayList<>();
    +
    +        final String columns = validationContext.getProperty(COLUMNS).getValue();
    +        final String filter = validationContext.getProperty(FILTER_EXPRESSION).getValue();
    +
    +        if (!StringUtils.isBlank(columns) && !StringUtils.isBlank(filter)) {
    +            problems.add(new ValidationResult.Builder()
    +                    .subject(FILTER_EXPRESSION.getDisplayName())
    +                    .input(filter).valid(false)
    +                    .explanation("A filter expression can not be used in conjunction with the Columns property")
    +                    .build());
    +        }
    +
    +        return problems;
    +    }
    +
    +    @Override
    +    public void onTrigger(ProcessContext context, ProcessSession session) throws ProcessException {
    +        FlowFile flowFile = session.get();
    +        if (flowFile == null) {
    +            return;
    +        }
    +
    +        try{
    +            final String tableName = context.getProperty(TABLE_NAME).evaluateAttributeExpressions(flowFile).getValue();
    +            if (StringUtils.isBlank(tableName)) {
    +                getLogger().error("Table Name is blank or null for {}, transferring to failure", new Object[] {flowFile});
    +                session.transfer(session.penalize(flowFile), REL_FAILURE);
    +                return;
    +            }
    +
    +            final String startRow = context.getProperty(START_ROW).evaluateAttributeExpressions(flowFile).getValue();
    +            final String endRow = context.getProperty(END_ROW).evaluateAttributeExpressions(flowFile).getValue();
    +
    +            final String filterExpression = context.getProperty(FILTER_EXPRESSION).evaluateAttributeExpressions(flowFile).getValue();
    +
    +            //evaluate and validate time range min and max values. They both should be either empty or provided.
    +            Long timerangeMin = null;
    +            Long timerangeMax = null;
    +
    +            try{
    +                timerangeMin = context.getProperty(TIME_RANGE_MIN).evaluateAttributeExpressions(flowFile).asLong();
    +            }catch(Exception e){
    +                getLogger().error("Time range min value is not a number ({}) for {}, transferring to failure",
    +                        new Object[] {context.getProperty(TIME_RANGE_MIN).evaluateAttributeExpressions(flowFile).getValue(), flowFile});
    +                session.transfer(session.penalize(flowFile), REL_FAILURE);
    +                return;
    +            }
    +            try{
    +                timerangeMax = context.getProperty(TIME_RANGE_MAX).evaluateAttributeExpressions(flowFile).asLong();
    +            }catch(Exception e){
    +                getLogger().error("Time range max value is not a number ({}) for {}, transferring to failure",
    +                        new Object[] {context.getProperty(TIME_RANGE_MAX).evaluateAttributeExpressions(flowFile).getValue(), flowFile});
    +                session.transfer(session.penalize(flowFile), REL_FAILURE);
    +                return;
    +            }
    +            if (timerangeMin == null && timerangeMax != null) {
    +                getLogger().error("Time range min value cannot be blank when max value provided for {}, transferring to failure", new Object[] {flowFile});
    +                session.transfer(session.penalize(flowFile), REL_FAILURE);
    +                return;
    +            }else if (timerangeMin != null && timerangeMax == null) {
    +                getLogger().error("Time range max value cannot be blank when min value provided for {}, transferring to failure", new Object[] {flowFile});
    +                session.transfer(session.penalize(flowFile), REL_FAILURE);
    +                return;
    +            }
    +
    +            final Integer limitRows = context.getProperty(LIMIT_ROWS).evaluateAttributeExpressions(flowFile).asInteger();
    +
    +            final Boolean isReversed = context.getProperty(REVERSED_SCAN).asBoolean();
    +
    +            final Integer bulkSize = context.getProperty(BULK_SIZE).evaluateAttributeExpressions(flowFile).asInteger();
    +
    +            final List<Column> columns = getColumns(context.getProperty(COLUMNS).evaluateAttributeExpressions(flowFile).getValue());
    +            final HBaseClientService hBaseClientService = context.getProperty(HBASE_CLIENT_SERVICE).asControllerService(HBaseClientService.class);
    +
    +            final AtomicReference<Long> rowsPulledHolder = new AtomicReference<>(0L);
    +            final AtomicReference<Long> ffCountHolder = new AtomicReference<>(0L);
    +            ScanHBaseResultHandler handler = new ScanHBaseResultHandler(context, session, flowFile, rowsPulledHolder, ffCountHolder, hBaseClientService, tableName, bulkSize);
    +
    +            try {
    +                hBaseClientService.scan(tableName,
    +                                        startRow, endRow,
    +                                        filterExpression,
    +                                        timerangeMin, timerangeMax,
    +                                        limitRows,
    +                                        isReversed,
    +                                        columns,
    +                                        handler);
    +            } catch (IOException e) {
    +                getLogger().error("Unable to fetch rows from HBase table {} due to {}", new Object[] {tableName, e});
    +                flowFile = session.putAttribute(flowFile, "scanhbase.results.found", Boolean.toString(handler.isHandledAny()));
    +                session.transfer(flowFile, REL_FAILURE);
    +                return;
    +            }
    +
    +            LinkedList<Tuple<byte[], ResultCell[]>> hangingRows = handler.getHangingRows();
    +            if (!handler.isHandledAny() ||                                                         // no rows found in hbase
    +                    (handler.isHandledAny() && (hangingRows == null || hangingRows.isEmpty()))     // all the rows are flushed to FF inside handlers
    +                ){
    +                flowFile = session.putAttribute(flowFile, "scanhbase.results.found", Boolean.toString(handler.isHandledAny()));
    +                session.transfer(flowFile, REL_ORIGINAL);
    +                session.commit();
    +                return;
    +            }
    +
    +            if (hangingRows != null && !hangingRows.isEmpty()) {
    +                FlowFile lastFF = session.create(flowFile);
    +                final Map<String, String> attributes = new HashMap<>();
    +                attributes.put(HBASE_TABLE_ATTR, tableName);
    +                attributes.put(HBASE_ROWS_COUNT_ATTR, Long.toString(rowsPulledHolder.get()));
    +                attributes.put(CoreAttributes.MIME_TYPE.key(), "application/json");
    +                attributes.put(HBASE_ROWS_COUNT_ATTR, Long.toString(hangingRows.size()));
    +                lastFF = session.putAllAttributes(lastFF, attributes);
    +
    +                final AtomicReference<IOException> ioe = new AtomicReference<>(null);
    +                lastFF = session.write(lastFF, (out) -> {
    +                    for (Iterator<Tuple<byte[], ResultCell[]>> iter = hangingRows.iterator(); iter.hasNext();){
    +                        Tuple<byte[], ResultCell[]> r = iter.next();
    +                        serializer.serialize(r.getKey(), r.getValue(), out);
    +                        if (iter.hasNext()){
    +                            out.write(nl);
    +                        }
    +                    }
    +                });
    +
    +                Relationship rel = REL_SUCCESS;
    +                IOException error = ioe.get();
    +                if (error != null){
    +                    lastFF = session.putAttribute(lastFF, "scanhbase.error", error.toString());
    +                    rel = REL_FAILURE;
    +                }
    +                session.transfer(lastFF, rel);
    +                flowFile = session.putAttribute(flowFile, "scanhbase.results.found", Boolean.toString(handler.isHandledAny()));
    +                session.transfer(flowFile, REL_ORIGINAL);
    --- End diff --
    
    Should transferring to original (and the putAttribute before it) be done outside the "if hanging rows" check? 
    
    I was thinking you always want to transfer the original.


---

[GitHub] nifi pull request #2478: NIFI-4833 Add scanHBase Processor

Posted by MikeThomsen <gi...@git.apache.org>.
Github user MikeThomsen commented on a diff in the pull request:

    https://github.com/apache/nifi/pull/2478#discussion_r169622554
  
    --- Diff: nifi-nar-bundles/nifi-standard-services/nifi-hbase_1_1_2-client-service-bundle/nifi-hbase_1_1_2-client-service/src/main/java/org/apache/nifi/hbase/HBase_1_1_2_ClientService.java ---
    @@ -430,6 +430,78 @@ public void scan(final String tableName, final byte[] startRow, final byte[] end
             }
         }
     
    +    @Override
    +    public void scan(final String tableName, final String startRow, final String endRow, String filterExpression,
    +            final Long timerangeMin, final Long timerangeMax, final Integer limitRows, final Boolean isReversed,
    +            final Collection<Column> columns, final ResultHandler handler) throws IOException {
    +
    +        try (final Table table = connection.getTable(TableName.valueOf(tableName));
    +                final ResultScanner scanner = getResults(table, startRow, endRow, filterExpression, timerangeMin,
    +                        timerangeMax, limitRows, isReversed, columns)) {
    +
    +            int cnt = 0;
    +            final int lim = limitRows != null ? limitRows : 0;
    +            for (final Result result : scanner) {
    +
    +                if (lim > 0 && cnt++ > lim) break;
    +
    +                final byte[] rowKey = result.getRow();
    +                final Cell[] cells = result.rawCells();
    +
    +                if (cells == null) {
    +                    continue;
    +                }
    +
    +                // convert HBase cells to NiFi cells
    +                final ResultCell[] resultCells = new ResultCell[cells.length];
    +                for (int i = 0; i < cells.length; i++) {
    +                    final Cell cell = cells[i];
    +                    final ResultCell resultCell = getResultCell(cell);
    +                    resultCells[i] = resultCell;
    +                }
    +
    +                // delegate to the handler
    +                handler.handle(rowKey, resultCells);
    +            }
    +        }
    +
    +    }
    +
    +    //
    +    protected ResultScanner getResults(final Table table, final String startRow, final String endRow, final String filterExpression, final Long timerangeMin, final Long timerangeMax,
    +            final Integer limitRows, final Boolean isReversed, final Collection<Column> columns)  throws IOException {
    +        final Scan scan = new Scan();
    +        if (!StringUtils.isBlank(startRow)) scan.setStartRow(startRow.getBytes(StandardCharsets.UTF_8));
    --- End diff --
    
    This should be on separate lines like this:
    ```
    if (!StringUtils.isBlank(startRow)) { 
        scan.setStartRow(startRow.getBytes(StandardCharsets.UTF_8));
    }
    ```


---

[GitHub] nifi pull request #2478: NIFI-4833 Add scanHBase Processor

Posted by MikeThomsen <gi...@git.apache.org>.
Github user MikeThomsen commented on a diff in the pull request:

    https://github.com/apache/nifi/pull/2478#discussion_r169622786
  
    --- Diff: nifi-nar-bundles/nifi-standard-services/nifi-hbase_1_1_2-client-service-bundle/nifi-hbase_1_1_2-client-service/src/main/java/org/apache/nifi/hbase/HBase_1_1_2_ClientService.java ---
    @@ -430,6 +430,78 @@ public void scan(final String tableName, final byte[] startRow, final byte[] end
             }
         }
     
    +    @Override
    +    public void scan(final String tableName, final String startRow, final String endRow, String filterExpression,
    +            final Long timerangeMin, final Long timerangeMax, final Integer limitRows, final Boolean isReversed,
    +            final Collection<Column> columns, final ResultHandler handler) throws IOException {
    +
    +        try (final Table table = connection.getTable(TableName.valueOf(tableName));
    +                final ResultScanner scanner = getResults(table, startRow, endRow, filterExpression, timerangeMin,
    +                        timerangeMax, limitRows, isReversed, columns)) {
    +
    +            int cnt = 0;
    +            final int lim = limitRows != null ? limitRows : 0;
    +            for (final Result result : scanner) {
    +
    +                if (lim > 0 && cnt++ > lim) break;
    +
    +                final byte[] rowKey = result.getRow();
    +                final Cell[] cells = result.rawCells();
    +
    +                if (cells == null) {
    +                    continue;
    +                }
    +
    +                // convert HBase cells to NiFi cells
    +                final ResultCell[] resultCells = new ResultCell[cells.length];
    +                for (int i = 0; i < cells.length; i++) {
    +                    final Cell cell = cells[i];
    +                    final ResultCell resultCell = getResultCell(cell);
    +                    resultCells[i] = resultCell;
    +                }
    +
    +                // delegate to the handler
    +                handler.handle(rowKey, resultCells);
    +            }
    +        }
    +
    +    }
    +
    +    //
    +    protected ResultScanner getResults(final Table table, final String startRow, final String endRow, final String filterExpression, final Long timerangeMin, final Long timerangeMax,
    +            final Integer limitRows, final Boolean isReversed, final Collection<Column> columns)  throws IOException {
    +        final Scan scan = new Scan();
    +        if (!StringUtils.isBlank(startRow)) scan.setStartRow(startRow.getBytes(StandardCharsets.UTF_8));
    +        if (!StringUtils.isBlank(endRow))   scan.setStopRow(   endRow.getBytes(StandardCharsets.UTF_8));
    +
    +
    +        Filter filter = null;
    +        if (columns != null) {
    +            for (Column col : columns) {
    +                if (col.getQualifier() == null) {
    +                    scan.addFamily(col.getFamily());
    +                } else {
    +                    scan.addColumn(col.getFamily(), col.getQualifier());
    +                }
    +            }
    +        }else if (!StringUtils.isBlank(filterExpression)) {
    +            ParseFilter parseFilter = new ParseFilter();
    +            filter = parseFilter.parseFilterString(filterExpression);
    +        }
    +        if (filter != null) scan.setFilter(filter);
    --- End diff --
    
    Separate lines with curly brackets.


---

[GitHub] nifi pull request #2478: NIFI-4833 Add scanHBase Processor

Posted by MikeThomsen <gi...@git.apache.org>.
Github user MikeThomsen commented on a diff in the pull request:

    https://github.com/apache/nifi/pull/2478#discussion_r169624523
  
    --- Diff: nifi-nar-bundles/nifi-hbase-bundle/nifi-hbase-processors/src/main/java/org/apache/nifi/hbase/ScanHBase.java ---
    @@ -0,0 +1,562 @@
    +/*
    + * Licensed to the Apache Software Foundation (ASF) under one or more
    + * contributor license agreements.  See the NOTICE file distributed with
    + * this work for additional information regarding copyright ownership.
    + * The ASF licenses this file to You under the Apache License, Version 2.0
    + * (the "License"); you may not use this file except in compliance with
    + * the License.  You may obtain a copy of the License at
    + *
    + *     http://www.apache.org/licenses/LICENSE-2.0
    + *
    + * Unless required by applicable law or agreed to in writing, software
    + * distributed under the License is distributed on an "AS IS" BASIS,
    + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    + * See the License for the specific language governing permissions and
    + * limitations under the License.
    + */
    +package org.apache.nifi.hbase;
    +
    +import org.apache.commons.lang3.StringUtils;
    +import org.apache.nifi.annotation.behavior.InputRequirement;
    +import org.apache.nifi.annotation.behavior.WritesAttribute;
    +import org.apache.nifi.annotation.behavior.WritesAttributes;
    +import org.apache.nifi.annotation.documentation.CapabilityDescription;
    +import org.apache.nifi.annotation.documentation.Tags;
    +import org.apache.nifi.annotation.lifecycle.OnScheduled;
    +import org.apache.nifi.components.AllowableValue;
    +import org.apache.nifi.components.PropertyDescriptor;
    +import org.apache.nifi.components.ValidationContext;
    +import org.apache.nifi.components.ValidationResult;
    +import org.apache.nifi.flowfile.FlowFile;
    +import org.apache.nifi.flowfile.attributes.CoreAttributes;
    +import org.apache.nifi.hbase.io.JsonFullRowSerializer;
    +import org.apache.nifi.hbase.io.JsonQualifierAndValueRowSerializer;
    +import org.apache.nifi.hbase.io.RowSerializer;
    +import org.apache.nifi.hbase.scan.Column;
    +import org.apache.nifi.hbase.scan.ResultCell;
    +import org.apache.nifi.hbase.scan.ResultHandler;
    +import org.apache.nifi.processor.AbstractProcessor;
    +import org.apache.nifi.processor.ProcessContext;
    +import org.apache.nifi.processor.ProcessSession;
    +import org.apache.nifi.processor.Relationship;
    +import org.apache.nifi.processor.exception.ProcessException;
    +import org.apache.nifi.processor.util.StandardValidators;
    +import org.apache.nifi.util.Tuple;
    +
    +import java.io.IOException;
    +import java.nio.charset.Charset;
    +import java.nio.charset.StandardCharsets;
    +import java.util.ArrayList;
    +import java.util.Collection;
    +import java.util.Collections;
    +import java.util.HashMap;
    +import java.util.HashSet;
    +import java.util.Iterator;
    +import java.util.LinkedList;
    +import java.util.List;
    +import java.util.Map;
    +import java.util.Set;
    +import java.util.concurrent.atomic.AtomicReference;
    +import java.util.regex.Pattern;
    +
    +@InputRequirement(InputRequirement.Requirement.INPUT_REQUIRED)
    +@Tags({"hbase", "scan", "fetch", "get"})
    +@CapabilityDescription("Scans and fetches rows from an HBase table. This processor may be used to fetch rows from hbase table by specifying a range of rowkey values (start and/or end ),"
    +        + "by time range, by filter expression, or any combination of them. \n"
    +        + "Order of records can be controlled by a property <code>Reversed</code>"
    +        + "Number of rows retrieved by the processor can be limited.")
    +@WritesAttributes({
    +        @WritesAttribute(attribute = "hbase.table", description = "The name of the HBase table that the row was fetched from"),
    +        @WritesAttribute(attribute = "hbase.resultset", description = "A JSON document/s representing the row/s. This property is only written when a Destination of flowfile-attributes is selected."),
    +        @WritesAttribute(attribute = "mime.type", description = "Set to application/json when using a Destination of flowfile-content, not set or modified otherwise"),
    +        @WritesAttribute(attribute = "hbase.rows.count", description = "Number of rows in the content of given flow file"),
    +        @WritesAttribute(attribute = "scanhbase.results.found", description = "Indicates whether at least one row has been found in given hbase table with provided conditions. <br/>"
    +                + "Could be null (not present) if transfered to FAILURE")
    +})
    +public class ScanHBase extends AbstractProcessor {
    +    //enhanced regex for columns to allow "-" in column qualifier names
    +    static final Pattern COLUMNS_PATTERN = Pattern.compile("\\w+(:(\\w|-)+)?(?:,\\w+(:(\\w|-)+)?)*");
    +    static final byte[] nl = System.lineSeparator().getBytes();
    +
    +    static final PropertyDescriptor HBASE_CLIENT_SERVICE = new PropertyDescriptor.Builder()
    +            .displayName("HBase Client Service")
    +            .name("scanhbase-client-service")
    +            .description("Specifies the Controller Service to use for accessing HBase.")
    +            .required(true)
    +            .identifiesControllerService(HBaseClientService.class)
    +            .build();
    +
    +    static final PropertyDescriptor TABLE_NAME = new PropertyDescriptor.Builder()
    +            .displayName("Table Name")
    +            .name("scanhbase-table-name")
    +            .description("The name of the HBase Table to fetch from.")
    +            .required(true)
    +            .expressionLanguageSupported(true)
    +            .addValidator(StandardValidators.NON_EMPTY_VALIDATOR)
    +            .build();
    +
    +    static final PropertyDescriptor START_ROW = new PropertyDescriptor.Builder()
    +            .displayName("Start rowkey")
    +            .name("scanhbase-start-rowkey")
    +            .description("The rowkey to start scan from.")
    +            .required(false)
    +            .expressionLanguageSupported(true)
    +            .addValidator(StandardValidators.NON_EMPTY_VALIDATOR)
    +            .build();
    +
    +    static final PropertyDescriptor END_ROW = new PropertyDescriptor.Builder()
    +            .displayName("End rowkey")
    +            .name("scanhbase-end-rowkey")
    +            .description("The row key to end scan by.")
    +            .required(false)
    +            .expressionLanguageSupported(true)
    +            .addValidator(StandardValidators.NON_EMPTY_VALIDATOR)
    +            .build();
    +
    +    static final PropertyDescriptor TIME_RANGE_MIN = new PropertyDescriptor.Builder()
    +            .displayName("Time range min")
    +            .name("scanhbase-time-range-min")
    +            .description("Time range min value. Both min and max values for time range should be either blank or provided.")
    +            .required(false)
    +            .expressionLanguageSupported(true)
    +            .addValidator(StandardValidators.LONG_VALIDATOR)
    +            .build();
    +
    +    static final PropertyDescriptor TIME_RANGE_MAX = new PropertyDescriptor.Builder()
    +            .displayName("Time range max")
    +            .name("scanhbase-time-range-max")
    +            .description("Time range max value. Both min and max values for time range should be either blank or provided.")
    +            .required(false)
    +            .expressionLanguageSupported(true)
    +            .addValidator(StandardValidators.LONG_VALIDATOR)
    +            .build();
    +
    +    static final PropertyDescriptor LIMIT_ROWS = new PropertyDescriptor.Builder()
    +            .displayName("Limit rows")
    +            .name("scanhbase-limit")
    +            .description("Limit number of rows retrieved by scan.")
    +            .required(false)
    +            .expressionLanguageSupported(true)
    +            .addValidator(StandardValidators.INTEGER_VALIDATOR)
    +            .build();
    +
    +    static final PropertyDescriptor BULK_SIZE = new PropertyDescriptor.Builder()
    +            .displayName("Max rows per flow file")
    +            .name("scanhbase-bulk-size")
    +            .description("Limits number of rows in single flow file content. Set to 0 to avoid multiple flow files.")
    +            .required(false)
    +            .expressionLanguageSupported(true)
    +            .defaultValue("0")
    +            .addValidator(StandardValidators.INTEGER_VALIDATOR)
    +            .build();
    +
    +    static final PropertyDescriptor REVERSED_SCAN = new PropertyDescriptor.Builder()
    +            .displayName("Reversed order")
    +            .name("scanhbase-reversed-order")
    +            .description("Set whether this scan is a reversed one. This is false by default which means forward(normal) scan.")
    +            .expressionLanguageSupported(false)
    +            .allowableValues("true", "false")
    +            .required(false)
    +            .defaultValue("false")
    +            .addValidator(StandardValidators.BOOLEAN_VALIDATOR)
    +            .build();
    +
    +    static final PropertyDescriptor FILTER_EXPRESSION = new PropertyDescriptor.Builder()
    +            .displayName("Filter expression")
    +            .name("scanhbase-filter-expression")
    +            .description("An HBase filter expression that will be applied to the scan. This property can not be used when also using the Columns property.<br/>"
    +                    + "Example: \"ValueFilter( =, 'binaryprefix:commit' )\"")
    +            .required(false)
    +            .expressionLanguageSupported(true)
    +            .addValidator(StandardValidators.NON_EMPTY_VALIDATOR)
    +            .build();
    +
    +    static final PropertyDescriptor COLUMNS = new PropertyDescriptor.Builder()
    +            .displayName("Columns")
    +            .name("scanhbase-columns")
    +            .description("An optional comma-separated list of \"<colFamily>:<colQualifier>\" pairs to fetch. To return all columns " +
    +                    "for a given family, leave off the qualifier such as \"<colFamily1>,<colFamily2>\".")
    +            .required(false)
    +            .expressionLanguageSupported(true)
    +            .addValidator(StandardValidators.createRegexMatchingValidator(COLUMNS_PATTERN))
    +            .build();
    +
    +    static final AllowableValue JSON_FORMAT_FULL_ROW = new AllowableValue("full-row", "full-row",
    +            "Creates a JSON document with the format: {\"row\":<row-id>, \"cells\":[{\"fam\":<col-fam>, \"qual\":<col-val>, \"val\":<value>, \"ts\":<timestamp>}]}.");
    +    static final AllowableValue JSON_FORMAT_QUALIFIER_AND_VALUE = new AllowableValue("col-qual-and-val", "col-qual-and-val",
    +            "Creates a JSON document with the format: {\"<col-qual>\":\"<value>\", \"<col-qual>\":\"<value>\".");
    +
    +    static final PropertyDescriptor JSON_FORMAT = new PropertyDescriptor.Builder()
    +            .displayName("JSON Format")
    +            .name("scanhbase-json-format")
    +            .description("Specifies how to represent the HBase row as a JSON document.")
    +            .required(true)
    +            .allowableValues(JSON_FORMAT_FULL_ROW, JSON_FORMAT_QUALIFIER_AND_VALUE)
    +            .defaultValue(JSON_FORMAT_FULL_ROW.getValue())
    +            .build();
    +
    +    static final PropertyDescriptor DECODE_CHARSET = new PropertyDescriptor.Builder()
    +            .displayName("Decode Character Set")
    +            .name("scanhbase-decode-charset")
    +            .description("The character set used to decode data from HBase.")
    +            .required(true)
    +            .defaultValue("UTF-8")
    +            .addValidator(StandardValidators.CHARACTER_SET_VALIDATOR)
    +            .build();
    +
    +    static final PropertyDescriptor ENCODE_CHARSET = new PropertyDescriptor.Builder()
    +            .displayName("Encode Character Set")
    +            .name("scanhbase-encode-charset")
    +            .description("The character set used to encode the JSON representation of the row.")
    +            .required(true)
    +            .defaultValue("UTF-8")
    +            .addValidator(StandardValidators.CHARACTER_SET_VALIDATOR)
    +            .build();
    +
    +    public static final Relationship REL_ORIGINAL = new Relationship.Builder()
    +            .name("original")
    +            .description("The original input file will be routed to this destination, even if no rows are retrieved based on provided conditions.")
    +            .build();
    +
    +    static final Relationship REL_SUCCESS = new Relationship.Builder()
    +            .name("success")
    +            .description("All successful fetches are routed to this relationship.")
    +            .build();
    +    static final Relationship REL_FAILURE = new Relationship.Builder()
    +            .name("failure")
    +            .description("All failed fetches are routed to this relationship.")
    +            .build();
    +
    +    static final String HBASE_TABLE_ATTR = "hbase.table";
    +    static final String HBASE_ROWS_COUNT_ATTR = "hbase.rows.count";
    +
    +    static final List<PropertyDescriptor> properties;
    +    static {
    +        List<PropertyDescriptor> props = new ArrayList<>();
    +        props.add(HBASE_CLIENT_SERVICE);
    +        props.add(TABLE_NAME);
    +        props.add(START_ROW);
    +        props.add(END_ROW);
    +        props.add(TIME_RANGE_MIN);
    +        props.add(TIME_RANGE_MAX);
    +        props.add(LIMIT_ROWS);
    +        props.add(REVERSED_SCAN);
    +        props.add(BULK_SIZE);
    +        props.add(FILTER_EXPRESSION);
    +        props.add(COLUMNS);
    +        props.add(JSON_FORMAT);
    +        props.add(ENCODE_CHARSET);
    +        props.add(DECODE_CHARSET);
    +        properties = Collections.unmodifiableList(props);
    +    }
    +
    +    static final Set<Relationship> relationships;
    +    static {
    +        Set<Relationship> rels = new HashSet<>();
    +        rels.add(REL_SUCCESS);
    +        rels.add(REL_ORIGINAL);
    +        rels.add(REL_FAILURE);
    +        relationships = Collections.unmodifiableSet(rels);
    +    }
    +
    +    private volatile Charset decodeCharset;
    +    private volatile Charset encodeCharset;
    +    private RowSerializer serializer = null;
    +
    +    @OnScheduled
    +    public void onScheduled(ProcessContext context) {
    +        this.decodeCharset = Charset.forName(context.getProperty(DECODE_CHARSET).getValue());
    +        this.encodeCharset = Charset.forName(context.getProperty(ENCODE_CHARSET).getValue());
    +
    +        final String jsonFormat = context.getProperty(JSON_FORMAT).getValue();
    +        if (jsonFormat.equals(JSON_FORMAT_FULL_ROW.getValue())) {
    +            this.serializer = new JsonFullRowSerializer(decodeCharset, encodeCharset);
    +        } else {
    +            this.serializer = new JsonQualifierAndValueRowSerializer(decodeCharset, encodeCharset);
    +        }
    +    }
    +
    +    @Override
    +    protected List<PropertyDescriptor> getSupportedPropertyDescriptors() {
    +        return properties;
    +    }
    +
    +    @Override
    +    public Set<Relationship> getRelationships() {
    +        return relationships;
    +    }
    +
    +    @Override
    +    protected Collection<ValidationResult> customValidate(ValidationContext validationContext) {
    +
    +        final List<ValidationResult> problems = new ArrayList<>();
    +
    +        final String columns = validationContext.getProperty(COLUMNS).getValue();
    +        final String filter = validationContext.getProperty(FILTER_EXPRESSION).getValue();
    +
    +        if (!StringUtils.isBlank(columns) && !StringUtils.isBlank(filter)) {
    +            problems.add(new ValidationResult.Builder()
    +                    .subject(FILTER_EXPRESSION.getDisplayName())
    +                    .input(filter).valid(false)
    +                    .explanation("A filter expression can not be used in conjunction with the Columns property")
    +                    .build());
    +        }
    +
    +        return problems;
    +    }
    +
    +    @Override
    +    public void onTrigger(ProcessContext context, ProcessSession session) throws ProcessException {
    +        FlowFile flowFile = session.get();
    +        if (flowFile == null) {
    +            return;
    +        }
    +
    +        try{
    +            final String tableName = context.getProperty(TABLE_NAME).evaluateAttributeExpressions(flowFile).getValue();
    +            if (StringUtils.isBlank(tableName)) {
    +                getLogger().error("Table Name is blank or null for {}, transferring to failure", new Object[] {flowFile});
    +                session.transfer(session.penalize(flowFile), REL_FAILURE);
    +                return;
    +            }
    +
    +            final String startRow = context.getProperty(START_ROW).evaluateAttributeExpressions(flowFile).getValue();
    +            final String endRow = context.getProperty(END_ROW).evaluateAttributeExpressions(flowFile).getValue();
    +
    +            final String filterExpression = context.getProperty(FILTER_EXPRESSION).evaluateAttributeExpressions(flowFile).getValue();
    +
    +            //evaluate and validate time range min and max values. They both should be either empty or provided.
    +            Long timerangeMin = null;
    +            Long timerangeMax = null;
    +
    +            try{
    +                timerangeMin = context.getProperty(TIME_RANGE_MIN).evaluateAttributeExpressions(flowFile).asLong();
    +            }catch(Exception e){
    +                getLogger().error("Time range min value is not a number ({}) for {}, transferring to failure",
    +                        new Object[] {context.getProperty(TIME_RANGE_MIN).evaluateAttributeExpressions(flowFile).getValue(), flowFile});
    +                session.transfer(session.penalize(flowFile), REL_FAILURE);
    +                return;
    +            }
    +            try{
    +                timerangeMax = context.getProperty(TIME_RANGE_MAX).evaluateAttributeExpressions(flowFile).asLong();
    +            }catch(Exception e){
    +                getLogger().error("Time range max value is not a number ({}) for {}, transferring to failure",
    +                        new Object[] {context.getProperty(TIME_RANGE_MAX).evaluateAttributeExpressions(flowFile).getValue(), flowFile});
    +                session.transfer(session.penalize(flowFile), REL_FAILURE);
    +                return;
    +            }
    +            if (timerangeMin == null && timerangeMax != null) {
    +                getLogger().error("Time range min value cannot be blank when max value provided for {}, transferring to failure", new Object[] {flowFile});
    +                session.transfer(session.penalize(flowFile), REL_FAILURE);
    +                return;
    +            }else if (timerangeMin != null && timerangeMax == null) {
    +                getLogger().error("Time range max value cannot be blank when min value provided for {}, transferring to failure", new Object[] {flowFile});
    +                session.transfer(session.penalize(flowFile), REL_FAILURE);
    +                return;
    +            }
    +
    +            final Integer limitRows = context.getProperty(LIMIT_ROWS).evaluateAttributeExpressions(flowFile).asInteger();
    +
    +            final Boolean isReversed = context.getProperty(REVERSED_SCAN).asBoolean();
    +
    +            final Integer bulkSize = context.getProperty(BULK_SIZE).evaluateAttributeExpressions(flowFile).asInteger();
    +
    +            final List<Column> columns = getColumns(context.getProperty(COLUMNS).evaluateAttributeExpressions(flowFile).getValue());
    +            final HBaseClientService hBaseClientService = context.getProperty(HBASE_CLIENT_SERVICE).asControllerService(HBaseClientService.class);
    +
    +            final AtomicReference<Long> rowsPulledHolder = new AtomicReference<>(0L);
    +            final AtomicReference<Long> ffCountHolder = new AtomicReference<>(0L);
    +            ScanHBaseResultHandler handler = new ScanHBaseResultHandler(context, session, flowFile, rowsPulledHolder, ffCountHolder, hBaseClientService, tableName, bulkSize);
    +
    +            try {
    +                hBaseClientService.scan(tableName,
    +                                        startRow, endRow,
    +                                        filterExpression,
    +                                        timerangeMin, timerangeMax,
    +                                        limitRows,
    +                                        isReversed,
    +                                        columns,
    +                                        handler);
    +            } catch (IOException e) {
    +                getLogger().error("Unable to fetch rows from HBase table {} due to {}", new Object[] {tableName, e});
    +                flowFile = session.putAttribute(flowFile, "scanhbase.results.found", Boolean.toString(handler.isHandledAny()));
    +                session.transfer(flowFile, REL_FAILURE);
    +                return;
    +            }
    +
    +            LinkedList<Tuple<byte[], ResultCell[]>> hangingRows = handler.getHangingRows();
    +            if (!handler.isHandledAny() ||                                                         // no rows found in hbase
    +                    (handler.isHandledAny() && (hangingRows == null || hangingRows.isEmpty()))     // all the rows are flushed to FF inside handlers
    +                ){
    +                flowFile = session.putAttribute(flowFile, "scanhbase.results.found", Boolean.toString(handler.isHandledAny()));
    +                session.transfer(flowFile, REL_ORIGINAL);
    +                session.commit();
    +                return;
    +            }
    +
    +            if (hangingRows != null && !hangingRows.isEmpty()) {
    +                FlowFile lastFF = session.create(flowFile);
    +                final Map<String, String> attributes = new HashMap<>();
    +                attributes.put(HBASE_TABLE_ATTR, tableName);
    +                attributes.put(HBASE_ROWS_COUNT_ATTR, Long.toString(rowsPulledHolder.get()));
    +                attributes.put(CoreAttributes.MIME_TYPE.key(), "application/json");
    +                attributes.put(HBASE_ROWS_COUNT_ATTR, Long.toString(hangingRows.size()));
    +                lastFF = session.putAllAttributes(lastFF, attributes);
    +
    +                final AtomicReference<IOException> ioe = new AtomicReference<>(null);
    +                lastFF = session.write(lastFF, (out) -> {
    +                    for (Iterator<Tuple<byte[], ResultCell[]>> iter = hangingRows.iterator(); iter.hasNext();){
    +                        Tuple<byte[], ResultCell[]> r = iter.next();
    +                        serializer.serialize(r.getKey(), r.getValue(), out);
    +                        if (iter.hasNext()){
    +                            out.write(nl);
    +                        }
    +                    }
    +                });
    +
    +                Relationship rel = REL_SUCCESS;
    +                IOException error = ioe.get();
    +                if (error != null){
    +                    lastFF = session.putAttribute(lastFF, "scanhbase.error", error.toString());
    +                    rel = REL_FAILURE;
    +                }
    +                session.transfer(lastFF, rel);
    +                flowFile = session.putAttribute(flowFile, "scanhbase.results.found", Boolean.toString(handler.isHandledAny()));
    +                session.transfer(flowFile, REL_ORIGINAL);
    +            }
    +            session.commit();
    +
    +        }catch (final Exception e) {
    +            getLogger().error("Failed to receive data from HBase due to {}", e);
    +            session.rollback();
    +            // if we failed, we want to yield so that we don't hammer hbase.
    +            context.yield();
    +        }
    +    }
    +
    +    /**
    +     * @param columnsValue a String in the form colFam:colQual,colFam:colQual
    +     * @return a list of Columns based on parsing the given String
    +     */
    +    private List<Column> getColumns(final String columnsValue) {
    +        final String[] columns = (columnsValue == null || columnsValue.isEmpty() ? new String[0] : columnsValue.split(","));
    +
    +        List<Column> columnsList = new ArrayList<>(columns.length);
    +
    +        for (final String column : columns) {
    +            if (column.contains(":"))  {
    +                final String[] parts = column.split(":");
    +                final byte[] cf = parts[0].getBytes(StandardCharsets.UTF_8);
    --- End diff --
    
    Shouldn't this charset be configurable? Same for the others here.


---

[GitHub] nifi pull request #2478: NIFI-4833 Add scanHBase Processor

Posted by bbende <gi...@git.apache.org>.
Github user bbende commented on a diff in the pull request:

    https://github.com/apache/nifi/pull/2478#discussion_r170683857
  
    --- Diff: nifi-nar-bundles/nifi-hbase-bundle/nifi-hbase-processors/src/main/java/org/apache/nifi/hbase/ScanHBase.java ---
    @@ -0,0 +1,564 @@
    +/*
    + * Licensed to the Apache Software Foundation (ASF) under one or more
    + * contributor license agreements.  See the NOTICE file distributed with
    + * this work for additional information regarding copyright ownership.
    + * The ASF licenses this file to You under the Apache License, Version 2.0
    + * (the "License"); you may not use this file except in compliance with
    + * the License.  You may obtain a copy of the License at
    + *
    + *     http://www.apache.org/licenses/LICENSE-2.0
    + *
    + * Unless required by applicable law or agreed to in writing, software
    + * distributed under the License is distributed on an "AS IS" BASIS,
    + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    + * See the License for the specific language governing permissions and
    + * limitations under the License.
    + */
    +package org.apache.nifi.hbase;
    +
    +import org.apache.commons.lang3.StringUtils;
    +import org.apache.nifi.annotation.behavior.InputRequirement;
    +import org.apache.nifi.annotation.behavior.WritesAttribute;
    +import org.apache.nifi.annotation.behavior.WritesAttributes;
    +import org.apache.nifi.annotation.documentation.CapabilityDescription;
    +import org.apache.nifi.annotation.documentation.Tags;
    +import org.apache.nifi.annotation.lifecycle.OnScheduled;
    +import org.apache.nifi.components.AllowableValue;
    +import org.apache.nifi.components.PropertyDescriptor;
    +import org.apache.nifi.components.ValidationContext;
    +import org.apache.nifi.components.ValidationResult;
    +import org.apache.nifi.flowfile.FlowFile;
    +import org.apache.nifi.flowfile.attributes.CoreAttributes;
    +import org.apache.nifi.hbase.io.JsonFullRowSerializer;
    +import org.apache.nifi.hbase.io.JsonQualifierAndValueRowSerializer;
    +import org.apache.nifi.hbase.io.RowSerializer;
    +import org.apache.nifi.hbase.scan.Column;
    +import org.apache.nifi.hbase.scan.ResultCell;
    +import org.apache.nifi.hbase.scan.ResultHandler;
    +import org.apache.nifi.processor.AbstractProcessor;
    +import org.apache.nifi.processor.ProcessContext;
    +import org.apache.nifi.processor.ProcessSession;
    +import org.apache.nifi.processor.Relationship;
    +import org.apache.nifi.processor.exception.ProcessException;
    +import org.apache.nifi.processor.util.StandardValidators;
    +import org.apache.nifi.util.Tuple;
    +
    +import java.io.IOException;
    +import java.nio.charset.Charset;
    +import java.nio.charset.StandardCharsets;
    +import java.util.ArrayList;
    +import java.util.Collection;
    +import java.util.Collections;
    +import java.util.HashMap;
    +import java.util.HashSet;
    +import java.util.Iterator;
    +import java.util.LinkedList;
    +import java.util.List;
    +import java.util.Map;
    +import java.util.Set;
    +import java.util.concurrent.atomic.AtomicReference;
    +import java.util.regex.Pattern;
    +
    +@InputRequirement(InputRequirement.Requirement.INPUT_REQUIRED)
    +@Tags({"hbase", "scan", "fetch", "get"})
    +@CapabilityDescription("Scans and fetches rows from an HBase table. This processor may be used to fetch rows from hbase table by specifying a range of rowkey values (start and/or end ),"
    +        + "by time range, by filter expression, or any combination of them. "
    +        + "Order of records can be controlled by a property Reversed"
    +        + "Number of rows retrieved by the processor can be limited.")
    +@WritesAttributes({
    +        @WritesAttribute(attribute = "hbase.table", description = "The name of the HBase table that the row was fetched from"),
    +        @WritesAttribute(attribute = "hbase.resultset", description = "A JSON document/s representing the row/s. This property is only written when a Destination of flowfile-attributes is selected."),
    --- End diff --
    
    Can this be removed? Doesn't look like we allow writing the results to an attribute, which is a good thing :)


---

[GitHub] nifi issue #2478: NIFI-4833 Add scanHBase Processor

Posted by bdesert <gi...@git.apache.org>.
Github user bdesert commented on the issue:

    https://github.com/apache/nifi/pull/2478
  
    @bbende , thank you!
    Both comments make sense. Will commit these changes soon.


---

[GitHub] nifi pull request #2478: NIFI-4833 Add scanHBase Processor

Posted by MikeThomsen <gi...@git.apache.org>.
Github user MikeThomsen commented on a diff in the pull request:

    https://github.com/apache/nifi/pull/2478#discussion_r169621787
  
    --- Diff: nifi-nar-bundles/nifi-hbase-bundle/nifi-hbase-processors/src/test/java/org/apache/nifi/hbase/TestScanHBase.java ---
    @@ -0,0 +1,375 @@
    +/*
    + * Licensed to the Apache Software Foundation (ASF) under one or more
    + * contributor license agreements.  See the NOTICE file distributed with
    + * this work for additional information regarding copyright ownership.
    + * The ASF licenses this file to You under the Apache License, Version 2.0
    + * (the "License"); you may not use this file except in compliance with
    + * the License.  You may obtain a copy of the License at
    + *
    + *     http://www.apache.org/licenses/LICENSE-2.0
    + *
    + * Unless required by applicable law or agreed to in writing, software
    + * distributed under the License is distributed on an "AS IS" BASIS,
    + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    + * See the License for the specific language governing permissions and
    + * limitations under the License.
    + */
    +package org.apache.nifi.hbase;
    +
    +import java.util.HashMap;
    +import java.util.List;
    +import java.util.Map;
    +
    +import org.apache.nifi.reporting.InitializationException;
    +import org.apache.nifi.util.MockFlowFile;
    +import org.apache.nifi.util.TestRunner;
    +import org.apache.nifi.util.TestRunners;
    +import org.junit.Assert;
    +import org.junit.Before;
    +import org.junit.Test;
    +
    +public class TestScanHBase {
    +
    +    private ScanHBase proc;
    +    private MockHBaseClientService hBaseClientService;
    +    private TestRunner runner;
    +
    +    @Before
    +    public void setup() throws InitializationException {
    +        proc = new ScanHBase();
    +        runner = TestRunners.newTestRunner(proc);
    +
    +        hBaseClientService = new MockHBaseClientService();
    +        runner.addControllerService("hbaseClient", hBaseClientService);
    +        runner.enableControllerService(hBaseClientService);
    +        runner.setProperty(ScanHBase.HBASE_CLIENT_SERVICE, "hbaseClient");
    +    }
    +
    +    @Test
    +    public void testColumnsValidation() {
    +        runner.setProperty(ScanHBase.TABLE_NAME, "table1");
    +        runner.setProperty(ScanHBase.START_ROW, "row1");
    +        runner.setProperty(ScanHBase.END_ROW, "row1");
    +        runner.assertValid();
    +
    +        runner.setProperty(ScanHBase.COLUMNS, "cf1:cq1");
    +        runner.assertValid();
    +
    +        runner.setProperty(ScanHBase.COLUMNS, "cf1");
    +        runner.assertValid();
    +
    +        runner.setProperty(ScanHBase.COLUMNS, "cf1:cq1,cf2:cq2,cf3:cq3");
    +        runner.assertValid();
    +
    +        runner.setProperty(ScanHBase.COLUMNS, "cf1,cf2:cq1,cf3");
    +        runner.assertValid();
    +
    +        runner.setProperty(ScanHBase.COLUMNS, "cf1 cf2,cf3");
    +        runner.assertNotValid();
    +
    +        runner.setProperty(ScanHBase.COLUMNS, "cf1:,cf2,cf3");
    +        runner.assertNotValid();
    +
    +        runner.setProperty(ScanHBase.COLUMNS, "cf1:cq1,");
    +        runner.assertNotValid();
    +    }
    +
    +    @Test
    +    public void testNoIncomingFlowFile() {
    +        runner.setProperty(ScanHBase.TABLE_NAME, "table1");
    +        runner.setProperty(ScanHBase.START_ROW, "row1");
    +        runner.setProperty(ScanHBase.END_ROW, "row1");
    +
    +        runner.run();
    +        runner.assertTransferCount(ScanHBase.REL_FAILURE, 0);
    +        runner.assertTransferCount(ScanHBase.REL_SUCCESS, 0);
    +        runner.assertTransferCount(ScanHBase.REL_ORIGINAL, 0);
    +
    +        Assert.assertEquals(0, hBaseClientService.getNumScans());
    +    }
    +
    +    @Test
    +    public void testInvalidTableName() {
    +        runner.setProperty(ScanHBase.TABLE_NAME, "${hbase.table}");
    --- End diff --
    
    Without calling `setVariable` and `setValidateExpressionLanguage` (think that's its name) I'm not sure if this is going to do more than test the raw value in that field. Granted, that is an invalid name.


---

[GitHub] nifi pull request #2478: NIFI-4833 Add scanHBase Processor

Posted by MikeThomsen <gi...@git.apache.org>.
Github user MikeThomsen commented on a diff in the pull request:

    https://github.com/apache/nifi/pull/2478#discussion_r169072654
  
    --- Diff: nifi-nar-bundles/nifi-hbase-bundle/nifi-hbase-processors/src/main/java/org/apache/nifi/hbase/ScanHBase.java ---
    @@ -0,0 +1,562 @@
    +/*
    + * Licensed to the Apache Software Foundation (ASF) under one or more
    + * contributor license agreements.  See the NOTICE file distributed with
    + * this work for additional information regarding copyright ownership.
    + * The ASF licenses this file to You under the Apache License, Version 2.0
    + * (the "License"); you may not use this file except in compliance with
    + * the License.  You may obtain a copy of the License at
    + *
    + *     http://www.apache.org/licenses/LICENSE-2.0
    + *
    + * Unless required by applicable law or agreed to in writing, software
    + * distributed under the License is distributed on an "AS IS" BASIS,
    + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    + * See the License for the specific language governing permissions and
    + * limitations under the License.
    + */
    +package org.apache.nifi.hbase;
    +
    +import org.apache.commons.lang3.StringUtils;
    +import org.apache.nifi.annotation.behavior.InputRequirement;
    +import org.apache.nifi.annotation.behavior.WritesAttribute;
    +import org.apache.nifi.annotation.behavior.WritesAttributes;
    +import org.apache.nifi.annotation.documentation.CapabilityDescription;
    +import org.apache.nifi.annotation.documentation.Tags;
    +import org.apache.nifi.annotation.lifecycle.OnScheduled;
    +import org.apache.nifi.components.AllowableValue;
    +import org.apache.nifi.components.PropertyDescriptor;
    +import org.apache.nifi.components.ValidationContext;
    +import org.apache.nifi.components.ValidationResult;
    +import org.apache.nifi.flowfile.FlowFile;
    +import org.apache.nifi.flowfile.attributes.CoreAttributes;
    +import org.apache.nifi.hbase.io.JsonFullRowSerializer;
    +import org.apache.nifi.hbase.io.JsonQualifierAndValueRowSerializer;
    +import org.apache.nifi.hbase.io.RowSerializer;
    +import org.apache.nifi.hbase.scan.Column;
    +import org.apache.nifi.hbase.scan.ResultCell;
    +import org.apache.nifi.hbase.scan.ResultHandler;
    +import org.apache.nifi.processor.AbstractProcessor;
    +import org.apache.nifi.processor.ProcessContext;
    +import org.apache.nifi.processor.ProcessSession;
    +import org.apache.nifi.processor.Relationship;
    +import org.apache.nifi.processor.exception.ProcessException;
    +import org.apache.nifi.processor.util.StandardValidators;
    +import org.apache.nifi.util.Tuple;
    +
    +import java.io.IOException;
    +import java.nio.charset.Charset;
    +import java.nio.charset.StandardCharsets;
    +import java.util.ArrayList;
    +import java.util.Collection;
    +import java.util.Collections;
    +import java.util.HashMap;
    +import java.util.HashSet;
    +import java.util.Iterator;
    +import java.util.LinkedList;
    +import java.util.List;
    +import java.util.Map;
    +import java.util.Set;
    +import java.util.concurrent.atomic.AtomicReference;
    +import java.util.regex.Pattern;
    +
    +@InputRequirement(InputRequirement.Requirement.INPUT_REQUIRED)
    +@Tags({"hbase", "scan", "fetch", "get"})
    +@CapabilityDescription("Scans and fetches rows from an HBase table. This processor may be used to fetch rows from hbase table by specifying a range of rowkey values (start and/or end ),"
    +        + "by time range, by filter expression, or any combination of them. \n"
    +        + "Order of records can be controlled by a property <code>Reversed</code>"
    +        + "Number of rows retrieved by the processor can be limited.")
    +@WritesAttributes({
    +        @WritesAttribute(attribute = "hbase.table", description = "The name of the HBase table that the row was fetched from"),
    +        @WritesAttribute(attribute = "hbase.resultset", description = "A JSON document/s representing the row/s. This property is only written when a Destination of flowfile-attributes is selected."),
    +        @WritesAttribute(attribute = "mime.type", description = "Set to application/json when using a Destination of flowfile-content, not set or modified otherwise"),
    +        @WritesAttribute(attribute = "hbase.rows.count", description = "Number of rows in the content of given flow file"),
    +        @WritesAttribute(attribute = "scanhbase.results.found", description = "Indicates whether at least one row has been found in given hbase table with provided conditions. <br/>"
    +                + "Could be null (not present) if transfered to FAILURE")
    +})
    +public class ScanHBase extends AbstractProcessor {
    +    //enhanced regex for columns to allow "-" in column qualifier names
    +    static final Pattern COLUMNS_PATTERN = Pattern.compile("\\w+(:(\\w|-)+)?(?:,\\w+(:(\\w|-)+)?)*");
    +    static final byte[] nl = System.lineSeparator().getBytes();
    +
    +    static final PropertyDescriptor HBASE_CLIENT_SERVICE = new PropertyDescriptor.Builder()
    +            .displayName("HBase Client Service")
    +            .name("scanhbase-client-service")
    +            .description("Specifies the Controller Service to use for accessing HBase.")
    +            .required(true)
    +            .identifiesControllerService(HBaseClientService.class)
    +            .build();
    +
    +    static final PropertyDescriptor TABLE_NAME = new PropertyDescriptor.Builder()
    +            .displayName("Table Name")
    +            .name("scanhbase-table-name")
    +            .description("The name of the HBase Table to fetch from.")
    +            .required(true)
    +            .expressionLanguageSupported(true)
    +            .addValidator(StandardValidators.NON_EMPTY_VALIDATOR)
    +            .build();
    +
    +    static final PropertyDescriptor START_ROW = new PropertyDescriptor.Builder()
    +            .displayName("Start rowkey")
    +            .name("scanhbase-start-rowkey")
    +            .description("The rowkey to start scan from.")
    +            .required(false)
    +            .expressionLanguageSupported(true)
    +            .addValidator(StandardValidators.NON_EMPTY_VALIDATOR)
    +            .build();
    +
    +    static final PropertyDescriptor END_ROW = new PropertyDescriptor.Builder()
    +            .displayName("End rowkey")
    +            .name("scanhbase-end-rowkey")
    +            .description("The row key to end scan by.")
    +            .required(false)
    +            .expressionLanguageSupported(true)
    +            .addValidator(StandardValidators.NON_EMPTY_VALIDATOR)
    +            .build();
    +
    +    static final PropertyDescriptor TIME_RANGE_MIN = new PropertyDescriptor.Builder()
    +            .displayName("Time range min")
    +            .name("scanhbase-time-range-min")
    +            .description("Time range min value. Both min and max values for time range should be either blank or provided.")
    +            .required(false)
    +            .expressionLanguageSupported(true)
    +            .addValidator(StandardValidators.LONG_VALIDATOR)
    +            .build();
    +
    +    static final PropertyDescriptor TIME_RANGE_MAX = new PropertyDescriptor.Builder()
    +            .displayName("Time range max")
    +            .name("scanhbase-time-range-max")
    +            .description("Time range max value. Both min and max values for time range should be either blank or provided.")
    +            .required(false)
    +            .expressionLanguageSupported(true)
    +            .addValidator(StandardValidators.LONG_VALIDATOR)
    +            .build();
    +
    +    static final PropertyDescriptor LIMIT_ROWS = new PropertyDescriptor.Builder()
    +            .displayName("Limit rows")
    +            .name("scanhbase-limit")
    +            .description("Limit number of rows retrieved by scan.")
    +            .required(false)
    +            .expressionLanguageSupported(true)
    +            .addValidator(StandardValidators.INTEGER_VALIDATOR)
    +            .build();
    +
    +    static final PropertyDescriptor BULK_SIZE = new PropertyDescriptor.Builder()
    +            .displayName("Max rows per flow file")
    +            .name("scanhbase-bulk-size")
    +            .description("Limits number of rows in single flow file content. Set to 0 to avoid multiple flow files.")
    +            .required(false)
    +            .expressionLanguageSupported(true)
    +            .defaultValue("0")
    +            .addValidator(StandardValidators.INTEGER_VALIDATOR)
    +            .build();
    +
    +    static final PropertyDescriptor REVERSED_SCAN = new PropertyDescriptor.Builder()
    +            .displayName("Reversed order")
    +            .name("scanhbase-reversed-order")
    +            .description("Set whether this scan is a reversed one. This is false by default which means forward(normal) scan.")
    +            .expressionLanguageSupported(false)
    +            .allowableValues("true", "false")
    +            .required(false)
    +            .defaultValue("false")
    +            .addValidator(StandardValidators.BOOLEAN_VALIDATOR)
    +            .build();
    +
    +    static final PropertyDescriptor FILTER_EXPRESSION = new PropertyDescriptor.Builder()
    +            .displayName("Filter expression")
    +            .name("scanhbase-filter-expression")
    +            .description("An HBase filter expression that will be applied to the scan. This property can not be used when also using the Columns property.<br/>"
    +                    + "Example: \"ValueFilter( =, 'binaryprefix:commit' )\"")
    +            .required(false)
    +            .expressionLanguageSupported(true)
    +            .addValidator(StandardValidators.NON_EMPTY_VALIDATOR)
    +            .build();
    +
    +    static final PropertyDescriptor COLUMNS = new PropertyDescriptor.Builder()
    +            .displayName("Columns")
    +            .name("scanhbase-columns")
    +            .description("An optional comma-separated list of \"<colFamily>:<colQualifier>\" pairs to fetch. To return all columns " +
    +                    "for a given family, leave off the qualifier such as \"<colFamily1>,<colFamily2>\".")
    +            .required(false)
    +            .expressionLanguageSupported(true)
    +            .addValidator(StandardValidators.createRegexMatchingValidator(COLUMNS_PATTERN))
    +            .build();
    +
    +    static final AllowableValue JSON_FORMAT_FULL_ROW = new AllowableValue("full-row", "full-row",
    +            "Creates a JSON document with the format: {\"row\":<row-id>, \"cells\":[{\"fam\":<col-fam>, \"qual\":<col-val>, \"val\":<value>, \"ts\":<timestamp>}]}.");
    +    static final AllowableValue JSON_FORMAT_QUALIFIER_AND_VALUE = new AllowableValue("col-qual-and-val", "col-qual-and-val",
    +            "Creates a JSON document with the format: {\"<col-qual>\":\"<value>\", \"<col-qual>\":\"<value>\".");
    +
    +    static final PropertyDescriptor JSON_FORMAT = new PropertyDescriptor.Builder()
    +            .displayName("JSON Format")
    +            .name("scanhbase-json-format")
    +            .description("Specifies how to represent the HBase row as a JSON document.")
    +            .required(true)
    +            .allowableValues(JSON_FORMAT_FULL_ROW, JSON_FORMAT_QUALIFIER_AND_VALUE)
    +            .defaultValue(JSON_FORMAT_FULL_ROW.getValue())
    +            .build();
    +
    +    static final PropertyDescriptor DECODE_CHARSET = new PropertyDescriptor.Builder()
    +            .displayName("Decode Character Set")
    +            .name("scanhbase-decode-charset")
    +            .description("The character set used to decode data from HBase.")
    +            .required(true)
    +            .defaultValue("UTF-8")
    +            .addValidator(StandardValidators.CHARACTER_SET_VALIDATOR)
    +            .build();
    +
    +    static final PropertyDescriptor ENCODE_CHARSET = new PropertyDescriptor.Builder()
    +            .displayName("Encode Character Set")
    +            .name("scanhbase-encode-charset")
    +            .description("The character set used to encode the JSON representation of the row.")
    +            .required(true)
    +            .defaultValue("UTF-8")
    +            .addValidator(StandardValidators.CHARACTER_SET_VALIDATOR)
    +            .build();
    +
    +    public static final Relationship REL_ORIGINAL = new Relationship.Builder()
    +            .name("original")
    +            .description("The original input file will be routed to this destination, even if no rows are retrieved based on provided conditions.")
    +            .build();
    +
    +    static final Relationship REL_SUCCESS = new Relationship.Builder()
    +            .name("success")
    +            .description("All successful fetches are routed to this relationship.")
    +            .build();
    +    static final Relationship REL_FAILURE = new Relationship.Builder()
    +            .name("failure")
    +            .description("All failed fetches are routed to this relationship.")
    +            .build();
    +
    +    static final String HBASE_TABLE_ATTR = "hbase.table";
    +    static final String HBASE_ROWS_COUNT_ATTR = "hbase.rows.count";
    +
    +    static final List<PropertyDescriptor> properties;
    +    static {
    +        List<PropertyDescriptor> props = new ArrayList<>();
    +        props.add(HBASE_CLIENT_SERVICE);
    +        props.add(TABLE_NAME);
    +        props.add(START_ROW);
    +        props.add(END_ROW);
    +        props.add(TIME_RANGE_MIN);
    +        props.add(TIME_RANGE_MAX);
    +        props.add(LIMIT_ROWS);
    +        props.add(REVERSED_SCAN);
    +        props.add(BULK_SIZE);
    +        props.add(FILTER_EXPRESSION);
    +        props.add(COLUMNS);
    +        props.add(JSON_FORMAT);
    +        props.add(ENCODE_CHARSET);
    +        props.add(DECODE_CHARSET);
    +        properties = Collections.unmodifiableList(props);
    +    }
    +
    +    static final Set<Relationship> relationships;
    +    static {
    +        Set<Relationship> rels = new HashSet<>();
    +        rels.add(REL_SUCCESS);
    +        rels.add(REL_ORIGINAL);
    +        rels.add(REL_FAILURE);
    +        relationships = Collections.unmodifiableSet(rels);
    +    }
    +
    +    private volatile Charset decodeCharset;
    +    private volatile Charset encodeCharset;
    +    private RowSerializer serializer = null;
    +
    +    @OnScheduled
    +    public void onScheduled(ProcessContext context) {
    +        this.decodeCharset = Charset.forName(context.getProperty(DECODE_CHARSET).getValue());
    +        this.encodeCharset = Charset.forName(context.getProperty(ENCODE_CHARSET).getValue());
    +
    +        final String jsonFormat = context.getProperty(JSON_FORMAT).getValue();
    +        if (jsonFormat.equals(JSON_FORMAT_FULL_ROW.getValue())) {
    +            this.serializer = new JsonFullRowSerializer(decodeCharset, encodeCharset);
    +        } else {
    +            this.serializer = new JsonQualifierAndValueRowSerializer(decodeCharset, encodeCharset);
    +        }
    +    }
    +
    +    @Override
    +    protected List<PropertyDescriptor> getSupportedPropertyDescriptors() {
    +        return properties;
    +    }
    +
    +    @Override
    +    public Set<Relationship> getRelationships() {
    +        return relationships;
    +    }
    +
    +    @Override
    +    protected Collection<ValidationResult> customValidate(ValidationContext validationContext) {
    +
    +        final List<ValidationResult> problems = new ArrayList<>();
    +
    +        final String columns = validationContext.getProperty(COLUMNS).getValue();
    +        final String filter = validationContext.getProperty(FILTER_EXPRESSION).getValue();
    +
    +        if (!StringUtils.isBlank(columns) && !StringUtils.isBlank(filter)) {
    +            problems.add(new ValidationResult.Builder()
    +                    .subject(FILTER_EXPRESSION.getDisplayName())
    +                    .input(filter).valid(false)
    +                    .explanation("A filter expression can not be used in conjunction with the Columns property")
    +                    .build());
    +        }
    +
    +        return problems;
    +    }
    +
    +    @Override
    +    public void onTrigger(ProcessContext context, ProcessSession session) throws ProcessException {
    +        FlowFile flowFile = session.get();
    +        if (flowFile == null) {
    +            return;
    +        }
    +
    +        try{
    +            final String tableName = context.getProperty(TABLE_NAME).evaluateAttributeExpressions(flowFile).getValue();
    +            if (StringUtils.isBlank(tableName)) {
    +                getLogger().error("Table Name is blank or null for {}, transferring to failure", new Object[] {flowFile});
    +                session.transfer(session.penalize(flowFile), REL_FAILURE);
    +                return;
    +            }
    +
    +            final String startRow = context.getProperty(START_ROW).evaluateAttributeExpressions(flowFile).getValue();
    +            final String endRow = context.getProperty(END_ROW).evaluateAttributeExpressions(flowFile).getValue();
    +
    +            final String filterExpression = context.getProperty(FILTER_EXPRESSION).evaluateAttributeExpressions(flowFile).getValue();
    +
    +            //evaluate and validate time range min and max values. They both should be either empty or provided.
    +            Long timerangeMin = null;
    +            Long timerangeMax = null;
    +
    +            try{
    +                timerangeMin = context.getProperty(TIME_RANGE_MIN).evaluateAttributeExpressions(flowFile).asLong();
    +            }catch(Exception e){
    +                getLogger().error("Time range min value is not a number ({}) for {}, transferring to failure",
    +                        new Object[] {context.getProperty(TIME_RANGE_MIN).evaluateAttributeExpressions(flowFile).getValue(), flowFile});
    +                session.transfer(session.penalize(flowFile), REL_FAILURE);
    +                return;
    +            }
    +            try{
    +                timerangeMax = context.getProperty(TIME_RANGE_MAX).evaluateAttributeExpressions(flowFile).asLong();
    +            }catch(Exception e){
    +                getLogger().error("Time range max value is not a number ({}) for {}, transferring to failure",
    +                        new Object[] {context.getProperty(TIME_RANGE_MAX).evaluateAttributeExpressions(flowFile).getValue(), flowFile});
    +                session.transfer(session.penalize(flowFile), REL_FAILURE);
    +                return;
    +            }
    +            if (timerangeMin == null && timerangeMax != null) {
    +                getLogger().error("Time range min value cannot be blank when max value provided for {}, transferring to failure", new Object[] {flowFile});
    +                session.transfer(session.penalize(flowFile), REL_FAILURE);
    +                return;
    +            }else if (timerangeMin != null && timerangeMax == null) {
    +                getLogger().error("Time range max value cannot be blank when min value provided for {}, transferring to failure", new Object[] {flowFile});
    +                session.transfer(session.penalize(flowFile), REL_FAILURE);
    +                return;
    +            }
    +
    +            final Integer limitRows = context.getProperty(LIMIT_ROWS).evaluateAttributeExpressions(flowFile).asInteger();
    +
    +            final Boolean isReversed = context.getProperty(REVERSED_SCAN).asBoolean();
    +
    +            final Integer bulkSize = context.getProperty(BULK_SIZE).evaluateAttributeExpressions(flowFile).asInteger();
    +
    +            final List<Column> columns = getColumns(context.getProperty(COLUMNS).evaluateAttributeExpressions(flowFile).getValue());
    +            final HBaseClientService hBaseClientService = context.getProperty(HBASE_CLIENT_SERVICE).asControllerService(HBaseClientService.class);
    +
    +            final AtomicReference<Long> rowsPulledHolder = new AtomicReference<>(0L);
    +            final AtomicReference<Long> ffCountHolder = new AtomicReference<>(0L);
    +            ScanHBaseResultHandler handler = new ScanHBaseResultHandler(context, session, flowFile, rowsPulledHolder, ffCountHolder, hBaseClientService, tableName, bulkSize);
    +
    +            try {
    +                hBaseClientService.scan(tableName,
    +                                        filterExpression,
    --- End diff --
    
    Wrong argument order. It should be tableName, start, end and then filterExpression.


---

[GitHub] nifi pull request #2478: NIFI-4833 Add scanHBase Processor

Posted by bdesert <gi...@git.apache.org>.
Github user bdesert commented on a diff in the pull request:

    https://github.com/apache/nifi/pull/2478#discussion_r169732184
  
    --- Diff: nifi-nar-bundles/nifi-hbase-bundle/nifi-hbase-processors/src/main/java/org/apache/nifi/hbase/ScanHBase.java ---
    @@ -0,0 +1,562 @@
    +/*
    + * Licensed to the Apache Software Foundation (ASF) under one or more
    + * contributor license agreements.  See the NOTICE file distributed with
    + * this work for additional information regarding copyright ownership.
    + * The ASF licenses this file to You under the Apache License, Version 2.0
    + * (the "License"); you may not use this file except in compliance with
    + * the License.  You may obtain a copy of the License at
    + *
    + *     http://www.apache.org/licenses/LICENSE-2.0
    + *
    + * Unless required by applicable law or agreed to in writing, software
    + * distributed under the License is distributed on an "AS IS" BASIS,
    + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    + * See the License for the specific language governing permissions and
    + * limitations under the License.
    + */
    +package org.apache.nifi.hbase;
    +
    +import org.apache.commons.lang3.StringUtils;
    +import org.apache.nifi.annotation.behavior.InputRequirement;
    +import org.apache.nifi.annotation.behavior.WritesAttribute;
    +import org.apache.nifi.annotation.behavior.WritesAttributes;
    +import org.apache.nifi.annotation.documentation.CapabilityDescription;
    +import org.apache.nifi.annotation.documentation.Tags;
    +import org.apache.nifi.annotation.lifecycle.OnScheduled;
    +import org.apache.nifi.components.AllowableValue;
    +import org.apache.nifi.components.PropertyDescriptor;
    +import org.apache.nifi.components.ValidationContext;
    +import org.apache.nifi.components.ValidationResult;
    +import org.apache.nifi.flowfile.FlowFile;
    +import org.apache.nifi.flowfile.attributes.CoreAttributes;
    +import org.apache.nifi.hbase.io.JsonFullRowSerializer;
    +import org.apache.nifi.hbase.io.JsonQualifierAndValueRowSerializer;
    +import org.apache.nifi.hbase.io.RowSerializer;
    +import org.apache.nifi.hbase.scan.Column;
    +import org.apache.nifi.hbase.scan.ResultCell;
    +import org.apache.nifi.hbase.scan.ResultHandler;
    +import org.apache.nifi.processor.AbstractProcessor;
    +import org.apache.nifi.processor.ProcessContext;
    +import org.apache.nifi.processor.ProcessSession;
    +import org.apache.nifi.processor.Relationship;
    +import org.apache.nifi.processor.exception.ProcessException;
    +import org.apache.nifi.processor.util.StandardValidators;
    +import org.apache.nifi.util.Tuple;
    +
    +import java.io.IOException;
    +import java.nio.charset.Charset;
    +import java.nio.charset.StandardCharsets;
    +import java.util.ArrayList;
    +import java.util.Collection;
    +import java.util.Collections;
    +import java.util.HashMap;
    +import java.util.HashSet;
    +import java.util.Iterator;
    +import java.util.LinkedList;
    +import java.util.List;
    +import java.util.Map;
    +import java.util.Set;
    +import java.util.concurrent.atomic.AtomicReference;
    +import java.util.regex.Pattern;
    +
    +@InputRequirement(InputRequirement.Requirement.INPUT_REQUIRED)
    --- End diff --
    
    I was thinking about that before. Couldn't really decide, and then I took a look at DeleteHBaseRow and FetchHBaseRow and decided to keep it consistent.


---

[GitHub] nifi pull request #2478: NIFI-4833 Add scanHBase Processor

Posted by MikeThomsen <gi...@git.apache.org>.
Github user MikeThomsen commented on a diff in the pull request:

    https://github.com/apache/nifi/pull/2478#discussion_r169622823
  
    --- Diff: nifi-nar-bundles/nifi-standard-services/nifi-hbase_1_1_2-client-service-bundle/nifi-hbase_1_1_2-client-service/src/main/java/org/apache/nifi/hbase/HBase_1_1_2_ClientService.java ---
    @@ -430,6 +430,78 @@ public void scan(final String tableName, final byte[] startRow, final byte[] end
             }
         }
     
    +    @Override
    +    public void scan(final String tableName, final String startRow, final String endRow, String filterExpression,
    +            final Long timerangeMin, final Long timerangeMax, final Integer limitRows, final Boolean isReversed,
    +            final Collection<Column> columns, final ResultHandler handler) throws IOException {
    +
    +        try (final Table table = connection.getTable(TableName.valueOf(tableName));
    +                final ResultScanner scanner = getResults(table, startRow, endRow, filterExpression, timerangeMin,
    +                        timerangeMax, limitRows, isReversed, columns)) {
    +
    +            int cnt = 0;
    +            final int lim = limitRows != null ? limitRows : 0;
    +            for (final Result result : scanner) {
    +
    +                if (lim > 0 && cnt++ > lim) break;
    +
    +                final byte[] rowKey = result.getRow();
    +                final Cell[] cells = result.rawCells();
    +
    +                if (cells == null) {
    +                    continue;
    +                }
    +
    +                // convert HBase cells to NiFi cells
    +                final ResultCell[] resultCells = new ResultCell[cells.length];
    +                for (int i = 0; i < cells.length; i++) {
    +                    final Cell cell = cells[i];
    +                    final ResultCell resultCell = getResultCell(cell);
    +                    resultCells[i] = resultCell;
    +                }
    +
    +                // delegate to the handler
    +                handler.handle(rowKey, resultCells);
    +            }
    +        }
    +
    +    }
    +
    +    //
    +    protected ResultScanner getResults(final Table table, final String startRow, final String endRow, final String filterExpression, final Long timerangeMin, final Long timerangeMax,
    +            final Integer limitRows, final Boolean isReversed, final Collection<Column> columns)  throws IOException {
    +        final Scan scan = new Scan();
    +        if (!StringUtils.isBlank(startRow)) scan.setStartRow(startRow.getBytes(StandardCharsets.UTF_8));
    +        if (!StringUtils.isBlank(endRow))   scan.setStopRow(   endRow.getBytes(StandardCharsets.UTF_8));
    +
    +
    +        Filter filter = null;
    +        if (columns != null) {
    +            for (Column col : columns) {
    +                if (col.getQualifier() == null) {
    +                    scan.addFamily(col.getFamily());
    +                } else {
    +                    scan.addColumn(col.getFamily(), col.getQualifier());
    +                }
    +            }
    +        }else if (!StringUtils.isBlank(filterExpression)) {
    +            ParseFilter parseFilter = new ParseFilter();
    +            filter = parseFilter.parseFilterString(filterExpression);
    +        }
    +        if (filter != null) scan.setFilter(filter);
    +
    +        if (timerangeMin != null && timerangeMax != null) scan.setTimeRange(timerangeMin, timerangeMax);
    +
    +        // ->>> reserved for HBase v 2 or later
    +        //if (limitRows != null && limitRows > 0){
    +        //    scan.setLimit(limitRows)
    +        //}
    +
    +        if (isReversed != null) scan.setReversed(isReversed);
    --- End diff --
    
    Same as above.


---

[GitHub] nifi pull request #2478: NIFI-4833 Add scanHBase Processor

Posted by bdesert <gi...@git.apache.org>.
Github user bdesert commented on a diff in the pull request:

    https://github.com/apache/nifi/pull/2478#discussion_r169680760
  
    --- Diff: nifi-nar-bundles/nifi-hbase-bundle/nifi-hbase-processors/src/test/java/org/apache/nifi/hbase/TestScanHBase.java ---
    @@ -0,0 +1,375 @@
    +/*
    + * Licensed to the Apache Software Foundation (ASF) under one or more
    + * contributor license agreements.  See the NOTICE file distributed with
    + * this work for additional information regarding copyright ownership.
    + * The ASF licenses this file to You under the Apache License, Version 2.0
    + * (the "License"); you may not use this file except in compliance with
    + * the License.  You may obtain a copy of the License at
    + *
    + *     http://www.apache.org/licenses/LICENSE-2.0
    + *
    + * Unless required by applicable law or agreed to in writing, software
    + * distributed under the License is distributed on an "AS IS" BASIS,
    + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    + * See the License for the specific language governing permissions and
    + * limitations under the License.
    + */
    +package org.apache.nifi.hbase;
    +
    +import java.util.HashMap;
    +import java.util.List;
    +import java.util.Map;
    +
    +import org.apache.nifi.reporting.InitializationException;
    +import org.apache.nifi.util.MockFlowFile;
    +import org.apache.nifi.util.TestRunner;
    +import org.apache.nifi.util.TestRunners;
    +import org.junit.Assert;
    +import org.junit.Before;
    +import org.junit.Test;
    +
    +public class TestScanHBase {
    +
    +    private ScanHBase proc;
    +    private MockHBaseClientService hBaseClientService;
    +    private TestRunner runner;
    +
    +    @Before
    +    public void setup() throws InitializationException {
    +        proc = new ScanHBase();
    +        runner = TestRunners.newTestRunner(proc);
    +
    +        hBaseClientService = new MockHBaseClientService();
    +        runner.addControllerService("hbaseClient", hBaseClientService);
    +        runner.enableControllerService(hBaseClientService);
    +        runner.setProperty(ScanHBase.HBASE_CLIENT_SERVICE, "hbaseClient");
    +    }
    +
    +    @Test
    +    public void testColumnsValidation() {
    +        runner.setProperty(ScanHBase.TABLE_NAME, "table1");
    +        runner.setProperty(ScanHBase.START_ROW, "row1");
    +        runner.setProperty(ScanHBase.END_ROW, "row1");
    +        runner.assertValid();
    +
    +        runner.setProperty(ScanHBase.COLUMNS, "cf1:cq1");
    +        runner.assertValid();
    +
    +        runner.setProperty(ScanHBase.COLUMNS, "cf1");
    +        runner.assertValid();
    +
    +        runner.setProperty(ScanHBase.COLUMNS, "cf1:cq1,cf2:cq2,cf3:cq3");
    +        runner.assertValid();
    +
    +        runner.setProperty(ScanHBase.COLUMNS, "cf1,cf2:cq1,cf3");
    +        runner.assertValid();
    +
    +        runner.setProperty(ScanHBase.COLUMNS, "cf1 cf2,cf3");
    +        runner.assertNotValid();
    +
    +        runner.setProperty(ScanHBase.COLUMNS, "cf1:,cf2,cf3");
    +        runner.assertNotValid();
    +
    +        runner.setProperty(ScanHBase.COLUMNS, "cf1:cq1,");
    +        runner.assertNotValid();
    +    }
    +
    +    @Test
    +    public void testNoIncomingFlowFile() {
    +        runner.setProperty(ScanHBase.TABLE_NAME, "table1");
    +        runner.setProperty(ScanHBase.START_ROW, "row1");
    +        runner.setProperty(ScanHBase.END_ROW, "row1");
    +
    +        runner.run();
    +        runner.assertTransferCount(ScanHBase.REL_FAILURE, 0);
    +        runner.assertTransferCount(ScanHBase.REL_SUCCESS, 0);
    +        runner.assertTransferCount(ScanHBase.REL_ORIGINAL, 0);
    +
    +        Assert.assertEquals(0, hBaseClientService.getNumScans());
    +    }
    +
    +    @Test
    +    public void testInvalidTableName() {
    +        runner.setProperty(ScanHBase.TABLE_NAME, "${hbase.table}");
    +        runner.setProperty(ScanHBase.START_ROW, "row1");
    +        runner.setProperty(ScanHBase.END_ROW, "row1");
    +
    +        runner.enqueue("trigger flow file");
    +        runner.run();
    +
    +        runner.assertTransferCount(ScanHBase.REL_FAILURE, 1);
    +        runner.assertTransferCount(ScanHBase.REL_SUCCESS, 0);
    +        runner.assertTransferCount(ScanHBase.REL_ORIGINAL, 0);
    +
    +        Assert.assertEquals(0, hBaseClientService.getNumScans());
    +    }
    +
    +    @Test
    +    public void testResultsNotFound() {
    +        runner.setProperty(ScanHBase.TABLE_NAME, "table1");
    +        runner.setProperty(ScanHBase.START_ROW, "row1");
    +        runner.setProperty(ScanHBase.END_ROW, "row1");
    +
    +        runner.enqueue("trigger flow file");
    +        runner.run();
    +
    +        runner.assertTransferCount(ScanHBase.REL_FAILURE, 0);
    +        runner.assertTransferCount(ScanHBase.REL_SUCCESS, 0);
    +        runner.assertTransferCount(ScanHBase.REL_ORIGINAL, 1);
    +
    +        MockFlowFile flowFile = runner.getFlowFilesForRelationship(ScanHBase.REL_ORIGINAL).get(0);
    +        flowFile.assertAttributeEquals("scanhbase.results.found", Boolean.FALSE.toString());
    +
    +        Assert.assertEquals(1, hBaseClientService.getNumScans());
    +    }
    +
    +    @Test
    +    public void testScanToContentWithStringValues() {
    +        final Map<String, String> cells = new HashMap<>();
    +        cells.put("cq1", "val1");
    +        cells.put("cq2", "val2");
    +
    +        final long ts1 = 123456789;
    +        hBaseClientService.addResult("row1", cells, ts1);
    +        hBaseClientService.addResult("row2", cells, ts1);
    +
    +        runner.setProperty(ScanHBase.TABLE_NAME, "table1");
    +        runner.setProperty(ScanHBase.START_ROW, "row1");
    +        runner.setProperty(ScanHBase.END_ROW, "row2");
    +        runner.setProperty(ScanHBase.TIME_RANGE_MIN, "0");
    +        runner.setProperty(ScanHBase.TIME_RANGE_MAX, "1111111110");
    +        runner.setProperty(ScanHBase.LIMIT_ROWS, "10");
    +        runner.setProperty(ScanHBase.REVERSED_SCAN, "false");
    +        runner.setProperty(ScanHBase.BULK_SIZE, "10");
    +
    +        runner.enqueue("trigger flow file");
    +        runner.run();
    +
    +        runner.assertTransferCount(ScanHBase.REL_FAILURE, 0);
    +        runner.assertTransferCount(ScanHBase.REL_SUCCESS, 1);
    +        runner.assertTransferCount(ScanHBase.REL_ORIGINAL, 1);
    +
    +        MockFlowFile flowFile = runner.getFlowFilesForRelationship(ScanHBase.REL_SUCCESS).get(0);
    +        flowFile.assertContentEquals("{\"row\":\"row1\", \"cells\": [" +
    --- End diff --
    
    The formatting and structure of JSON representation is coming from NIFI implementation, not HBase. It is defined in:
    org.apache.nifi.hbase.io.JsonFullRowSerializer;
    org.apache.nifi.hbase.io.JsonQualifierAndValueRowSerializer;
    
    Also, I tried to keep it consistent with TestFetchHBaseRow.


---