Example usage for org.apache.commons.lang3 StringUtils trim

List of usage examples for org.apache.commons.lang3 StringUtils trim

Introduction

In this page you can find the example usage for org.apache.commons.lang3 StringUtils trim.

Prototype

public static String trim(final String str) 

Source Link

Document

Removes control characters (char <= 32) from both ends of this String, handling null by returning null .

The String is trimmed using String#trim() .

Usage

From source file:com.webbfontaine.valuewebb.action.fcvr.FCVRSendScheduler.java

private static boolean isFCVRAlreadyExists(String error) {
    return "FCVR Number already exists".equals(StringUtils.trim(error));
}

From source file:ch.cyberduck.core.aquaticprime.ReceiptVerifier.java

@Override
public boolean verify(final LicenseVerifierCallback callback) {
    try {// w ww.j  a  va 2 s  . c o m
        // For additional security, you may verify the fingerprint of the root CA and the OIDs of the
        // intermediate CA and signing certificate. The OID in the Certificate Policies Extension of the
        // intermediate CA is (1 2 840 113635 100 5 6 1), and the Marker OID of the signing certificate
        // is (1 2 840 113635 100 6 11 1).
        final CMSSignedData s = new CMSSignedData(new FileInputStream(file.getAbsolute()));
        Store certs = s.getCertificates();
        SignerInformationStore signers = s.getSignerInfos();
        for (SignerInformation signer : signers.getSigners()) {
            final Collection<X509CertificateHolder> matches = certs.getMatches(signer.getSID());
            for (X509CertificateHolder holder : matches) {
                if (!signer.verify(new JcaSimpleSignerInfoVerifierBuilder()
                        .setProvider(new BouncyCastleProvider()).build(holder))) {
                    return false;
                }
            }
        }
        // Extract the receipt attributes
        final CMSProcessable signedContent = s.getSignedContent();
        byte[] originalContent = (byte[]) signedContent.getContent();
        final ASN1Primitive asn = ASN1Primitive.fromByteArray(originalContent);

        byte[] opaque = null;
        String bundleIdentifier = null;
        String bundleVersion = null;
        byte[] hash = null;

        if (asn instanceof ASN1Set) {
            // 2 Bundle identifier      Interpret as an ASN.1 UTF8STRING.
            // 3 Application version    Interpret as an ASN.1 UTF8STRING.
            // 4 Opaque value           Interpret as a series of bytes.
            // 5 SHA-1 hash             Interpret as a 20-byte SHA-1 digest value.
            final ASN1Set set = (ASN1Set) asn;
            final Enumeration enumeration = set.getObjects();
            while (enumeration.hasMoreElements()) {
                Object next = enumeration.nextElement();
                if (next instanceof DLSequence) {
                    DLSequence sequence = (DLSequence) next;
                    ASN1Encodable type = sequence.getObjectAt(0);
                    if (type instanceof ASN1Integer) {
                        if (((ASN1Integer) type).getValue().intValue() == 2) {
                            final ASN1Encodable value = sequence.getObjectAt(2);
                            if (value instanceof DEROctetString) {
                                bundleIdentifier = new String(((DEROctetString) value).getOctets(), "UTF-8");
                            }
                        } else if (((ASN1Integer) type).getValue().intValue() == 3) {
                            final ASN1Encodable value = sequence.getObjectAt(2);
                            if (value instanceof DEROctetString) {
                                bundleVersion = new String(((DEROctetString) value).getOctets(), "UTF-8");
                            }
                        } else if (((ASN1Integer) type).getValue().intValue() == 4) {
                            final ASN1Encodable value = sequence.getObjectAt(2);
                            if (value instanceof DEROctetString) {
                                opaque = ((DEROctetString) value).getOctets();
                            }
                        } else if (((ASN1Integer) type).getValue().intValue() == 5) {
                            final ASN1Encodable value = sequence.getObjectAt(2);
                            if (value instanceof DEROctetString) {
                                hash = ((DEROctetString) value).getOctets();
                            }
                        }
                    }
                }
            }
        } else {
            log.error(String.format("Expected set of attributes for %s", asn));
            return false;
        }
        if (!StringUtils.equals(application, StringUtils.trim(bundleIdentifier))) {
            log.error(String.format("Bundle identifier %s in ASN set does not match", bundleIdentifier));
            return false;
        }
        if (!StringUtils.equals(version, StringUtils.trim(bundleVersion))) {
            log.warn(String.format("Bundle version %s in ASN set does not match", bundleVersion));
        }
        final NetworkInterface en0 = NetworkInterface.getByName("en0");
        if (null == en0) {
            // Interface is not found when link is down #fail
            log.warn("No network interface en0");
            return true;
        } else {
            final byte[] mac = en0.getHardwareAddress();
            if (null == mac) {
                log.error("Cannot determine MAC address");
                // Continue without validation
                return true;
            }
            final String hex = Hex.encodeHexString(mac);
            if (log.isDebugEnabled()) {
                log.debug(String.format("Interface en0 %s", hex));
            }
            // Compute the hash of the GUID
            final MessageDigest digest = MessageDigest.getInstance("SHA-1");
            digest.update(mac);
            if (null == opaque) {
                log.error(String.format("Missing opaque string in ASN.1 set %s", asn));
                return false;
            }
            digest.update(opaque);
            if (null == bundleIdentifier) {
                log.error(String.format("Missing bundle identifier in ASN.1 set %s", asn));
                return false;
            }
            digest.update(bundleIdentifier.getBytes(Charset.forName("UTF-8")));
            final byte[] result = digest.digest();
            if (Arrays.equals(result, hash)) {
                if (log.isInfoEnabled()) {
                    log.info(String.format("Valid receipt for GUID %s", hex));
                }
                guid = hex;
                return true;
            } else {
                log.error(String.format("Failed verification. Hash with GUID %s does not match hash in receipt",
                        hex));
                return false;
            }
        }
    } catch (IOException | GeneralSecurityException | CMSException | SecurityException e) {
        log.error("Receipt validation error", e);
        // Shutdown if receipt is not valid
        return false;
    } catch (Exception e) {
        log.error("Unknown receipt validation error", e);
        return true;
    }
}

