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:com.taobao.android.builder.tools.classinject.CodeInjectByJavassist.java

/**
 * jar?/*w  w  w  .  ja v  a  2  s.  c  om*/
 *
 * @param inJar
 * @param outJar
 * @throws IOException
 * @throws NotFoundException
 * @throws CannotCompileException
 */
public static List<String> inject(ClassPool pool, File inJar, File outJar, InjectParam injectParam)
        throws Exception {
    List<String> errorFiles = new ArrayList<String>();
    JarFile jarFile = newJarFile(inJar);

    outJar.getParentFile().mkdirs();
    FileOutputStream fileOutputStream = new FileOutputStream(outJar);
    JarOutputStream jos = new JarOutputStream(new BufferedOutputStream(fileOutputStream));
    Enumeration<JarEntry> jarFileEntries = jarFile.entries();
    JarEntry jarEntry = null;
    while (jarFileEntries.hasMoreElements()) {
        jarEntry = jarFileEntries.nextElement();
        String name = jarEntry.getName();
        String className = StringUtils.replace(name, File.separator, "/");
        className = StringUtils.replace(className, "/", ".");
        className = StringUtils.substring(className, 0, className.length() - 6);
        if (!StringUtils.endsWithIgnoreCase(name, ".class")) {
            InputStream inputStream = jarFile.getInputStream(jarEntry);
            copyStreamToJar(inputStream, jos, name, jarEntry.getTime(), jarEntry);
            IOUtils.closeQuietly(inputStream);
        } else {
            byte[] codes;

            codes = inject(pool, className, injectParam);
            InputStream classInstream = new ByteArrayInputStream(codes);
            copyStreamToJar(classInstream, jos, name, jarEntry.getTime(), jarEntry);

        }
    }
    jarFile.close();
    IOUtils.closeQuietly(jos);
    return errorFiles;
}

From source file:com.oneops.sensor.ws.SensorWsController.java

private void fixTS(CiOpenEvent event) {
    String timestampS = String.valueOf(event.getTimestamp());
    if (StringUtils.length(timestampS) < LENGTH_OF_TIMESTAMP_FOR_TWO_CENTURIES) {
        String timeStamp = StringUtils.rightPad(timestampS, LENGTH_OF_TIMESTAMP_FOR_TWO_CENTURIES, '0');
        logger.info("Corrected TS for  " + event.getName() + "oldTs: " + timestampS + " :correctedValue: "
                + timeStamp);/*w  ww . ja  va 2 s . co  m*/
        event.setTimestamp(Long.valueOf(timeStamp));
    } else if (StringUtils.length(timestampS) > LENGTH_OF_TIMESTAMP_FOR_TWO_CENTURIES) {
        String timeStamp = StringUtils.substring(timestampS, 0, LENGTH_OF_TIMESTAMP_FOR_TWO_CENTURIES);
        event.setTimestamp(Long.valueOf(timeStamp));
        logger.info("Corrected TS for" + event.getName() + " timestamp fixed with " + timeStamp);
    }
}

From source file:de.forsthaus.webui.order.OrderDialogCtrl.java

/**
 * Opens the Dialog window modal./*from  w w  w  .j  a  va2 s .  c  o  m*/
 * 
 * It checks if the dialog opens with a new or existing object and set the
 * readOnly mode accordingly.
 * 
 * @param anOrder
 * @throws InterruptedException
 */
public void doShowDialog(Order anOrder) throws InterruptedException {

    // if anOrder == null then we opened the Dialog without
    // args for a given entity, so we get a new Obj().
    if (anOrder == null) {
        /** !!! DO NOT BREAK THE TIERS !!! */
        // We don't create a new DomainObject() in the frontend.
        // We GET it from the backend.
        anOrder = getOrderService().getNewOrder();
    }

    // set Readonly mode accordingly if the object is new or not.
    if (anOrder.isNew()) {
        btnCtrl.setInitNew();
        doEdit();
    } else {
        btnCtrl.setInitEdit();
        doReadOnly();
    }

    try {
        // fill the components with the data
        if (anOrder.getCustomer() != null) {
            kunNr.setValue(anOrder.getCustomer().getKunNr());
            String substr = anOrder.getCustomer().getKunName1() + " " + anOrder.getCustomer().getKunName2()
                    + ", " + anOrder.getCustomer().getKunOrt();
            substr = StringUtils.substring(substr, 0, 49);
            kunName1.setValue(substr);

        }
        aufNr.setValue(anOrder.getAufNr());
        aufBezeichnung.setValue(anOrder.getAufBezeichnung());

        // stores the inital data for comparing if they are changed
        // during user action.
        doStoreInitValues();

        orderDialogWindow.doModal(); // open the dialog in modal mode
    } catch (final Exception e) {
        Messagebox.show(e.toString());
    }
}

From source file:com.haulmont.cuba.gui.WindowManager.java

protected ComponentLoader createLayout(WindowInfo windowInfo, Element rootElement,
        ComponentLoader.Context context, LayoutLoaderConfig layoutConfig) {
    String descriptorPath = windowInfo.getTemplate();

    LayoutLoader layoutLoader = new LayoutLoader(context, AppConfig.getFactory(), layoutConfig);
    layoutLoader.setLocale(getLocale());
    if (!StringUtils.isEmpty(descriptorPath)) {
        if (descriptorPath.contains("/")) {
            descriptorPath = StringUtils.substring(descriptorPath, 0, descriptorPath.lastIndexOf("/"));
        }//  ww  w.  j  a  v  a 2  s  .  c o m

        String path = descriptorPath.replaceAll("/", ".");
        int start = path.startsWith(".") ? 1 : 0;
        path = path.substring(start);

        layoutLoader.setMessagesPack(path);
    }
    //noinspection UnnecessaryLocalVariable
    ComponentLoader windowLoader = layoutLoader.createWindow(rootElement, windowInfo.getId());
    return windowLoader;
}

