Example usage for org.apache.commons.lang StringUtils substring

List of usage examples for org.apache.commons.lang StringUtils substring

Introduction

In this page you can find the example usage for org.apache.commons.lang StringUtils substring.

Prototype

public static String substring(String str, int start, int end) 

Source Link

Document

Gets a substring from the specified String avoiding exceptions.

Usage

From source file:org.apache.ambari.msi.ClusterDefinition.java

/**
 * Get the major stack version for this cluster.
 *
 * @return the major stack version//from   ww  w.  ja v a2  s .c o m
 */
public Integer getMajorStackVersion() {
    if (StringUtils.isNotEmpty(versionId)) {
        String majorVersion = StringUtils.substring(versionId, 4, 5);
        if (StringUtils.isNotEmpty(majorVersion)) {
            return Integer.parseInt(majorVersion);
        }
    }
    return null;
}

From source file:org.apache.ambari.msi.ClusterDefinition.java

/**
 * Get the minor stack version for this cluster.
 *
 * @return the minor stack version/*www  .j ava 2  s  . com*/
 */
public Integer getMinorStackVersion() {
    if (StringUtils.isNotEmpty(versionId)) {
        String majorVersion = StringUtils.substring(versionId, 6, 7);
        if (StringUtils.isNotEmpty(majorVersion)) {
            return Integer.parseInt(majorVersion);
        }
    }
    return null;
}

From source file:org.apache.archiva.repository.content.maven2.RepositoryRequest.java

public boolean isMetadataSupportFile(String requestedPath) {
    if (isSupportFile(requestedPath)) {
        String basefilePath = StringUtils.substring(requestedPath, 0, requestedPath.lastIndexOf('.'));
        if (isMetadata(basefilePath)) {
            return true;
        }//from ww w  .  ja va  2 s .c o  m
    }

    return false;
}

From source file:org.apache.cloudstack.api.command.LdapImportUsersCmd.java

private Domain getDomainForName(String name) {
    Domain domain = null;// w w w  .  j  a v  a  2 s .c om
    if (StringUtils.isNotBlank(name)) {
        //removing all the special characters and trimming its length to 190 to make the domain valid.
        String domainName = StringUtils.substring(name.replaceAll("\\W", ""), 0, 190);
        if (StringUtils.isNotBlank(domainName)) {
            domain = _domainService.getDomainByName(domainName, Domain.ROOT_DOMAIN);
            if (domain == null) {
                domain = _domainService.createDomain(domainName, Domain.ROOT_DOMAIN, domainName,
                        UUID.randomUUID().toString());
            }
        }
    }
    return domain;
}

From source file:org.apache.nutch.util.DumpFileUtil.java

public static String createFileName(String md5, String fileBaseName, String fileExtension) {
    if (fileBaseName.length() > MAX_LENGTH_OF_FILENAME) {
        LOG.info("File name is too long. Truncated to {} characters.", MAX_LENGTH_OF_FILENAME);
        fileBaseName = StringUtils.substring(fileBaseName, 0, MAX_LENGTH_OF_FILENAME);
    }/* w w w  .java 2s .c  o m*/

    if (fileExtension.length() > MAX_LENGTH_OF_EXTENSION) {
        LOG.info("File extension is too long. Truncated to {} characters.", MAX_LENGTH_OF_EXTENSION);
        fileExtension = StringUtils.substring(fileExtension, 0, MAX_LENGTH_OF_EXTENSION);
    }

    // Added to prevent FileNotFoundException (Invalid Argument) - in *nix environment
    fileBaseName = fileBaseName.replaceAll("\\?", "");
    fileExtension = fileExtension.replaceAll("\\?", "");

    return String.format(FILENAME_PATTERN, md5, fileBaseName, fileExtension);
}

From source file:org.apache.nutch.util.DumpFileUtil.java

public static String createFileNameFromUrl(String basePath, String reverseKey, String urlString,
        String epochScrapeTime, String fileExtension, boolean makeDir) {
    String fullDirPath = basePath + File.separator + reverseKey + File.separator
            + DigestUtils.sha1Hex(urlString);

    if (makeDir) {
        try {/*w  w w . j av a2  s  . com*/
            FileUtils.forceMkdir(new File(fullDirPath));
        } catch (IOException e) {
            LOG.error("Failed to create dir: {}", fullDirPath);
            fullDirPath = null;
        }
    }

    if (fileExtension.length() > MAX_LENGTH_OF_EXTENSION) {
        LOG.info("File extension is too long. Truncated to {} characters.", MAX_LENGTH_OF_EXTENSION);
        fileExtension = StringUtils.substring(fileExtension, 0, MAX_LENGTH_OF_EXTENSION);
    }

    String outputFullPath = fullDirPath + File.separator + epochScrapeTime + "." + fileExtension;

    return outputFullPath;
}