From source file:gov.nih.nci.caintegrator.external.biodbnet.BioDbNetSearchImpl.java

/**
 * Given a label: value string, return the value.
 * @param input the input/*from w w w  . ja  v  a  2 s .  co m*/
 * @return the value
 */
private String getValue(Matcher matcher) {
    String result = StringUtils.EMPTY;
    if (matcher.find()) {
        String[] matchedValue = StringUtils.split(matcher.group(), ':');
        result = StringUtils.trim(matchedValue[1]);
    }
    return result;
}

From source file:com.mirth.connect.model.CodeTemplate.java

@Override
public void migrate3_3_0(DonkeyElement element) {
    element.addChildElement("revision", "1");

    try {//from  w  w w  .  j a va2 s.  c  om
        element.addChildElementFromXml(ObjectXMLSerializer.getInstance().serialize(Calendar.getInstance()))
                .setNodeName("lastModified");
    } catch (DonkeyElementException e) {
        throw new SerializerException("Failed to migrate code template last modified date.", e);
    }

    String type = element.getChildElement("type").getTextContent();
    if (type.equals("CODE") || type.equals("VARIABLE")) {
        element.getChildElement("type").setTextContent("DRAG_AND_DROP_CODE");
    }

    DonkeyElement codeElement = element.getChildElement("code");
    String code = StringUtils.trim(codeElement.getTextContent());
    String toolTip = StringUtils.trim(element.removeChild("tooltip").getTextContent());

    if (StringUtils.isNotBlank(toolTip)) {
        if (code.startsWith("/**")) {
            // Code already has a documentation block, so put the tooltip inside it
            int index = StringUtils.indexOfAnyBut(code.substring(1), '*') + 1;
            StringBuilder builder = new StringBuilder(code.substring(0, index)).append("\n\t")
                    .append(WordUtils.wrap(toolTip, 100, "\n\t", false)).append('\n');
            String remaining = code.substring(index);
            if (StringUtils.indexOfAnyBut(remaining.trim(), '*', '/') == 0) {
                builder.append("\n\t");
            }
            code = builder.append(remaining).toString();
        } else {
            // Add a new documentation block
            code = new StringBuilder("/**\n\t").append(WordUtils.wrap(toolTip, 100, "\n\t", false))
                    .append("\n*/\n").append(code).toString();
        }

        codeElement.setTextContent(code);
    }

    DonkeyElement contextSet = element.addChildElement("contextSet").addChildElement("delegate");

    switch (Integer.parseInt(element.removeChild("scope").getTextContent())) {
    case 0:
    case 1:
        contextSet.addChildElement("contextType", "GLOBAL_DEPLOY");
        contextSet.addChildElement("contextType", "GLOBAL_UNDEPLOY");
        contextSet.addChildElement("contextType", "GLOBAL_PREPROCESSOR");
    case 2:
        contextSet.addChildElement("contextType", "GLOBAL_POSTPROCESSOR");
        contextSet.addChildElement("contextType", "CHANNEL_DEPLOY");
        contextSet.addChildElement("contextType", "CHANNEL_UNDEPLOY");
        contextSet.addChildElement("contextType", "CHANNEL_PREPROCESSOR");
        contextSet.addChildElement("contextType", "CHANNEL_POSTPROCESSOR");
        contextSet.addChildElement("contextType", "CHANNEL_ATTACHMENT");
        contextSet.addChildElement("contextType", "CHANNEL_BATCH");
    case 3:
        contextSet.addChildElement("contextType", "SOURCE_RECEIVER");
        contextSet.addChildElement("contextType", "SOURCE_FILTER_TRANSFORMER");
        contextSet.addChildElement("contextType", "DESTINATION_FILTER_TRANSFORMER");
        contextSet.addChildElement("contextType", "DESTINATION_DISPATCHER");
        contextSet.addChildElement("contextType", "DESTINATION_RESPONSE_TRANSFORMER");
    }
}