From source file:gnete.card.web.merch.MerchAction.java

public String addOldMerch() throws Exception {
    String type = merchInfoReg.getMerchType();
    Assert.notEmpty(type, "?");
    //      this.merchInfoReg.setMerchType(type.substring(0, type.indexOf("|")));
    this.merchInfoReg.setMerchType(StringUtils.substring(type, 0, StringUtils.indexOf(type, "|")));

    //      if (addAdmin == 1) {
    //         UserInfo admin = new UserInfo();
    //         admin.setUserId(this.merchAdmin);
    //         this.merchService.addOldMerch(this.merchInfo, admin, branchCode, this
    //               .getSessionUserCode());
    //      } else {
    //         this.merchService.addOldMerch(this.merchInfo, null, branchCode, this
    //               .getSessionUserCode());
    //      }//from  w ww .java 2s. c om

    this.merchInfoReg.setAdminId(this.merchAdmin);

    this.merchService.addOldMerch(this.merchInfoReg, this.getSessionUser());

    String msg = LogUtils.r("[{0}]?", this.merchInfoReg.getMerchId());
    this.addActionMessage("/pages/merch/regList.do?goBack=goBack", msg);
    this.log(msg, UserLogType.ADD);
    return SUCCESS;
}

From source file:com.mmj.app.common.util.IPTools.java

public Set<String> getCity(String ip) {
    if (StringUtils.isEmpty(ip)) {
        return null;
    }/*from w  w w  .j  a v  a 2  s.c  om*/
    String country = getCountry(ip).equals(" CZ88.NET") ? StringUtils.EMPTY : getCountry(ip);
    Set<String> set = new HashSet<String>();
    int provinceIndex = 0;
    if (country.contains("?")) {
        int index = StringUtils.indexOf(country, "?");
        set.add(StringUtils.substring(country, 0, index));
        set.add(StringUtils.substring(country, 0, index + 1));
        provinceIndex = index + 1;
    }
    if (country.contains("")) {
        int index = StringUtils.indexOf(country, "");
        set.add(StringUtils.substring(country, provinceIndex, index));
        set.add(StringUtils.substring(country, provinceIndex, index + 1));
        String endStr = StringUtils.substring(country, index + 1);
        if (StringUtils.isNotEmpty(endStr)) {
            set.add(endStr);
        }
        if (endStr.contains("")) {
            int end = StringUtils.indexOf(endStr, "");
            set.add(StringUtils.substring(endStr, provinceIndex, end));
            set.add(StringUtils.substring(endStr, provinceIndex, end + 1));
        }
        if (endStr.contains("")) {
            int end = StringUtils.indexOf(endStr, "");
            set.add(StringUtils.substring(endStr, provinceIndex, end));
            set.add(StringUtils.substring(endStr, provinceIndex, end + 1));
        }
    }
    set.add(country);
    return set;
}

From source file:be.solidx.hot.data.rest.RestDataStore.java

protected Object convert(Object value) {
    try {//www.j  a  va2s .c  o m
        return conversionService.convert(value, Long.class);
    } catch (Exception e) {
        try {
            return conversionService.convert(value, Date.class);
        } catch (Exception e1) {
            try {
                return conversionService.convert(value, Boolean.class);
            } catch (Exception e2) {
                try {
                    String decoded = URLDecoder.decode(value.toString(), "utf-8");
                    if (decoded.startsWith("/") && decoded.endsWith("/")) {
                        return new BasicDBObject("$regex", StringUtils.substring(decoded, 1, -1));
                    } else {
                        return decoded;
                    }
                } catch (UnsupportedEncodingException e3) {
                    return value.toString();
                }
            }
        }
    }
}

From source file:com.mmj.app.web.controller.manage.ManageController.java

@RequestMapping(value = "/manage/comments/publish/{topicId}")
public ModelAndView commentsPublish(@PathVariable("topicId") final Long topicId, Integer page) {
    ModelAndView mav = new ModelAndView("manage/comments");
    List<String> menuList = getShowMenuBar(request);
    mav.addObject("menuList", menuList);

    TopicDO topic = topicService.getTopicById(topicId);
    if (topic == null) {
        return mav;
    }//  ww w  . j  a v a2  s .  c  o  m

    CommentsQuery query = new CommentsQuery(null, topicId);
    query.setNowPageIndex(Argument.isNotPositive(page) ? 0 : page - 1);
    query.setSortType(DBSortTypeEnum.GMT_CREATE);

    PaginationList<CommentsDO> list = commentsService.listPagination(query, new IPageUrl() {

        @Override
        public String parsePageUrl(Object... objs) {
            return "/manage/comments/publish/" + topicId + "/" + (Integer) objs[1];
        }
    });
    initUserInfo4List(list);

    String title = topic.getTitle();
    title = StringUtils.substring(title, 0, 10);

    mav.addObject("list", list);
    mav.addObject("publish", "?" + title + "..." + "");
    mav.addObject("source", "comments");
    return mav;
}

From source file:edu.csu.kfs.sciquest.impl.B2BPurchaseOrderServiceImpl.java