From source file:org.apache.ofbiz.service.job.PersistedServiceJob.java

@Override
protected void finish(Map<String, Object> result) throws InvalidJobException {
    super.finish(result);
    // set the finish date
    jobValue.set("statusId", "SERVICE_FINISHED");
    jobValue.set("finishDateTime", UtilDateTime.nowTimestamp());
    String jobResult = null;// w  w  w  .  ja  v a  2s . c  o  m
    if (ServiceUtil.isError(result)) {
        jobResult = StringUtils.substring(ServiceUtil.getErrorMessage(result), 0, 255);
    } else {
        jobResult = StringUtils.substring(ServiceUtil.makeSuccessMessage(result, "", "", "", ""), 0, 255);
    }
    if (UtilValidate.isNotEmpty(jobResult)) {
        jobValue.set("jobResult", jobResult);
    }
    try {
        jobValue.store();
    } catch (GenericEntityException e) {
        Debug.logError(e, "Cannot update the job [" + getJobId() + "] sandbox", module);
    }
}

From source file:org.apache.ofbiz.service.job.PersistedServiceJob.java

@Override
protected void failed(Throwable t) throws InvalidJobException {
    super.failed(t);
    // if the job has not been re-scheduled; we need to re-schedule and run again
    if (nextRecurrence == -1) {
        if (this.canRetry()) {
            // create a recurrence
            Calendar cal = Calendar.getInstance();
            try {
                cal.add(Calendar.MINUTE,
                        ServiceConfigUtil.getServiceEngine().getThreadPool().getFailedRetryMin());
            } catch (GenericConfigException e) {
                Debug.logWarning(e,//  ww  w.  ja  va 2  s. c  o m
                        "Unable to get retry minutes for job [" + getJobId() + "], defaulting to now: ",
                        module);
            }
            long next = cal.getTimeInMillis();
            try {
                createRecurrence(next, true);
            } catch (GenericEntityException e) {
                Debug.logError(e, "Unable to re-schedule job [" + getJobId() + "]: ", module);
            }
            Debug.logInfo("Persisted Job [" + getJobId() + "] Failed. Re-Scheduling : " + next, module);
        } else {
            Debug.logWarning("Persisted Job [" + getJobId() + "] Failed. Max Retry Hit, not re-scheduling",
                    module);
        }
    }
    // set the failed status
    jobValue.set("statusId", "SERVICE_FAILED");
    jobValue.set("finishDateTime", UtilDateTime.nowTimestamp());
    jobValue.set("jobResult", StringUtils.substring(t.getMessage(), 0, 255));
    try {
        jobValue.store();
    } catch (GenericEntityException e) {
        Debug.logError(e, "Cannot update the JobSandbox entity", module);
    }
}

From source file:org.apache.ofbiz.shipment.thirdparty.usps.UspsServices.java