From source file:com.webbfontaine.valuewebb.action.fcvr.FCVRSendScheduler.java

private static boolean isAccessProblem(String error) {
    return StringUtils.trim(error).toLowerCase().contains("access denied to binder");
}

From source file:com.sonicle.webtop.core.versioning.SqlUpgradeScript.java

private void readFile(InputStreamReader readable, boolean flatNewLines) throws IOException {
    this.statements = new ArrayList<>();
    StringBuilder sb = null, sbsql = null;
    String lines[] = null;/*from w  ww .ja v  a2  s . c o m*/

    Scanner s = new Scanner(readable);
    s.useDelimiter("(;( )?(\r)?\n)");
    //s.useDelimiter("(;( )?(\r)?\n)|(--\n)");
    while (s.hasNext()) {
        String block = s.next();
        block = StringUtils.replace(block, "\r", "");
        if (!StringUtils.isEmpty(block)) {
            // Remove remaining ; at the end of the block (only if this block is the last one)
            if (!s.hasNext() && StringUtils.endsWith(block, ";"))
                block = StringUtils.left(block, block.length() - 1);

            sb = new StringBuilder();
            sbsql = new StringBuilder();
            lines = StringUtils.split(block, "\n");
            for (String line : lines) {
                if (AnnotationLine.matches(line)) {
                    if (DataSourceAnnotationLine.matches(line)) {
                        statements.add(new DataSourceAnnotationLine(line));
                    } else if (IgnoreErrorsAnnotationLine.matches(line)) {
                        statements.add(new IgnoreErrorsAnnotationLine(line));
                    } else if (RequireAdminAnnotationLine.matches(line)) {
                        statements.add(new RequireAdminAnnotationLine(line));
                    } else {
                        throw new IOException("Bad line: " + line);
                    }
                } else if (CommentLine.matches(line)) {
                    sb.append(line);
                    sb.append("\n");
                } else {
                    sbsql.append(StringUtils.trim(line));
                    sbsql.append(" ");
                    if (!flatNewLines)
                        sbsql.append("\n");
                }
            }
            if (sb.length() > 0)
                statements.add(new CommentLine(StringUtils.removeEnd(sb.toString(), "\n")));
            if (sbsql.length() > 0)
                statements.add(new SqlLine(StringUtils.removeEnd(sbsql.toString(), "\n")));
        }
    }
}