/**
 * Generates the Sciquest XML for non-catelog Purchase Order documents
 *
 * @see org.kuali.kfs.module.purap.document.service.B2BPurchaseOrderService#getCxml(org.kuali.kfs.module.purap.document.PurchaseOrderDocument,
 *      org.kuali.rice.kim.bo.Person, String, org.kuali.kfs.vnd.businessobject.ContractManager,
 *      String, String)//  w ww .  ja v a 2  s .  c  o m
 */
@Override
public String getCxml(PurchaseOrderDocument purchaseOrder, String requisitionInitiatorId, String password,
        ContractManager contractManager, String contractManagerEmail, String vendorDuns) {
    StringBuffer cxml = new StringBuffer();

    cxml.append(PREFIX + CsuPurapConstants.MIME_BOUNDARY_FOR_ATTACHMENTS + NEWLINE);
    cxml.append("Content-Type: application/xop+xml;" + NEWLINE);
    cxml.append("\tcharset=\"UTF-8\";" + NEWLINE);
    cxml.append("\ttype=\"text/xml\"" + NEWLINE);
    cxml.append("Content-Transfer-Encoding: 8bit" + NEWLINE);
    cxml.append("Content-ID: <4444711855555.4444160141700455555@sciquest.com>" + NEWLINE + NEWLINE);

    cxml.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + NEWLINE);
    cxml.append("<!DOCTYPE PurchaseOrderMessage SYSTEM \"PO.dtd\">" + NEWLINE);
    cxml.append("<PurchaseOrderMessage version=\"2.0\">" + NEWLINE);
    cxml.append("  <Header>" + NEWLINE);

    // MessageId - can be whatever you would like it to be. Just make it unique.
    cxml.append("    <MessageId>KFS_cXML_PO</MessageId>" + NEWLINE);

    // Timestamp - it doesn't matter what's in the timezone, just that it's there (need "T" space between date/time)
    Date d = SpringContext.getBean(DateTimeService.class).getCurrentDate();
    SimpleDateFormat date = PurApDateFormatUtils
            .getSimpleDateFormat(PurapConstants.NamedDateFormats.CXML_SIMPLE_DATE_FORMAT);
    SimpleDateFormat time = PurApDateFormatUtils
            .getSimpleDateFormat(PurapConstants.NamedDateFormats.CXML_SIMPLE_TIME_FORMAT);
    cxml.append("    <Timestamp>").append(date.format(d)).append("T").append(time.format(d)).append("+05:30")
            .append("</Timestamp>" + NEWLINE);

    cxml.append("    <Authentication>" + NEWLINE);
    cxml.append("      <Identity>ColoState</Identity>" + NEWLINE);
    cxml.append("      <SharedSecret>").append(password).append("</SharedSecret>" + NEWLINE);
    cxml.append("    </Authentication>" + NEWLINE);
    cxml.append("  </Header>" + NEWLINE);
    cxml.append("  <PurchaseOrder>" + NEWLINE);

    KualiWorkflowDocument workFlowDocument = purchaseOrder.getDocumentHeader().getWorkflowDocument();
    String documentType = workFlowDocument.getDocumentType();

    // void = VOPE      ammend = CGIN ?   ammend should =
    if (purchaseOrder.getStatusCode().equals("VOPE") || documentType
            .equalsIgnoreCase(PurapConstants.PurchaseOrderDocTypes.PURCHASE_ORDER_VOID_DOCUMENT)) {
        cxml.append("    <POHeader type=\"cancel\">" + NEWLINE);
        cxml.append("    <DistributeRevision>false</DistributeRevision>" + NEWLINE);
    } else if (documentType.equals(PurapConstants.PurchaseOrderDocTypes.PURCHASE_ORDER_AMENDMENT_DOCUMENT)) {
        cxml.append("    <POHeader type=\"update\">" + NEWLINE);
        cxml.append("    <DistributeRevision>false</DistributeRevision>" + NEWLINE);
    } else {
        cxml.append("    <POHeader>" + NEWLINE);
    }
    cxml.append("      <PONumber>").append(purchaseOrder.getPurapDocumentIdentifier())
            .append("</PONumber>" + NEWLINE);
    cxml.append("      <Requestor>" + NEWLINE);
    cxml.append("        <UserProfile username=\"").append(requisitionInitiatorId.toUpperCase())
            .append("\">" + NEWLINE);
    cxml.append("        </UserProfile>" + NEWLINE);
    cxml.append("      </Requestor>" + NEWLINE);
    cxml.append("      <Priority>High</Priority>" + NEWLINE);
    cxml.append("      <AccountingDate>").append(purchaseOrder.getPurchaseOrderCreateTimestamp())
            .append("</AccountingDate>" + NEWLINE);

    if (PurapConstants.RequisitionSources.B2B.equals(purchaseOrder.getRequisitionSourceCode())) {
        /** *** SUPPLIER SECTION **** */
        cxml.append("      <Supplier>" + NEWLINE);
        cxml.append("        <DUNS>").append(vendorDuns).append("</DUNS>" + NEWLINE);
        cxml.append("        <SupplierNumber>").append(purchaseOrder.getVendorNumber())
                .append("</SupplierNumber>" + NEWLINE);

        // Type attribute is required. Valid values: main and technical. Only main will be considered for POImport.
        cxml.append("        <ContactInfo type=\"main\">" + NEWLINE);
        // TelephoneNumber is required. With all fields, only numeric digits will be stored. Non-numeric characters are allowed, but
        // will be stripped before storing.
        cxml.append("          <Phone>" + NEWLINE);
        cxml.append("            <TelephoneNumber>" + NEWLINE);
        cxml.append("              <CountryCode>1</CountryCode>" + NEWLINE);
        if (contractManager.getContractManagerPhoneNumber().length() > 4) {
            cxml.append("              <AreaCode>")
                    .append(contractManager.getContractManagerPhoneNumber().substring(0, 3))
                    .append("</AreaCode>" + NEWLINE);
            cxml.append("              <Number>")
                    .append(contractManager.getContractManagerPhoneNumber().substring(3))
                    .append("</Number>" + NEWLINE);
        } else {
            LOG.error("getCxml() The phone number is invalid for this contract manager: "
                    + contractManager.getContractManagerUserIdentifier() + " "
                    + contractManager.getContractManagerName());
            cxml.append("              <AreaCode>555</AreaCode>" + NEWLINE);
            cxml.append("              <Number>").append(contractManager.getContractManagerPhoneNumber())
                    .append("</Number>" + NEWLINE);
        }
        cxml.append("            </TelephoneNumber>" + NEWLINE);
        cxml.append("          </Phone>" + NEWLINE);
        cxml.append("        </ContactInfo>" + NEWLINE);
        cxml.append("      </Supplier>" + NEWLINE);
    } else {

        /** *** SUPPLIER SECTION **** */
        cxml.append("      <Supplier>" + NEWLINE);
        cxml.append("        <Name><![CDATA[").append(purchaseOrder.getVendorName())
                .append("]]></Name>" + NEWLINE);

        // Type attribute is required. Valid values: main and technical. Only main will be considered for POImport.
        cxml.append("        <ContactInfo type=\"main\">" + NEWLINE);
        // TelephoneNumber is required. With all fields, only numeric digits will be stored. Non-numeric characters are allowed, but
        // will be stripped before storing.
        cxml.append("          <Phone>" + NEWLINE);
        cxml.append("            <TelephoneNumber>" + NEWLINE);
        cxml.append("              <CountryCode>1</CountryCode>" + NEWLINE);
        if (StringUtils.isNotEmpty(purchaseOrder.getVendorPhoneNumber())
                && purchaseOrder.getVendorPhoneNumber().length() > 4) {
            cxml.append("              <AreaCode>").append(purchaseOrder.getVendorPhoneNumber().substring(0, 3))
                    .append("</AreaCode>" + NEWLINE);
            cxml.append("              <Number>").append(purchaseOrder.getVendorPhoneNumber().substring(3))
                    .append("</Number>" + NEWLINE);
        } else {

            cxml.append("              <AreaCode>000</AreaCode>" + NEWLINE);
            cxml.append("              <Number>-000-0000</Number>" + NEWLINE);
        }

        cxml.append("            </TelephoneNumber>" + NEWLINE);
        cxml.append("          </Phone>" + NEWLINE);

        cxml.append("          <ContactAddress>" + NEWLINE);
        if (StringUtils.isNotEmpty(purchaseOrder.getVendorLine1Address())) {
            cxml.append("          <AddressLine label=\"Street1\" linenumber=\"1\"><![CDATA[")
                    .append(purchaseOrder.getVendorLine1Address()).append("]]></AddressLine>" + NEWLINE);
        }
        if (StringUtils.isNotEmpty(purchaseOrder.getVendorLine2Address())) {
            cxml.append("          <AddressLine label=\"Street2\" linenumber=\"2\"><![CDATA[")
                    .append(purchaseOrder.getVendorLine2Address()).append("]]></AddressLine>" + NEWLINE);
        }
        if (StringUtils.isNotEmpty(purchaseOrder.getVendorStateCode())) {
            cxml.append("          <State>").append(purchaseOrder.getBillingStateCode())
                    .append("</State>" + NEWLINE);
        }
        if (StringUtils.isNotEmpty(purchaseOrder.getVendorPostalCode())) {
            cxml.append("          <PostalCode>").append(purchaseOrder.getBillingPostalCode())
                    .append("</PostalCode>" + NEWLINE);
        }
        if (StringUtils.isNotEmpty(purchaseOrder.getVendorCountryCode())) {
            cxml.append("          <Country isocountrycode=\"").append(purchaseOrder.getBillingCountryCode())
                    .append("\">").append(purchaseOrder.getBillingCountryCode()).append("</Country>" + NEWLINE);
        }
        cxml.append("          </ContactAddress>" + NEWLINE);

        cxml.append("        </ContactInfo>" + NEWLINE);
        cxml.append("      </Supplier>" + NEWLINE);

        /** *** DISTRIBUTION SECTION *** */
        VendorAddress vendorAddress = vendorService.getVendorDefaultAddress(
                purchaseOrder.getVendorDetail().getVendorAddresses(),
                VendorConstants.AddressTypes.PURCHASE_ORDER, purchaseOrder.getDeliveryCampusCode());
        cxml.append("      <OrderDistribution>" + NEWLINE);

        // first take fax from PO, if empty then get fax number for PO default vendor address
        String vendorFaxNumber = purchaseOrder.getVendorFaxNumber();
        if (StringUtils.isBlank(vendorFaxNumber) && vendorAddress != null) {
            vendorFaxNumber = vendorAddress.getVendorFaxNumber();
        }

        // use fax number if not blank, else use vendor email
        if (StringUtils.isNotBlank(vendorFaxNumber) && vendorFaxNumber.length() > 4) {
            cxml.append("        <DistributionMethod type=\"fax\">" + NEWLINE);
            cxml.append("          <Fax>" + NEWLINE);
            cxml.append("            <TelephoneNumber>" + NEWLINE);
            cxml.append("              <CountryCode>1</CountryCode>" + NEWLINE);
            cxml.append("              <AreaCode>").append(vendorFaxNumber.substring(0, 3))
                    .append("</AreaCode>" + NEWLINE);
            cxml.append("              <Number>").append(vendorFaxNumber.substring(3))
                    .append("</Number>" + NEWLINE);
            cxml.append("            </TelephoneNumber>" + NEWLINE);
            cxml.append("          </Fax>" + NEWLINE);
        } else {
            String emailAddress = "";
            if (vendorAddress != null) {
                emailAddress = vendorAddress.getVendorAddressEmailAddress();
            }

            if (StringUtils.isNotBlank(emailAddress)) {
                cxml.append("        <DistributionMethod type=\"email\">" + NEWLINE);
                cxml.append("          <Email><![CDATA[").append(emailAddress).append("]]></Email>" + NEWLINE);
            } else {
                // default fax
                cxml.append("        <DistributionMethod type=\"fax\">" + NEWLINE);
                cxml.append("          <Fax>" + NEWLINE);
                cxml.append("            <TelephoneNumber>" + NEWLINE);
                cxml.append("              <CountryCode>1</CountryCode>" + NEWLINE);
                cxml.append("              <AreaCode>").append(defaultDistributionFaxNumber.substring(0, 3))
                        .append("</AreaCode>" + NEWLINE);
                cxml.append("              <Number>").append(defaultDistributionFaxNumber.substring(3))
                        .append("</Number>" + NEWLINE);
                cxml.append("            </TelephoneNumber>" + NEWLINE);
                cxml.append("          </Fax>" + NEWLINE);
            }
        }
        cxml.append("        </DistributionMethod>" + NEWLINE);
        cxml.append("      </OrderDistribution>" + NEWLINE);
    }

    /** *** BILL TO SECTION **** */
    cxml.append("      <BillTo>" + NEWLINE);
    cxml.append("        <Address>" + NEWLINE);
    cxml.append("          <TemplateName>Bill To</TemplateName>" + NEWLINE);
    cxml.append("          <AddressCode>").append(purchaseOrder.getDeliveryCampusCode())
            .append("</AddressCode>" + NEWLINE);
    // Contact - There can be 0-5 Contact elements. The label attribute is optional.
    cxml.append(
            "          <Contact label=\"FirstName\" linenumber=\"1\"><![CDATA[Accounts]]></Contact>" + NEWLINE);
    cxml.append(
            "          <Contact label=\"LastName\" linenumber=\"2\"><![CDATA[Payable]]></Contact>" + NEWLINE);
    cxml.append("          <Contact label=\"Company\" linenumber=\"3\"><![CDATA[")
            .append(purchaseOrder.getBillingName().trim()).append("]]></Contact>" + NEWLINE);
    cxml.append("          <Contact label=\"Phone\" linenumber=\"4\"><![CDATA[")
            .append(purchaseOrder.getBillingPhoneNumber().trim()).append("]]></Contact>" + NEWLINE);
    // There must be 1-5 AddressLine elements. The label attribute is optional.
    cxml.append("          <AddressLine label=\"Street1\" linenumber=\"1\"><![CDATA[")
            .append(purchaseOrder.getBillingLine1Address()).append("]]></AddressLine>" + NEWLINE);
    cxml.append("          <AddressLine label=\"Street2\" linenumber=\"2\"><![CDATA[")
            .append(purchaseOrder.getBillingLine2Address()).append("]]></AddressLine>" + NEWLINE);
    cxml.append("          <City><![CDATA[").append(purchaseOrder.getBillingCityName())
            .append("]]></City>" + NEWLINE); // Required.
    cxml.append("          <State>").append(purchaseOrder.getBillingStateCode()).append("</State>" + NEWLINE);
    cxml.append("          <PostalCode>").append(purchaseOrder.getBillingPostalCode())
            .append("</PostalCode>" + NEWLINE); // Required.
    cxml.append("          <Country isocountrycode=\"").append(purchaseOrder.getBillingCountryCode())
            .append("\">").append(purchaseOrder.getBillingCountryCode()).append("</Country>" + NEWLINE);
    cxml.append("        </Address>" + NEWLINE);
    cxml.append("      </BillTo>" + NEWLINE);

    /** *** SHIP TO SECTION **** */
    cxml.append("      <ShipTo>" + NEWLINE);
    cxml.append("        <Address>" + NEWLINE);
    cxml.append("          <TemplateName>Ship To</TemplateName>" + NEWLINE);
    // AddressCode. A code to identify the address, that is sent to the supplier.
    cxml.append("          <AddressCode>").append(purchaseOrder.getReceivingName().trim())
            .append("</AddressCode>" + NEWLINE);
    cxml.append("          <Contact label=\"Name\" linenumber=\"1\"><![CDATA[")
            .append(purchaseOrder.getDeliveryToName().trim()).append("]]></Contact>" + NEWLINE);
    cxml.append("          <Contact label=\"PurchasingEmail\" linenumber=\"2\"><![CDATA[")
            .append(contractManagerEmail).append("]]></Contact>" + NEWLINE);
    if (ObjectUtils.isNotNull(purchaseOrder.getInstitutionContactEmailAddress())) {
        cxml.append("          <Contact label=\"ContactEmail\" linenumber=\"3\"><![CDATA[")
                .append(purchaseOrder.getInstitutionContactEmailAddress()).append("]]></Contact>" + NEWLINE);
    } else {
        cxml.append("          <Contact label=\"ContactEmail\" linenumber=\"3\"><![CDATA[")
                .append(purchaseOrder.getRequestorPersonEmailAddress()).append("]]></Contact>" + NEWLINE);
    }
    if (ObjectUtils.isNotNull(purchaseOrder.getInstitutionContactPhoneNumber())) {
        cxml.append("          <Contact label=\"Phone\" linenumber=\"4\"><![CDATA[")
                .append(purchaseOrder.getInstitutionContactPhoneNumber().trim())
                .append("]]></Contact>" + NEWLINE);
    } else {
        cxml.append("          <Contact label=\"Phone\" linenumber=\"4\"><![CDATA[")
                .append(purchaseOrder.getRequestorPersonPhoneNumber()).append("]]></Contact>" + NEWLINE);
    }

    //check indicator to decide if receiving or delivery address should be sent to the vendor
    if (purchaseOrder.getAddressToVendorIndicator()) { //use receiving address
        if (StringUtils.isNotEmpty(purchaseOrder.getDeliveryBuildingName())) {
            cxml.append("          <Contact label=\"Building\" linenumber=\"5\"><![CDATA[")
                    .append(purchaseOrder.getDeliveryBuildingName()).append(" - Rm ")
                    .append(purchaseOrder.getDeliveryBuildingRoomNumber()).append("]]></Contact>" + NEWLINE);
        }
        cxml.append("          <AddressLine label=\"Street1\" linenumber=\"1\"><![CDATA[")
                .append(purchaseOrder.getReceivingName().trim()).append("]]></AddressLine>" + NEWLINE);
        cxml.append("          <AddressLine label=\"Street2\" linenumber=\"2\"><![CDATA[")
                .append(purchaseOrder.getReceivingLine1Address().trim()).append("]]></AddressLine>" + NEWLINE);
        if (ObjectUtils.isNull(purchaseOrder.getReceivingLine2Address())) {
            cxml.append("          <AddressLine label=\"Street3\" linenumber=\"3\"><![CDATA[").append(" ")
                    .append("]]></AddressLine>" + NEWLINE);
        } else {
            cxml.append("          <AddressLine label=\"Street3\" linenumber=\"3\"><![CDATA[")
                    .append(purchaseOrder.getReceivingLine2Address()).append("]]></AddressLine>" + NEWLINE);
        }
        cxml.append("          <City><![CDATA[").append(purchaseOrder.getReceivingCityName().trim())
                .append("]]></City>" + NEWLINE);
        cxml.append("          <State>").append(purchaseOrder.getReceivingStateCode())
                .append("</State>" + NEWLINE);
        cxml.append("          <PostalCode>").append(purchaseOrder.getReceivingPostalCode())
                .append("</PostalCode>" + NEWLINE);
        cxml.append("          <Country isocountrycode=\"").append(purchaseOrder.getReceivingCountryCode())
                .append("\">").append(purchaseOrder.getReceivingCountryCode()).append("</Country>" + NEWLINE);
    } else {
        if (StringUtils.isNotEmpty(purchaseOrder.getDeliveryBuildingName())) {
            cxml.append("          <Contact label=\"Building\" linenumber=\"5\"><![CDATA[")
                    .append(purchaseOrder.getDeliveryBuildingName()).append(" - Rm ")
                    .append(purchaseOrder.getDeliveryBuildingRoomNumber()).append("]]></Contact>" + NEWLINE);
        }
        cxml.append("          <AddressLine label=\"Street1\" linenumber=\"1\"><![CDATA[")
                .append(purchaseOrder.getDeliveryBuildingLine1Address().trim())
                .append("]]></AddressLine>" + NEWLINE);
        cxml.append("          <AddressLine label=\"Street2\" linenumber=\"2\"><![CDATA[Room #")
                .append(purchaseOrder.getDeliveryBuildingRoomNumber().trim())
                .append("]]></AddressLine>" + NEWLINE);
        cxml.append("          <AddressLine label=\"Company\" linenumber=\"4\"><![CDATA[")
                .append(purchaseOrder.getBillingName().trim()).append("]]></AddressLine>" + NEWLINE);
        if (ObjectUtils.isNull(purchaseOrder.getDeliveryBuildingLine2Address())) {
            cxml.append("          <AddressLine label=\"Street3\" linenumber=\"3\"><![CDATA[").append(" ")
                    .append("]]></AddressLine>" + NEWLINE);
        } else {
            cxml.append("          <AddressLine label=\"Street3\" linenumber=\"3\"><![CDATA[")
                    .append(purchaseOrder.getDeliveryBuildingLine2Address())
                    .append("]]></AddressLine>" + NEWLINE);
        }
        cxml.append("          <City><![CDATA[").append(purchaseOrder.getDeliveryCityName().trim())
                .append("]]></City>" + NEWLINE);
        cxml.append("          <State>").append(purchaseOrder.getDeliveryStateCode())
                .append("</State>" + NEWLINE);
        cxml.append("          <PostalCode>").append(purchaseOrder.getDeliveryPostalCode())
                .append("</PostalCode>" + NEWLINE);
        cxml.append("          <Country isocountrycode=\"").append(purchaseOrder.getDeliveryCountryCode())
                .append("\">").append(purchaseOrder.getDeliveryCountryCode()).append("</Country>" + NEWLINE);
    }
    cxml.append("        </Address>" + NEWLINE);
    cxml.append("      </ShipTo>" + NEWLINE);

    // mjmc - Attachments must be defined in the xml part and must match info in MIME binary part
    List<Note> notesToSendToVendor = getNotesToSendToVendor(purchaseOrder);
    if (!notesToSendToVendor.isEmpty()) {
        String allNotes = "";
        String allNotesNoAttach = "";
        cxml.append("      <ExternalInfo >" + NEWLINE);
        cxml.append("        <Attachments xmlns:xop = \"http://www.w3.org/2004/08/xop/include/\" >" + NEWLINE);

        for (int i = 0; i < notesToSendToVendor.size(); i++) {
            Note note = notesToSendToVendor.get(i);
            Attachment attachment = SpringContext.getBean(AttachmentService.class)
                    .getAttachmentByNoteId(note.getNoteIdentifier());
            if (ObjectUtils.isNotNull(attachment)) {
                allNotes = allNotes + NEWLINE + "(" + (i + 1) + ") " + note.getNoteText() + "  ";
                cxml.append("          <Attachment id=\"" + attachment.getAttachmentIdentifier()
                        + "\" type=\"file\">" + NEWLINE);
                cxml.append("            <AttachmentName><![CDATA[" + attachment.getAttachmentFileName()
                        + "]]></AttachmentName>" + NEWLINE);
                cxml.append(
                        "            <AttachmentURL>http://usertest.sciquest.com/apps/Router/ReqAttachmentDownload?AttachmentId="
                                + attachment.getAttachmentIdentifier() + "&amp;DocId="
                                + purchaseOrder.getPurapDocumentIdentifier()
                                + "&amp;OrgName=SQSupportTest&amp;AuthMethod=Local</AttachmentURL>" + NEWLINE);
                cxml.append("            <AttachmentSize>" + attachment.getAttachmentFileSize() / 1024
                        + "</AttachmentSize>" + NEWLINE);
                cxml.append("            <xop:Include href=\"cid:" + attachment.getAttachmentIdentifier()
                        + "@sciquest.com\" />" + NEWLINE);
                cxml.append("          </Attachment>" + NEWLINE);
            } else {
                allNotesNoAttach = allNotesNoAttach + "           " + note.getNoteText() + "          ";
            }
        }
        cxml.append("        </Attachments>" + NEWLINE);
        cxml.append("          <Note><![CDATA[" + allNotesNoAttach + "          " + allNotes + "]]></Note>"
                + NEWLINE);
        cxml.append("      </ExternalInfo>" + NEWLINE);
    } // mjmc done adding attachments

    cxml.append("      <CustomFieldValueSet name=\"SupplierAddress1\">" + NEWLINE);
    cxml.append("        <CustomFieldValue>" + NEWLINE);
    cxml.append("          <Value><![CDATA[").append(purchaseOrder.getVendorLine1Address())
            .append("]]></Value>" + NEWLINE);
    cxml.append("         </CustomFieldValue>" + NEWLINE);
    cxml.append("      </CustomFieldValueSet>" + NEWLINE);
    cxml.append("      <CustomFieldValueSet name=\"SupplierCityStateZip\">" + NEWLINE);
    cxml.append("        <CustomFieldValue>" + NEWLINE);
    cxml.append("          <Value><![CDATA[").append(purchaseOrder.getVendorCityName()).append(", ")
            .append(purchaseOrder.getVendorStateCode()).append(" ").append(purchaseOrder.getVendorPostalCode())
            .append("]]></Value>" + NEWLINE);
    cxml.append("         </CustomFieldValue>" + NEWLINE);
    cxml.append("      </CustomFieldValueSet>" + NEWLINE);
    cxml.append("    </POHeader>" + NEWLINE);

    /** *** Items Section **** */
    List detailList = purchaseOrder.getItems();

    for (Iterator iter = detailList.iterator(); iter.hasNext();) {
        PurchaseOrderItem poi = (PurchaseOrderItem) iter.next();
        if ((ObjectUtils.isNotNull(poi.getItemType())) && poi.getItemType().isLineItemIndicator()) {
            String uom = poi.getItemUnitOfMeasureCode();
            KualiDecimal quantity = poi.getItemQuantity();
            if (quantity == null || quantity.isZero()) {
                quantity = new KualiDecimal(1);
                uom = "LOT";
            }

            cxml.append("    <POLine linenumber=\"").append(poi.getItemLineNumber()).append("\">" + NEWLINE);
            cxml.append("      <Item>" + NEWLINE);
            // CatalogNumber - This is a string that the supplier uses to identify the item (i.e., SKU). Optional.
            cxml.append("        <CatalogNumber><![CDATA[").append(poi.getItemCatalogNumber())
                    .append("]]></CatalogNumber>" + NEWLINE);
            if (ObjectUtils.isNotNull(poi.getItemAuxiliaryPartIdentifier())) {
                cxml.append("        <AuxiliaryCatalogNumber><![CDATA[")
                        .append(poi.getItemAuxiliaryPartIdentifier())
                        .append("]]></AuxiliaryCatalogNumber>" + NEWLINE);
            }
            cxml.append("        <Description><![CDATA[")
                    .append(StringUtils.substring(poi.getItemDescription(), 0, 254))
                    .append("]]></Description>" + NEWLINE); // Required.
            cxml.append(
                    "        <ProductUnitOfMeasure type=\"supplier\"><Measurement><MeasurementValue><![CDATA[")
                    .append(uom)
                    .append("]]></MeasurementValue></Measurement></ProductUnitOfMeasure>" + NEWLINE);
            cxml.append(
                    "        <ProductUnitOfMeasure type=\"system\"><Measurement><MeasurementValue><![CDATA[")
                    .append(uom)
                    .append("]]></MeasurementValue></Measurement></ProductUnitOfMeasure>" + NEWLINE);

            if (PurapConstants.RequisitionSources.B2B.equals(purchaseOrder.getRequisitionSourceCode())) {

                // ProductReferenceNumber - Unique id for hosted products in SelectSite
                if (poi.getExternalOrganizationB2bProductTypeName().equals("Punchout")) {
                    cxml.append("        <ProductReferenceNumber>null</ProductReferenceNumber>\n");
                } else {
                    cxml.append("        <ProductReferenceNumber>")
                            .append(poi.getExternalOrganizationB2bProductReferenceNumber())
                            .append("</ProductReferenceNumber>\n");
                }
                // ProductType - Describes the type of the product or service. Valid values: Catalog, Form, Punchout. Mandatory.
                cxml.append("        <ProductType>").append(poi.getExternalOrganizationB2bProductTypeName())
                        .append("</ProductType>\n");

            } else {

                cxml.append("        <ProductReferenceNumber>null</ProductReferenceNumber>" + NEWLINE);
                // non-catalog POs don't have product type so we send 'Form'
                cxml.append("        <ProductType>Form</ProductType>" + NEWLINE);
            }
            cxml.append("      </Item>" + NEWLINE);
            cxml.append("      <Quantity>").append(quantity).append("</Quantity>" + NEWLINE);
            // LineCharges - All the monetary charges for this line, including the price, tax, shipping, and handling.
            // Required.
            cxml.append("      <LineCharges>" + NEWLINE);
            cxml.append("        <UnitPrice>" + NEWLINE);
            cxml.append("          <Money currency=\"USD\">").append(poi.getItemUnitPrice())
                    .append("</Money>" + NEWLINE);
            cxml.append("        </UnitPrice>" + NEWLINE);
            cxml.append("      </LineCharges>" + NEWLINE);
            cxml.append("    </POLine>" + NEWLINE);
        }

    }

    cxml.append("  </PurchaseOrder>" + NEWLINE);
    cxml.append("</PurchaseOrderMessage>" + NEWLINE);

    LOG.info("getCxml(): cXML for po number " + purchaseOrder.getPurapDocumentIdentifier() + ":" + NEWLINE
            + cxml.toString());

    // mjmc *****************************************************************************************************************
    // mjmc * This is where the attachment gets put into the xml as raw binary data                                         *
    // mjmc *****************************************************************************************************************
    if (!notesToSendToVendor.isEmpty()) {
        for (int i = 0; i < notesToSendToVendor.size(); i++) {
            Note note = notesToSendToVendor.get(i);
            //Attachment poAttachment = note.getAttachment(); // mjmc - doesn't work as of 2010-01
            try {
                Attachment poAttachment = SpringContext.getBean(AttachmentService.class)
                        .getAttachmentByNoteId(note.getNoteIdentifier());
                if (ObjectUtils.isNotNull(poAttachment)) {
                    cxml.append(PREFIX + CsuPurapConstants.MIME_BOUNDARY_FOR_ATTACHMENTS + NEWLINE);
                    cxml.append("Content-Type: application/octet-stream" + NEWLINE);
                    cxml.append("Content-Transfer-Encoding: binary" + NEWLINE);
                    cxml.append("Content-ID: <" + poAttachment.getAttachmentIdentifier() + "@sciquest.com>"
                            + NEWLINE);
                    cxml.append("Content-Disposition: attachment; filename=\""
                            + poAttachment.getAttachmentFileName() + "\"" + NEWLINE + NEWLINE);

                    InputStream attInputStream = poAttachment.getAttachmentContents();
                    ByteArrayOutputStream buffer = new ByteArrayOutputStream();
                    int c;
                    while ((c = attInputStream.read()) != -1)
                        buffer.write(c);
                    String binaryStream = new String(buffer.toByteArray());

                    cxml.append(binaryStream + NEWLINE);
                }

            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        cxml.append(PREFIX + CsuPurapConstants.MIME_BOUNDARY_FOR_ATTACHMENTS + PREFIX + NEWLINE); // signals this is the last MIME boundary
    } else {
        cxml.append(NEWLINE + NEWLINE + PREFIX + CsuPurapConstants.MIME_BOUNDARY_FOR_ATTACHMENTS + PREFIX
                + NEWLINE);
    }

    // mjmc - for testing :
    //        FileOutputStream out;
    //        try {
    //            LOG.info("storing copy of po xml before sending it to sciquest: /tmp/po-" + purchaseOrder.getPurapDocumentIdentifier() + ".xml");
    //            out = new FileOutputStream("/tmp/po-" + purchaseOrder.getPurapDocumentIdentifier() + ".xml");
    //            out.write(cxml.toString().getBytes());           // used for testing with cURL
    //        } catch (IOException e) {
    //            LOG.error(e);
    //        }

    return cxml.toString();
}

From source file:br.com.bropenmaps.util.Util.java

/**
 * Corta o texto no espao mais prximo do limite e acrescenta retecencias.
 * //from   w ww . j a  v  a2s . c o m
 * @param texto
 * @param limite
 * @return
 */
public static String cortaTexto(String texto, Integer limite) {
    texto += " ";
    Integer i = limite;
    if (texto.length() > limite) {
        while (texto.charAt(i) != ' ' && i < texto.length()) {
            i++;
        }
        texto = StringUtils.substring(texto, 0, i) + "...";
    }

    return texto;
}