public static Map<String, Object> uspsRateInquire(DispatchContext dctx, Map<String, ? extends Object> context) {
    Delegator delegator = dctx.getDelegator();
    String shipmentGatewayConfigId = (String) context.get("shipmentGatewayConfigId");
    String resource = (String) context.get("configProps");
    Locale locale = (Locale) context.get("locale");

    // check for 0 weight
    BigDecimal shippableWeight = (BigDecimal) context.get("shippableWeight");
    if (shippableWeight.compareTo(BigDecimal.ZERO) == 0) {
        // TODO: should we return an error, or $0.00 ?
        return ServiceUtil.returnFailure(UtilProperties.getMessage(resourceError,
                "FacilityShipmentUspsShippableWeightMustGreaterThanZero", locale));
    }/*from  w w w .j  a v a  2  s .  c  om*/

    // get the origination ZIP
    String originationZip = null;
    GenericValue productStore = ProductStoreWorker.getProductStore(((String) context.get("productStoreId")),
            delegator);
    if (productStore != null && productStore.get("inventoryFacilityId") != null) {
        GenericValue facilityContactMech = ContactMechWorker.getFacilityContactMechByPurpose(delegator,
                productStore.getString("inventoryFacilityId"),
                UtilMisc.toList("SHIP_ORIG_LOCATION", "PRIMARY_LOCATION"));
        if (facilityContactMech != null) {
            try {
                GenericValue shipFromAddress = EntityQuery.use(delegator).from("PostalAddress")
                        .where("contactMechId", facilityContactMech.getString("contactMechId")).queryOne();
                if (shipFromAddress != null) {
                    originationZip = shipFromAddress.getString("postalCode");
                }
            } catch (GenericEntityException e) {
                Debug.logError(e, module);
            }
        }
    }
    if (UtilValidate.isEmpty(originationZip)) {
        return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                "FacilityShipmentUspsUnableDetermineOriginationZip", locale));
    }

    // get the destination ZIP
    String destinationZip = null;
    String shippingContactMechId = (String) context.get("shippingContactMechId");
    if (UtilValidate.isNotEmpty(shippingContactMechId)) {
        try {
            GenericValue shipToAddress = EntityQuery.use(delegator).from("PostalAddress")
                    .where("contactMechId", shippingContactMechId).queryOne();
            if (shipToAddress != null) {
                if (!domesticCountries.contains(shipToAddress.getString("countryGeoId"))) {
                    return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                            "FacilityShipmentUspsRateInquiryOnlyInUsDestinations", locale));
                }
                destinationZip = shipToAddress.getString("postalCode");
            }
        } catch (GenericEntityException e) {
            Debug.logError(e, module);
        }
    }
    if (UtilValidate.isEmpty(destinationZip)) {
        return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                "FacilityShipmentUspsUnableDetermineDestinationZip", locale));
    }

    // get the service code
    String serviceCode = null;
    try {
        GenericValue carrierShipmentMethod = EntityQuery.use(delegator).from("CarrierShipmentMethod")
                .where("shipmentMethodTypeId", (String) context.get("shipmentMethodTypeId"), "partyId",
                        (String) context.get("carrierPartyId"), "roleTypeId",
                        (String) context.get("carrierRoleTypeId"))
                .queryOne();
        if (carrierShipmentMethod != null) {
            serviceCode = carrierShipmentMethod.getString("carrierServiceCode").toUpperCase();
        }
    } catch (GenericEntityException e) {
        Debug.logError(e, module);
    }
    if (UtilValidate.isEmpty(serviceCode)) {
        return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                "FacilityShipmentUspsUnableDetermineServiceCode", locale));
    }

    // create the request document
    Document requestDocument = createUspsRequestDocument("RateV2Request", true, delegator,
            shipmentGatewayConfigId, resource);

    // TODO: 70 lb max is valid for Express, Priority and Parcel only - handle other methods
    BigDecimal maxWeight = new BigDecimal("70");
    String maxWeightStr = getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, "maxEstimateWeight",
            resource, "shipment.usps.max.estimate.weight", "70");
    try {
        maxWeight = new BigDecimal(maxWeightStr);
    } catch (NumberFormatException e) {
        Debug.logWarning(
                "Error parsing max estimate weight string [" + maxWeightStr + "], using default instead",
                module);
        maxWeight = new BigDecimal("70");
    }

    List<Map<String, Object>> shippableItemInfo = UtilGenerics.checkList(context.get("shippableItemInfo"));
    List<Map<String, BigDecimal>> packages = ShipmentWorker.getPackageSplit(dctx, shippableItemInfo, maxWeight);
    boolean isOnePackage = packages.size() == 1; // use shippableWeight if there's only one package
    // TODO: Up to 25 packages can be included per request - handle more than 25
    for (ListIterator<Map<String, BigDecimal>> li = packages.listIterator(); li.hasNext();) {
        Map<String, BigDecimal> packageMap = li.next();

        BigDecimal packageWeight = isOnePackage ? shippableWeight
                : ShipmentWorker.calcPackageWeight(dctx, packageMap, shippableItemInfo, BigDecimal.ZERO);
        if (packageWeight.compareTo(BigDecimal.ZERO) == 0) {
            continue;
        }

        Element packageElement = UtilXml.addChildElement(requestDocument.getDocumentElement(), "Package",
                requestDocument);
        packageElement.setAttribute("ID", String.valueOf(li.nextIndex() - 1)); // use zero-based index (see examples)

        UtilXml.addChildElementValue(packageElement, "Service", serviceCode, requestDocument);
        UtilXml.addChildElementValue(packageElement, "ZipOrigination",
                StringUtils.substring(originationZip, 0, 5), requestDocument);
        UtilXml.addChildElementValue(packageElement, "ZipDestination",
                StringUtils.substring(destinationZip, 0, 5), requestDocument);

        BigDecimal weightPounds = packageWeight.setScale(0, BigDecimal.ROUND_FLOOR);
        // for Parcel post, the weight must be at least 1 lb
        if ("PARCEL".equals(serviceCode.toUpperCase()) && (weightPounds.compareTo(BigDecimal.ONE) < 0)) {
            weightPounds = BigDecimal.ONE;
            packageWeight = BigDecimal.ZERO;
        }
        // (packageWeight % 1) * 16 (Rounded up to 0 dp)
        BigDecimal weightOunces = packageWeight.remainder(BigDecimal.ONE).multiply(new BigDecimal("16"))
                .setScale(0, BigDecimal.ROUND_CEILING);

        UtilXml.addChildElementValue(packageElement, "Pounds", weightPounds.toPlainString(), requestDocument);
        UtilXml.addChildElementValue(packageElement, "Ounces", weightOunces.toPlainString(), requestDocument);

        // TODO: handle other container types, package sizes, and machinable packages
        // IMPORTANT: Express or Priority Mail will fail if you supply a Container tag: you will get a message like
        // Invalid container type. Valid container types for Priority Mail are Flat Rate Envelope and Flat Rate Box.
        /* This is an official response from the United States Postal Service:
        The <Container> tag is used to specify the flat rate mailing options, or the type of large or oversized package being mailed.
        If you are wanting to get regular Express Mail rates, leave the <Container> tag empty, or do not include it in the request at all.
         */
        if ("Parcel".equalsIgnoreCase(serviceCode)) {
            UtilXml.addChildElementValue(packageElement, "Container", "None", requestDocument);
        }
        UtilXml.addChildElementValue(packageElement, "Size", "REGULAR", requestDocument);
        UtilXml.addChildElementValue(packageElement, "Machinable", "false", requestDocument);
    }

    // send the request
    Document responseDocument = null;
    try {
        responseDocument = sendUspsRequest("RateV2", requestDocument, delegator, shipmentGatewayConfigId,
                resource, locale);
    } catch (UspsRequestException e) {
        Debug.logInfo(e, module);
        return ServiceUtil.returnError(
                UtilProperties.getMessage(resourceError, "FacilityShipmentUspsRateDomesticSendingError",
                        UtilMisc.toMap("errorString", e.getMessage()), locale));
    }

    if (responseDocument == null) {
        return ServiceUtil.returnError(
                UtilProperties.getMessage(resourceError, "FacilityShipmentRateNotAvailable", locale));
    }

    List<? extends Element> rates = UtilXml.childElementList(responseDocument.getDocumentElement(), "Package");
    if (UtilValidate.isEmpty(rates)) {
        return ServiceUtil.returnError(
                UtilProperties.getMessage(resourceError, "FacilityShipmentRateNotAvailable", locale));
    }

    BigDecimal estimateAmount = BigDecimal.ZERO;
    for (Element packageElement : rates) {
        try {
            Element postageElement = UtilXml.firstChildElement(packageElement, "Postage");
            BigDecimal packageAmount = new BigDecimal(UtilXml.childElementValue(postageElement, "Rate"));
            estimateAmount = estimateAmount.add(packageAmount);
        } catch (NumberFormatException e) {
            Debug.logInfo(e, module);
        }
    }

    Map<String, Object> result = ServiceUtil.returnSuccess();
    result.put("shippingEstimateAmount", estimateAmount);
    return result;
}

From source file:org.apache.oodt.cas.protocol.ProtocolFile.java

/**
 * Gets the parent {@link ProtocolFile} for this path.
 * /*from   www  .j  a  v a2  s  .c o  m*/
 * @return The parent {@link ProtocolFile}
 */
public ProtocolFile getParent() {
    if (parent != null) {
        return parent;
    } else {
        int index = StringUtils.lastIndexOf(path, SEPARATOR);
        return (index > 0) ? new ProtocolFile(StringUtils.substring(path, 0, index), true) : null;
    }
}