From source file:com.intuit.karate.StepDefs.java

@When("^table (.+) =$")
public void table(String name, DataTable table) {
    DocumentContext doc = toJson(table);
    name = StringUtils.trim(name);
    context.vars.put(name, doc);
}

From source file:controllers.ImportApp.java

private static ValidationResult validateForm(Form<Project> newProjectForm, Organization organization,
        User user) {/*from  ww  w.  java2  s .  co  m*/
    boolean hasError = false;
    Result result = null;

    List<OrganizationUser> orgUserList = OrganizationUser.findByAdmin(UserApp.currentUser().id);

    String owner = newProjectForm.field("owner").value();
    String name = newProjectForm.field("name").value();
    boolean ownerIsUser = User.isLoginIdExist(owner);
    boolean ownerIsOrganization = Organization.isNameExist(owner);

    if (!ownerIsUser && !ownerIsOrganization) {
        newProjectForm.reject("owner", "project.owner.invalidate");
        hasError = true;
        result = badRequest(create.render("title.newProject", newProjectForm, orgUserList));
    }

    if (ownerIsUser && UserApp.currentUser().id != user.id) {
        newProjectForm.reject("owner", "project.owner.invalidate");
        hasError = true;
        result = badRequest(create.render("title.newProject", newProjectForm, orgUserList));
    }

    if (ownerIsOrganization && !OrganizationUser.isAdmin(organization.id, UserApp.currentUser().id)) {
        hasError = true;
        result = forbidden(
                ErrorViews.Forbidden.render("'" + UserApp.currentUser().name + "' has no permission"));
    }

    if (Project.exists(owner, name)) {
        newProjectForm.reject("name", "project.name.duplicate");
        hasError = true;
        result = badRequest(importing.render("title.newProject", newProjectForm, orgUserList));
    }

    String gitUrl = StringUtils.trim(newProjectForm.data().get("url"));
    if (StringUtils.isBlank(gitUrl)) {
        newProjectForm.reject("url", "project.import.error.empty.url");
        hasError = true;
        result = badRequest(importing.render("title.newProject", newProjectForm, orgUserList));
    }

    if (newProjectForm.hasErrors()) {
        newProjectForm.reject("name", "project.name.alert");
        hasError = true;
        result = badRequest(importing.render("title.newProject", newProjectForm, orgUserList));
    }

    return new ValidationResult(result, hasError);
}

From source file:com.thinkbiganalytics.feedmgr.service.feed.datasource.DerivedDatasourceFactory.java

/**
 * Builds the list of data sources for the specified data transformation feed.
 *
 * @param feed the feed//from w  w  w  .  j ava  2s  .  c om
 * @return the list of data sources
 */
