List of usage examples for org.apache.commons.lang3 StringUtils trimToEmpty
public static String trimToEmpty(final String str)
Removes control characters (char <= 32) from both ends of this String returning an empty String ("") if the String is empty ("") after the trim or if it is null .
From source file:org.apache.metron.stellar.common.shell.StellarShell.java
/** * Handle a magic '%define var=value'. Alter the global configuration. * @param expression The expression passed to %define *//*from w w w . j a va 2 s . c om*/ public void handleMagicDefine(String expression) { // grab the expression in '%define <assign-expression>' String assignExpr = StringUtils.trimToEmpty(expression.substring(MAGIC_DEFINE.length())); if (assignExpr.length() > 0) { // the expression must be an assignment if (StellarAssignment.isAssignment(assignExpr)) { StellarAssignment expr = StellarAssignment.from(assignExpr); // execute the expression Object result = executor.execute(expr.getStatement()); if (result != null) { writeLine(result.toString()); // alter the global configuration getOrCreateGlobalConfig(executor).put(expr.getVariable(), result); } } else { // the expression is not an assignment. boo! writeLine(ERROR_PROMPT + MAGIC_DEFINE + " expected assignment expression"); } } }
From source file:org.apache.nifi.processors.aws.AbstractAWSProcessor.java
protected void initializeRegionAndEndpoint(ProcessContext context) { // if the processor supports REGION, get the configured region. if (getSupportedPropertyDescriptors().contains(REGION)) { final String region = context.getProperty(REGION).getValue(); if (region != null) { this.region = Region.getRegion(Regions.fromName(region)); client.setRegion(this.region); } else {//from ww w .ja v a 2s. c o m this.region = null; } } // if the endpoint override has been configured, set the endpoint. // (per Amazon docs this should only be configured at client creation) final String urlstr = StringUtils.trimToEmpty(context.getProperty(ENDPOINT_OVERRIDE).getValue()); if (!urlstr.isEmpty()) { this.client.setEndpoint(urlstr); } }
From source file:org.apache.nifi.processors.aws.s3.AbstractS3Processor.java
private void initalizeEndpointOverride(final ProcessContext context, final AmazonS3Client s3) { // if ENDPOINT_OVERRIDE is set, use PathStyleAccess if (StringUtils.trimToEmpty(context.getProperty(ENDPOINT_OVERRIDE).getValue()).isEmpty() == false) { final S3ClientOptions s3Options = new S3ClientOptions(); s3Options.setPathStyleAccess(true); s3.setS3ClientOptions(s3Options); }// w ww . jav a2 s. c o m }
From source file:org.apache.nifi.processors.aws.wag.AbstractAWSGatewayApiProcessor.java
@Override public void onPropertyModified(final PropertyDescriptor descriptor, final String oldValue, final String newValue) { if (descriptor.isDynamic()) { final Set<String> newDynamicPropertyNames = new HashSet<>(dynamicPropertyNames); if (newValue == null) { newDynamicPropertyNames.remove(descriptor.getName()); } else if (oldValue == null) { // new property newDynamicPropertyNames.add(descriptor.getName()); }/*from w w w . ja va2s. c om*/ this.dynamicPropertyNames = Collections.unmodifiableSet(newDynamicPropertyNames); } else { // compile the attributes-to-send filter pattern if (PROP_ATTRIBUTES_TO_SEND.getName().equalsIgnoreCase(descriptor.getName())) { if (newValue == null || newValue.isEmpty()) { regexAttributesToSend = null; } else { final String trimmedValue = StringUtils.trimToEmpty(newValue); regexAttributesToSend = Pattern.compile(trimmedValue); } } } }
From source file:org.apache.nifi.processors.elasticsearch.FetchElasticsearchHttp.java
@Override public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException { FlowFile flowFile = null;/*from www. ja va 2s.c om*/ if (context.hasIncomingConnection()) { flowFile = session.get(); // If we have no FlowFile, and all incoming connections are self-loops then we can continue on. // However, if we have no FlowFile and we have connections coming from other Processors, then // we know that we should run only if we have a FlowFile. if (flowFile == null && context.hasNonLoopConnection()) { return; } } OkHttpClient okHttpClient = getClient(); if (flowFile == null) { flowFile = session.create(); } final String index = context.getProperty(INDEX).evaluateAttributeExpressions(flowFile).getValue(); final String docId = context.getProperty(DOC_ID).evaluateAttributeExpressions(flowFile).getValue(); final String docType = context.getProperty(TYPE).evaluateAttributeExpressions(flowFile).getValue(); final String fields = context.getProperty(FIELDS).isSet() ? context.getProperty(FIELDS).evaluateAttributeExpressions(flowFile).getValue() : null; // Authentication final String username = context.getProperty(USERNAME).evaluateAttributeExpressions(flowFile).getValue(); final String password = context.getProperty(PASSWORD).evaluateAttributeExpressions().getValue(); final ComponentLog logger = getLogger(); Response getResponse = null; try { logger.debug("Fetching {}/{}/{} from Elasticsearch", new Object[] { index, docType, docId }); // read the url property from the context final String urlstr = StringUtils .trimToEmpty(context.getProperty(ES_URL).evaluateAttributeExpressions().getValue()); final URL url = buildRequestURL(urlstr, docId, index, docType, fields); final long startNanos = System.nanoTime(); getResponse = sendRequestToElasticsearch(okHttpClient, url, username, password, "GET", null); final int statusCode = getResponse.code(); if (isSuccess(statusCode)) { ResponseBody body = getResponse.body(); final byte[] bodyBytes = body.bytes(); JsonNode responseJson = parseJsonResponse(new ByteArrayInputStream(bodyBytes)); boolean found = responseJson.get("found").asBoolean(false); String retrievedIndex = responseJson.get("_index").asText(); String retrievedType = responseJson.get("_type").asText(); String retrievedId = responseJson.get("_id").asText(); if (found) { JsonNode source = responseJson.get("_source"); flowFile = session.putAttribute(flowFile, "filename", retrievedId); flowFile = session.putAttribute(flowFile, "es.index", retrievedIndex); flowFile = session.putAttribute(flowFile, "es.type", retrievedType); if (source != null) { flowFile = session.write(flowFile, out -> { out.write(source.toString().getBytes()); }); } logger.debug("Elasticsearch document " + retrievedId + " fetched, routing to success"); // emit provenance event final long millis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNanos); if (context.hasNonLoopConnection()) { session.getProvenanceReporter().fetch(flowFile, url.toExternalForm(), millis); } else { session.getProvenanceReporter().receive(flowFile, url.toExternalForm(), millis); } session.transfer(flowFile, REL_SUCCESS); } else { logger.warn("Failed to read {}/{}/{} from Elasticsearch: Document not found", new Object[] { index, docType, docId }); // We couldn't find the document, so send it to "not found" session.transfer(flowFile, REL_NOT_FOUND); } } else { if (statusCode == 404) { logger.warn("Failed to read {}/{}/{} from Elasticsearch: Document not found", new Object[] { index, docType, docId }); // We couldn't find the document, so penalize it and send it to "not found" session.transfer(flowFile, REL_NOT_FOUND); } else { // 5xx -> RETRY, but a server error might last a while, so yield if (statusCode / 100 == 5) { logger.warn( "Elasticsearch returned code {} with message {}, transferring flow file to retry. This is likely a server problem, yielding...", new Object[] { statusCode, getResponse.message() }); session.transfer(flowFile, REL_RETRY); context.yield(); } else if (context.hasIncomingConnection()) { // 1xx, 3xx, 4xx -> NO RETRY logger.warn( "Elasticsearch returned code {} with message {}, transferring flow file to failure", new Object[] { statusCode, getResponse.message() }); session.transfer(flowFile, REL_FAILURE); } else { logger.warn("Elasticsearch returned code {} with message {}", new Object[] { statusCode, getResponse.message() }); session.remove(flowFile); } } } } catch (IOException ioe) { logger.error( "Failed to read from Elasticsearch due to {}, this may indicate an error in configuration " + "(hosts, username/password, etc.). Routing to retry", new Object[] { ioe.getLocalizedMessage() }, ioe); if (context.hasIncomingConnection()) { session.transfer(flowFile, REL_RETRY); } else { session.remove(flowFile); } context.yield(); } catch (Exception e) { logger.error("Failed to read {} from Elasticsearch due to {}", new Object[] { flowFile, e.getLocalizedMessage() }, e); if (context.hasIncomingConnection()) { session.transfer(flowFile, REL_FAILURE); } else { session.remove(flowFile); } context.yield(); } finally { if (getResponse != null) { getResponse.close(); } } }
From source file:org.apache.nifi.processors.elasticsearch.QueryElasticsearchHttp.java
@Override public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException { FlowFile flowFile = null;/* w w w .j av a 2 s .c om*/ if (context.hasIncomingConnection()) { flowFile = session.get(); // If we have no FlowFile, and all incoming connections are self-loops then we can // continue on. // However, if we have no FlowFile and we have connections coming from other Processors, // then // we know that we should run only if we have a FlowFile. if (flowFile == null && context.hasNonLoopConnection()) { return; } } OkHttpClient okHttpClient = getClient(); final String index = context.getProperty(INDEX).evaluateAttributeExpressions(flowFile).getValue(); final String query = context.getProperty(QUERY).evaluateAttributeExpressions(flowFile).getValue(); final String docType = context.getProperty(TYPE).evaluateAttributeExpressions(flowFile).getValue(); final int pageSize = context.getProperty(PAGE_SIZE).evaluateAttributeExpressions(flowFile).asInteger() .intValue(); final Integer limit = context.getProperty(LIMIT).isSet() ? context.getProperty(LIMIT).evaluateAttributeExpressions(flowFile).asInteger().intValue() : null; final String fields = context.getProperty(FIELDS).isSet() ? context.getProperty(FIELDS).evaluateAttributeExpressions(flowFile).getValue() : null; final String sort = context.getProperty(SORT).isSet() ? context.getProperty(SORT).evaluateAttributeExpressions(flowFile).getValue() : null; final boolean targetIsContent = context.getProperty(TARGET).getValue().equals(TARGET_FLOW_FILE_CONTENT); // Authentication final String username = context.getProperty(USERNAME).evaluateAttributeExpressions().getValue(); final String password = context.getProperty(PASSWORD).evaluateAttributeExpressions().getValue(); final ComponentLog logger = getLogger(); int fromIndex = 0; int numResults; try { logger.debug("Querying {}/{} from Elasticsearch: {}", new Object[] { index, docType, query }); final long startNanos = System.nanoTime(); // read the url property from the context final String urlstr = StringUtils .trimToEmpty(context.getProperty(ES_URL).evaluateAttributeExpressions().getValue()); boolean hitLimit = false; do { int mPageSize = pageSize; if (limit != null && limit <= (fromIndex + pageSize)) { mPageSize = limit - fromIndex; hitLimit = true; } final URL queryUrl = buildRequestURL(urlstr, query, index, docType, fields, sort, mPageSize, fromIndex); final Response getResponse = sendRequestToElasticsearch(okHttpClient, queryUrl, username, password, "GET", null); numResults = this.getPage(getResponse, queryUrl, context, session, flowFile, logger, startNanos, targetIsContent); fromIndex += pageSize; getResponse.close(); } while (numResults > 0 && !hitLimit); if (flowFile != null) { session.remove(flowFile); } } catch (IOException ioe) { logger.error( "Failed to read from Elasticsearch due to {}, this may indicate an error in configuration " + "(hosts, username/password, etc.). Routing to retry", new Object[] { ioe.getLocalizedMessage() }, ioe); if (flowFile != null) { session.transfer(flowFile, REL_RETRY); } context.yield(); } catch (RetryableException e) { logger.error(e.getMessage(), new Object[] { e.getLocalizedMessage() }, e); if (flowFile != null) { session.transfer(flowFile, REL_RETRY); } context.yield(); } catch (Exception e) { logger.error("Failed to read {} from Elasticsearch due to {}", new Object[] { flowFile, e.getLocalizedMessage() }, e); if (flowFile != null) { session.transfer(flowFile, REL_FAILURE); } context.yield(); } }
From source file:org.apache.nifi.processors.elasticsearch.ScrollElasticsearchHttp.java
@Override public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException { try {/*from w w w. j a v a 2 s . co m*/ if (isQueryFinished(context.getStateManager())) { getLogger().trace("Query has been marked finished in the state manager. " + "To run another query, clear the state."); return; } } catch (IOException e) { throw new ProcessException("Could not retrieve state", e); } OkHttpClient okHttpClient = getClient(); FlowFile flowFile = session.create(); final String index = context.getProperty(INDEX).evaluateAttributeExpressions(flowFile).getValue(); final String query = context.getProperty(QUERY).evaluateAttributeExpressions(flowFile).getValue(); final String docType = context.getProperty(TYPE).evaluateAttributeExpressions(flowFile).getValue(); final int pageSize = context.getProperty(PAGE_SIZE).evaluateAttributeExpressions(flowFile).asInteger() .intValue(); final String fields = context.getProperty(FIELDS).isSet() ? context.getProperty(FIELDS).evaluateAttributeExpressions(flowFile).getValue() : null; final String sort = context.getProperty(SORT).isSet() ? context.getProperty(SORT).evaluateAttributeExpressions(flowFile).getValue() : null; final String scroll = context.getProperty(SCROLL_DURATION).isSet() ? context.getProperty(SCROLL_DURATION).evaluateAttributeExpressions(flowFile).getValue() : null; // Authentication final String username = context.getProperty(USERNAME).evaluateAttributeExpressions().getValue(); final String password = context.getProperty(PASSWORD).evaluateAttributeExpressions().getValue(); final ComponentLog logger = getLogger(); try { String scrollId = loadScrollId(context.getStateManager()); // read the url property from the context final String urlstr = StringUtils .trimToEmpty(context.getProperty(ES_URL).evaluateAttributeExpressions().getValue()); if (scrollId != null) { final URL scrollurl = buildRequestURL(urlstr, query, index, docType, fields, sort, scrollId, pageSize, scroll); final long startNanos = System.nanoTime(); final Response getResponse = sendRequestToElasticsearch(okHttpClient, scrollurl, username, password, "GET", null); this.getPage(getResponse, scrollurl, context, session, flowFile, logger, startNanos); getResponse.close(); } else { logger.debug("Querying {}/{} from Elasticsearch: {}", new Object[] { index, docType, query }); // read the url property from the context final URL queryUrl = buildRequestURL(urlstr, query, index, docType, fields, sort, scrollId, pageSize, scroll); final long startNanos = System.nanoTime(); final Response getResponse = sendRequestToElasticsearch(okHttpClient, queryUrl, username, password, "GET", null); this.getPage(getResponse, queryUrl, context, session, flowFile, logger, startNanos); getResponse.close(); } } catch (IOException ioe) { logger.error("Failed to read from Elasticsearch due to {}, this may indicate an error in configuration " + "(hosts, username/password, etc.).", new Object[] { ioe.getLocalizedMessage() }, ioe); session.remove(flowFile); context.yield(); } catch (Exception e) { logger.error("Failed to read {} from Elasticsearch due to {}", new Object[] { flowFile, e.getLocalizedMessage() }, e); session.transfer(flowFile, REL_FAILURE); context.yield(); } }
From source file:org.apache.struts2.dispatcher.mapper.CompositeActionMapper.java
@Inject public CompositeActionMapper(Container container, @Inject(value = StrutsConstants.STRUTS_MAPPER_COMPOSITE) String list) { String[] arr = StringUtils.split(StringUtils.trimToEmpty(list), ","); for (String name : arr) { Object obj = container.getInstance(ActionMapper.class, name); if (obj != null) { actionMappers.add((ActionMapper) obj); }//from w ww . jav a 2 s . c o m } }
From source file:org.apache.tika.parser.pdf.EnhancedPDFParser.java
private String getMatchGroup(Matcher m, int group) { return StringEscapeUtils.unescapeHtml4(StringUtils.trimToEmpty(m.group(group))); }
From source file:org.bytesoft.bytejta.logging.SampleTransactionLogger.java
public File getDefaultDirectory() { String address = StringUtils.trimToEmpty(this.endpoint); File directory = new File(String.format("bytejta/%s", address.replaceAll("[^a-zA-Z0-9]", "_"))); if (directory.exists() == false) { try {//from www . j a v a 2 s . c o m directory.mkdirs(); } catch (SecurityException ex) { logger.error("Error occurred while creating directory {}!", directory.getAbsolutePath(), ex); } } return directory; }