@Nonnull
private Set<Datasource.ID> ensureDataTransformationSourceDatasources(@Nonnull final FeedMetadata feed) {
    // Build the data sources from the view model
    final Set<Datasource.ID> datasources = new HashSet<>();
    final Set<String> tableNames = Optional.ofNullable(feed.getDataTransformation())
            .map(FeedDataTransformation::getTableNamesFromViewModel).orElse(Collections.emptySet());

    if (!tableNames.isEmpty()) {
        DatasourceDefinition datasourceDefinition = datasourceDefinitionProvider
                .findByProcessorType(DATA_TRANSFORMATION_DEFINITION);
        if (datasourceDefinition != null) {
            tableNames.forEach(hiveTable -> {
                String schema = StringUtils.trim(StringUtils.substringBefore(hiveTable, "."));
                String table = StringUtils.trim(StringUtils.substringAfterLast(hiveTable, "."));
                String identityString = datasourceDefinition.getIdentityString();
                Map<String, String> props = new HashMap<String, String>();
                props.put("schema", schema);
                props.put("table", table);
                identityString = propertyExpressionResolver.resolveVariables(identityString, props);
                String desc = datasourceDefinition.getDescription();
                if (desc != null) {
                    desc = propertyExpressionResolver.resolveVariables(desc, props);
                }
                String title = identityString;

                DerivedDatasource derivedDatasource = datasourceProvider.ensureDerivedDatasource(
                        datasourceDefinition.getDatasourceType(), identityString, title, desc,
                        new HashMap<String, Object>(props));
                if (derivedDatasource != null) {
                    datasources.add(derivedDatasource.getId());
                }
            });
        }
    }

    // Build the data sources from the data source ids
    final List<String> datasourceIds = Optional.ofNullable(feed.getDataTransformation())
            .map(FeedDataTransformation::getDatasourceIds).orElse(Collections.emptyList());
    datasourceIds.stream().map(datasourceProvider::resolve).forEach(datasources::add);

    return datasources;
}

From source file:com.thinkbiganalytics.alerts.spi.defaults.KyloEntityAwareAlertCriteria.java

private BooleanBuilder orFilter(QJpaAlert alert, QJpaOpsManagerFeed feed,
        QJpaServiceLevelAgreementDescription sla) {
    BooleanBuilder globalFilter = new BooleanBuilder();
    if (StringUtils.isNotBlank(getOrFilter())) {
        Lists.newArrayList(StringUtils.split(getOrFilter(), ",")).stream().forEach(filter -> {
            filter = StringUtils.trim(filter);
            if (filter != null) {
                List<String> in = null;
                if (filter.contains("||")) {
                    //replace the OR || with commas for IN clause
                    in = Arrays.asList(StringUtils.split(filter, "||")).stream().map(f -> StringUtils.trim(f))
                            .collect(Collectors.toList());
                    filter = in.stream().collect(Collectors.joining(","));
                }//from www.j ava2s .c o  m
                BooleanBuilder booleanBuilder = new BooleanBuilder();
                List<Predicate> preds = new ArrayList<>();
                try {
                    Alert.State state = Alert.State.valueOf(filter.toUpperCase());
                    preds.add(alert.state.eq(state));
                } catch (IllegalArgumentException e) {

                }
                if (in != null) {
                    preds.add(alert.description.in(in));
                    preds.add(alert.entityType.in(in));
                    preds.add(alert.typeString.in(in));
                    preds.add(alert.subtype.in(in));
                    //add in joins on the feed or sla name
                    addOrFilter(feed, CommonFilterTranslations.feedFilters, preds, filter);
                    addOrFilter(sla, KyloEntityAwareAlertManager.alertSlaFilters, preds, filter);
                } else {
                    preds.add(alert.description.likeIgnoreCase(filter.concat("%")));
                    preds.add(alert.entityType.likeIgnoreCase(filter.concat("%")));
                    preds.add(alert.typeString.likeIgnoreCase(filter.concat("%")));
                    preds.add(alert.subtype.like(filter.concat("%")));
                    //add in joins on the feed or sla name
                    addOrFilter(feed, CommonFilterTranslations.feedFilters, preds, filter);
                    addOrFilter(sla, KyloEntityAwareAlertManager.alertSlaFilters, preds, filter);

                }

                booleanBuilder.andAnyOf(preds.toArray(new Predicate[preds.size()]));
                globalFilter.and(booleanBuilder);
            }
        });

    }
    return globalFilter;
}