Example usage for java.lang StringBuffer insert

List of usage examples for java.lang StringBuffer insert

Introduction

In this page you can find the example usage for java.lang StringBuffer insert.

Prototype

@Override
public StringBuffer insert(int offset, double d) 

Source Link

Usage

From source file:org.dspace.browse.BrowseDAOOracle.java

/**
 * Build the query that will be used for a distinct select.  This incorporates
 * only the parts of the parameters that are actually useful for this type
 * of browse//w  w  w  . j a v a 2 s .  co m
 *
 * @return      the query to be executed
 * @throws BrowseException
 */
private String buildDistinctQuery(List<Serializable> params) throws BrowseException {
    StringBuffer queryBuf = new StringBuffer();

    if (!buildSelectListCount(queryBuf)) {
        if (!buildSelectListValues(queryBuf)) {
            throw new BrowseException("No arguments for SELECT statement");
        }
    }

    buildSelectStatementDistinct(queryBuf, params);
    buildWhereClauseOpReset();

    // assemble the focus clase if we are to have one
    // it will look like one of the following, for example
    //     sort_value <= myvalue
    //     sort_1 >= myvalue
    buildWhereClauseJumpTo(queryBuf, params);

    // assemble the where clause out of the two possible value clauses
    // and include container support
    buildWhereClauseDistinctConstraints(queryBuf, params);

    // assemble the order by field
    buildOrderBy(queryBuf);

    // prepare the limit and offset clauses
    buildRowLimitAndOffset(queryBuf, params);

    //If we want frequencies and this is not a count query, enchance the query accordingly
    if (isEnableBrowseFrequencies() && countValues == null) {
        String before = "SELECT count(*) AS num, dvalues.value, dvalues.authority FROM (";
        String after = ") dvalues , " + tableMap + " WHERE dvalues.id = " + tableMap + ".distinct_id GROUP BY "
                + tableMap + ".distinct_id, dvalues.value, dvalues.authority, dvalues.sort_value";

        queryBuf.insert(0, before);
        queryBuf.append(after);
        buildOrderBy(queryBuf);
    }

    return queryBuf.toString();
}

From source file:com.ephesoft.dcma.filebound.FileBoundExporter.java

/**
 * This method reads the batch.xml file. It finds the names of multi page tif and pdf files from the batch.xml. Then it upload these
 * files to the repository main root folder. At a time it will upload only pdf or tif files.
 * //from  ww w  .  ja  v a 2s. c  o m
 * 
 * @param batchInstanceIdentifier {@link String}
 * @throws JAXBException root exception class for all JAXB exceptions
 * @throws DCMAApplicationException If not able to upload files to repository server. If invalid input parameters.
 */
public void exportFiles(final String batchInstanceIdentifier) throws JAXBException, DCMAApplicationException {
    LOGGER.info("FileBound export plugin.");
    LOGGER.info("Initializing properties...");
    final String isFileBoundON = pluginPropertiesService.getPropertyValue(batchInstanceIdentifier,
            FileBoundConstants.FILEBOUND_EXPORT_PLUGIN, FileBoundProperties.FILEBOUND_SWITCH);
    if (FileBoundConstants.ON_STRING.equalsIgnoreCase(isFileBoundON)) {
        final String connectionURL = pluginPropertiesService.getPropertyValue(batchInstanceIdentifier,
                FileBoundConstants.FILEBOUND_EXPORT_PLUGIN, FileBoundProperties.FILEBOUND_CONNECTION_URL);
        final String indexField = pluginPropertiesService.getPropertyValue(batchInstanceIdentifier,
                FileBoundConstants.FILEBOUND_EXPORT_PLUGIN, FileBoundProperties.FILEBOUND_INDEX_FIELD);
        final String division = pluginPropertiesService.getPropertyValue(batchInstanceIdentifier,
                FileBoundConstants.FILEBOUND_EXPORT_PLUGIN, FileBoundProperties.FILEBOUND_DIVISION);
        final String seperator = pluginPropertiesService.getPropertyValue(batchInstanceIdentifier,
                FileBoundConstants.FILEBOUND_EXPORT_PLUGIN, FileBoundProperties.FILEBOUND_SEPERATOR);
        final String userName = pluginPropertiesService.getPropertyValue(batchInstanceIdentifier,
                FileBoundConstants.FILEBOUND_EXPORT_PLUGIN, FileBoundProperties.FILEBOUND_USERNAME);
        final String password = pluginPropertiesService.getPropertyValue(batchInstanceIdentifier,
                FileBoundConstants.FILEBOUND_EXPORT_PLUGIN, FileBoundProperties.FILEBOUND_PASSWORD);
        final String projectName = pluginPropertiesService.getPropertyValue(batchInstanceIdentifier,
                FileBoundConstants.FILEBOUND_EXPORT_PLUGIN, FileBoundProperties.FILEBOUND_PROJECT_NAME);
        final String exportFormat = pluginPropertiesService.getPropertyValue(batchInstanceIdentifier,
                FileBoundConstants.FILEBOUND_EXPORT_PLUGIN, FileBoundProperties.FILEBOUND_EXPORT_FORMAT);

        LOGGER.info("Filebound properties initialised successfully...");
        boolean divisionPresent = false;
        boolean seperatorPresent = false;
        checkInformation(connectionURL, userName, password, projectName, indexField, division, seperator);
        skipDlfNames = new ArrayList<String>();
        skipDlfNames.add(FileBoundConstants.DOCUMENT_NAME);
        if ((null != seperator) && !(seperator.equals(""))) {
            seperatorPresent = true;
            skipDlfNames.add(seperator);
        }
        if ((null != division) && !(division.equals(""))) {
            divisionPresent = true;
            skipDlfNames.add(division);
        }

        final List<String> cmdList = populateCommandsList();
        final Batch batch = batchSchemaService.getBatch(batchInstanceIdentifier);
        final List<Document> xmlDocuments = batch.getDocuments().getDocument();
        final StringBuffer docFieldValues = new StringBuffer();
        String indexFieldVal = "";
        final Document document = xmlDocuments.get(0);
        final DocumentLevelFields docLeveleFields = document.getDocumentLevelFields();
        if (docLeveleFields == null) {
            LOGGER.error("Document Level fields are null. So cannot upload documents of batch instance "
                    + batchInstanceIdentifier + " to filebound repository");
            throw new DCMAApplicationException(
                    "Document Level fields are null. So cannot upload documents of batch instance "
                            + batchInstanceIdentifier + " to filebound repository");
        }
        final List<DocField> docLevelFields = docLeveleFields.getDocumentLevelField();
        String indexFieldName = "";
        if (docLevelFields != null && !docLevelFields.isEmpty()) {
            int count = 0;
            for (DocField docField : docLevelFields) {
                String dlfName = docField.getName();
                final String dlfValue = docField.getValue();
                if (dlfName == null) {
                    continue;
                }
                if (dlfName.equalsIgnoreCase(indexField)) {
                    indexFieldVal = dlfValue;
                    continue;
                }
                count++;
                if (!skipDlfNames.contains(docField.getName())) {
                    indexFieldName = updateDocLevelFied(indexField, docFieldValues, docLevelFields,
                            indexFieldName, count, dlfName, dlfValue);
                }
            }
        }
        if (indexFieldName.isEmpty()) {
            indexFieldName = indexField;
        }
        docFieldValues.insert(0, indexFieldName + "=" + indexFieldVal + ";;");
        String divider = "";
        divider = fetchDividerValues(xmlDocuments, division, divisionPresent);
        String seperatorVal = "";
        seperatorVal = fetchSeperatorValues(xmlDocuments, seperator, seperatorPresent);

        // Over-riding the divider value from the value configured in filebound-mapping.properties
        final String docName = document.getType();
        final String dividerMapping = fetchDocNameMapping(docName, batch.getBatchClassIdentifier());
        if (dividerMapping != null && dividerMapping.length() > 0) {
            divider = dividerMapping;
        }
        validateInformationForExporting(batchInstanceIdentifier, indexFieldVal, divider, divisionPresent,
                seperatorVal, seperatorPresent);
        // ----------------batch in error if all doclevel fields are null or empty as per discussion with
        // IKE------------------------\\
        validateDocLevelFields(batchInstanceIdentifier, docFieldValues);
        // ----------------------end-----------------------\\

        final String exportFolder = batchInstanceService.getSystemFolderForBatchInstanceId(
                batchInstanceIdentifier) + File.separator + batchInstanceIdentifier;
        final String docNamePathValues = getDocNamePathValues(xmlDocuments, exportFolder,
                batchInstanceIdentifier, exportFormat);
        final File fileboundParameterFile = new File(
                exportFolder + File.separator + FileBoundConstants.PARAMETERS_FILE_NAME);
        writeParametersToFile(batch, fileboundParameterFile, divider, docNamePathValues, seperatorVal,
                batchInstanceIdentifier);
        executeCommand(cmdList, connectionURL, userName, password, docFieldValues.toString(), indexFieldVal,
                projectName, indexFieldName,
                exportFolder + File.separator + FileBoundConstants.PARAMETERS_FILE_NAME);
        LOGGER.info("File bound upload successful.");
        LOGGER.info("Cleaning up intermediate filebound parameters file.....");
        if (fileboundParameterFile.exists()) {
            fileboundParameterFile.delete();
        }
    } else {
        LOGGER.info("Filebound configured not to be run.");
    }
}

From source file:forseti.JUtil.java

public static synchronized String Converts(String strval, String separador, boolean si_o_ret_nada) {
    if (strval == null || strval.equals("") || strval.equals("null"))
        return "&nbsp;";

    StringBuffer str = new StringBuffer(strval);
    int cantidad = Integer.parseInt(strval);
    int comas, len;
    boolean negativo = (cantidad < 0) ? true : false;
    if (cantidad == 0 && si_o_ret_nada)
        return "&nbsp;";

    if (negativo)
        str.deleteCharAt(0);// www.j a v  a 2  s.c o m

    if (!separador.equals(" ")) {
        comas = (str.length() / 3);
        len = str.length();
        for (int i = 0; i < comas; i++) {
            len -= 3;
            if (len > 0)
                str.insert(len, separador);
        }
    }

    if (negativo)
        str.insert(0, '-');

    return str.toString();

}

From source file:com.sun.honeycomb.admin.mgmt.server.HCCellAdapterBase.java

/**
 * Update the service tag data associated with a single cell.   This routine
 * must be called on ever cell in order to keep the silo_info.xml
 * up to date./*from  w  ww . j  a va  2s  .c  om*/
 * <P>
 * On the master cell this routine will clear the service tag registry
 * and attempt to repopulate it with the new service tag registry 
 * information.
 * @param evt the callback handle
 * @param tagData the service tag data to update
 * @param updateRegistry boolean to indicate whether the registry
 * file should be rebuilt.  If the callee already knows the 
 * service tag data is invalid they will call this value with a
 * value of 0.  In this case this api is getting used to clear the
 * registry and the instanceURNs
 * @return BigInteger, 0 for SUCCESS, -1 for failure.  
 * Currently always returns 0
 * @throws com.sun.honeycomb.mgmt.common.MgmtException
 */
public BigInteger updateAllServiceTagData(EventSender evt, HCServiceTags tagData, BigInteger updateRegistry)
        throws MgmtException {

    boolean updateRegistryFile = updateRegistry.intValue() == 1;
    MultiCellLib multiCell = MultiCellLib.getInstance();
    boolean isStandAlone = multiCell.isCellStandalone();
    StringBuffer buf = new StringBuffer();
    buf.append(" service tag data for cell");
    if (isStandAlone == false) {
        buf.append(" ").append(getCellId());
    }
    buf.append(".");
    Reassure reassureThread = null;
    try {
        reassureThread = new Reassure(evt);
        reassureThread.start();
        boolean isSupported = ServiceTagsRegistry.isSupported();
        boolean isMaster = multiCell.isCellMaster();
        if (isSupported && isMaster) {
            // If we modify an service tag data the service tag registry
            // is considered out of date.  As such we clear the registry
            // of all ST5800 service tags.
            clearRegistry();
        }

        List<HCServiceTagCellData> list = tagData.getData();
        HCServiceTagCellData[] hCellData = (HCServiceTagCellData[]) list
                .toArray(new HCServiceTagCellData[list.size()]);
        ServiceTagCellData[] cellData = new ServiceTagCellData[hCellData.length];
        for (int i = 0; i < hCellData.length; i++) {
            ServiceTagData data = new ServiceTagData(hCellData[i].getProductNumber(),
                    hCellData[i].getProductSerialNumber(), hCellData[i].getMarketingNumber(),
                    hCellData[i].getInstanceURN());
            ServiceTagCellData cell = new ServiceTagCellData(hCellData[i].getCellId(), data);
            cellData[i] = cell;
        }

        multiCell.updateServiceTagData(cellData);
        buf.insert(0, "Successfully updated");
        logger.log(Level.INFO, buf.toString());
        //evt.sendAsynchronousEvent(buf.toString()); 

        if (updateRegistryFile && isMaster) {
            // Reset the buf to new action in case of exception
            buf = new StringBuffer(" service tag registry.");
            if (isSupported == false) {
                evt.sendAsynchronousEvent(SERVICE_TAG_REGISTRY_IS_NOT_AVAILABLE_MSG);
                return BigInteger.valueOf(CliConstants.FAILURE);
            }
            // The silo_info.xml has been updated.
            // Now update the service tag registry
            ServiceTagsGenerator generator = new ServiceTagsGenerator(cellData);
            if (generator.isValid() == false) {
                // This should technically never happen is everything is
                // done via the cli since the validation check on the cli
                // side should of failed and prevented this call from
                // ever occurring
                buf = new StringBuffer();
                buf.append("Failed to update service tag registry due to a ");
                buf.append("validation error.\nSee logs for further details.");
                // Validation errors found via ServiceTagsGenerator are
                // logged by default
                evt.sendAsynchronousEvent(buf.toString());
                return BigInteger.valueOf(CliConstants.SERVICE_TAG_REGISTRY_VALIDATION_FAILURE);
            } else {
                ServiceTagsRegistry.update(generator.getServiceTags());
                buf.insert(0, "Successfully updated");
                logger.log(Level.INFO, buf.toString());
            }
        }
        return BigInteger.ZERO;
    } catch (MultiCellLibError mcle) {
        buf.insert(0, "Failed to update");
        logger.log(Level.SEVERE, buf.toString(), mcle);
        buf.append(" Reason: ");
        buf.append(mcle.getMessage());
        buf.append(".\n");
        buf.append("Ensure that the servicetag entries are all valid by invoking the command,\n");
        buf.append("'servicetags --refresh'.");

        evt.sendAsynchronousEvent(buf.toString());
        return BigInteger.valueOf(CliConstants.FAILURE);
    } catch (Exception ex) {
        buf.insert(0, "Failed to update");
        logger.log(Level.SEVERE, buf.toString(), ex);
        buf.append(" Reason: ");
        buf.append(ex.getMessage());
        buf.append(".\n");
        buf.append("Ensure that the servicetag entries are all valid by invoking the command,\n");
        buf.append("'servicetags --refresh'");
        evt.sendAsynchronousEvent(buf.toString());
        return BigInteger.valueOf(CliConstants.FAILURE);
    } finally {
        if (reassureThread != null)
            reassureThread.safeStop();
    }
}

From source file:com.ephesoft.dcma.kvfieldcreation.KVFieldCreator.java

/**
 * Concatenate keys found at left location.
 * /*from   ww w .j a v  a2s.com*/
 * @param kvExtractionField
 * @param lineDataCarrier
 * @param span
 * @param minKeyCharsInt
 * @param keyCoordinates
 * @return
 */
private boolean concatenateKeysLeft(final KVExtraction kvExtractionField, final LineDataCarrier lineDataCarrier,
        final Span span, final int minKeyCharsInt, final Coordinates keyCoordinates) {
    LOGGER.info("Concatenating keys on left....");
    boolean keyFound = false;
    String key = span.getValue();
    StringBuffer keyString = null;
    List<Coordinates> keyCoordinatesList = new ArrayList<Coordinates>();
    if (key != null) {
        keyString = new StringBuffer(key);
        keyCoordinatesList.add(span.getCoordinates());
        int prevKeyX0 = span.getCoordinates().getX0().intValue();
        int gapBetweenWords = 0;
        keyString = new StringBuffer(key);
        Integer spanIndex = lineDataCarrier.getIndexOfSpan(span);
        if (spanIndex != null) {
            Span leftSpan = lineDataCarrier.getLeftSpan(spanIndex);
            while (leftSpan != null) {
                key = leftSpan.getValue();
                if (null != key && !key.trim().isEmpty()) {
                    gapBetweenWords = prevKeyX0 - leftSpan.getCoordinates().getX1().intValue();
                    if (Math.abs(gapBetweenWords) < gapBetweenKeys) {
                        LOGGER.info(key.trim() + " Concatenated on left.");
                        keyCoordinatesList.add(leftSpan.getCoordinates());
                        keyString.insert(0, key.trim() + KVFieldCreatorConstants.SPACE);
                        prevKeyX0 = leftSpan.getCoordinates().getX0().intValue();
                    } else {
                        LOGGER.info("gap between words > " + gapBetweenKeys);
                        break;
                    }
                }
                spanIndex = spanIndex - 1;
                leftSpan = lineDataCarrier.getLeftSpan(spanIndex);
            }
        }
    }
    keyFound = setKeyPattern(kvExtractionField, keyCoordinates, minKeyCharsInt, keyString, keyCoordinatesList);
    return keyFound;
}

From source file:com.ephesoft.dcma.kvfieldcreation.KVFieldCreator.java

/**
 * Concatenate keys found at right location.
 * /*  ww  w  .ja va  2 s.  c  o m*/
 * @param kvExtractionField
 * @param lineDataCarrier
 * @param span
 * @param minKeyCharsInt
 * @param keyCoordinates
 * @return
 */
private boolean concatenateKeysRight(final KVExtraction kvExtractionField,
        final LineDataCarrier lineDataCarrier, final Span span, final int minKeyCharsInt,
        final Coordinates keyCoordinates) {
    LOGGER.info("Concatenating keys on right....");
    boolean keyFound = false;
    String key = span.getValue();
    StringBuffer keyString = null;
    List<Coordinates> keyCoordinatesList = new ArrayList<Coordinates>();
    if (key != null) {
        keyString = new StringBuffer(key);
        keyCoordinatesList.add(span.getCoordinates());
        int prevKeyX1 = span.getCoordinates().getX1().intValue();
        int gapBetweenWords = 0;
        keyString = new StringBuffer(key);
        Integer spanIndex = lineDataCarrier.getIndexOfSpan(span);
        if (spanIndex != null) {
            Span rightSpan = lineDataCarrier.getLeftSpan(spanIndex);
            while (rightSpan != null) {
                key = rightSpan.getValue();
                if (null != key && !key.trim().isEmpty()) {
                    gapBetweenWords = prevKeyX1 - rightSpan.getCoordinates().getX0().intValue();
                    if (Math.abs(gapBetweenWords) < gapBetweenKeys) {
                        LOGGER.info(key.trim() + " Concatenated on right.");
                        keyCoordinatesList.add(rightSpan.getCoordinates());
                        keyString.insert(0, key.trim() + KVFieldCreatorConstants.SPACE);
                        prevKeyX1 = rightSpan.getCoordinates().getX0().intValue();
                    } else {
                        LOGGER.info("gap between words >= " + gapBetweenKeys);
                        break;
                    }
                }
                spanIndex = spanIndex - 1;
                rightSpan = lineDataCarrier.getRightSpan(spanIndex);
            }
        }
    }
    keyFound = setKeyPattern(kvExtractionField, keyCoordinates, minKeyCharsInt, keyString, keyCoordinatesList);
    return keyFound;
}

From source file:com.sun.honeycomb.admin.mgmt.server.HCCellAdapterBase.java

/**
 * Update the service tag data associated with a single cell.   This routine
 * must be called on ever cell in order to keep the silo_info.xml.  On
 * the master node this will clear the registry file.  If the cell is
 * a single cell system the registry file will be updated.  An update
 * does not happen on multi-cell since we can't update all the instanceIDs
 * on all cells.  Therefore we required the operator to do a 
 * "servicetags --refresh"// w  w  w  .j a  v  a2  s.co  m
 * @param evt the callback handle
 * @param cellData the service tag data to update
 * @return BigInteger, 0 for SUCCESS, -1 for failure, -2 for failed
 * to update registry file on a single cell system.   
 * Currently always returns 0
 * @throws com.sun.honeycomb.mgmt.common.MgmtException
 */
public BigInteger updateServiceTagData(EventSender evt, HCServiceTagCellData cellData) throws MgmtException {

    MultiCellLib multiCell = MultiCellLib.getInstance();
    boolean isStandAlone = multiCell.isCellStandalone();
    StringBuffer buf = new StringBuffer();
    buf.append(" service tag data on cell");
    if (isStandAlone == false) {
        buf.append(" ").append(cellData.getCellId()).append(" on cell ");
        buf.append(getCellId());
    }
    buf.append(".");
    Reassure reassureThread = new Reassure(evt);
    try {
        reassureThread.start();
        boolean isSupported = ServiceTagsRegistry.isSupported();
        boolean isMaster = multiCell.isCellMaster();
        if (isMaster) {
            // If we modify an service tag data the service tag registry
            // is considered out of date.  As such we clear the registry
            // of all ST5800 service tags.
            if (isSupported)
                clearRegistry();
        }
        String instanceURN = null;
        if (isStandAlone) {
            // When we have a single cell system we can automatically
            // update the service tag registry.  On a multi-cell hive
            // this isn't possible since we can't update all the 
            // instance information on all the cells.  The operator
            // in that scenario must follow up with a "servicetag --refresh"
            // command.
            instanceURN = ServiceTag.generateInstanceURN();
        }
        ServiceTagData data = new ServiceTagData(cellData.getProductNumber(), cellData.getProductSerialNumber(),
                cellData.getMarketingNumber(), instanceURN);

        multiCell.updateServiceTagData(cellData.getCellId(), data);
        buf.insert(0, "Successfully updated");
        logger.log(Level.INFO, buf.toString());
        //evt.sendAsynchronousEvent(buf.toString());

        if (isStandAlone) {
            // Reset the buf to new action in case of exception
            buf = new StringBuffer(" service tag registry.");

            ClusterProperties props = ClusterProperties.getInstance();
            boolean disabled = props
                    .getPropertyAsBoolean(ConfigPropertyNames.PROP_SERVICE_TAG_SERVICE_DISABLED);
            if (disabled) {
                evt.sendAsynchronousEvent(
                        "Service Tag service is disabled service tag " + "registry file will not be updated.");
                return BigInteger.valueOf(CliConstants.SERVICE_TAG_REGISTRY_UPDATE_FAILURE);

            }

            // This is a single cell system.
            // We can automatically update the service tag registry
            if (isSupported == false) {
                evt.sendAsynchronousEvent(SERVICE_TAG_REGISTRY_IS_NOT_AVAILABLE_MSG);
                return BigInteger.valueOf(CliConstants.SERVICE_TAG_REGISTRY_UPDATE_FAILURE);
            }
            ServiceTagCellData[] cells = new ServiceTagCellData[] { new ServiceTagCellData(getCellId(), data) };
            ServiceTagsGenerator generator = new ServiceTagsGenerator(cells);
            if (generator.isValid() == false) {
                // This should never happen on a single cell system
                buf = new StringBuffer().append("Failed to update service tag registry due to a ")
                        .append("validation error.\nSee logs for further details.");
                // Validation errors found via ServiceTagsGenerator are
                // logged by default
                evt.sendAsynchronousEvent(buf.toString());
                return BigInteger.valueOf(CliConstants.SERVICE_TAG_REGISTRY_VALIDATION_FAILURE);
            } else {
                ServiceTagsRegistry.update(generator.getServiceTags());
                buf.insert(0, "Successfully updated");
                evt.sendAsynchronousEvent(buf.toString());
                logger.log(Level.INFO, buf.toString());
            }
        }
        return BigInteger.ZERO;
    } catch (MgmtException me) {
        buf.insert(0, "Failed to update");
        logger.log(Level.SEVERE, buf.toString(), me);
        buf.append(" Reason: ");
        buf.append(me.getMessage());
        buf.append(".\n");
        buf.append("Ensure that the servicetag entries are all valid by invoking the command,");
        buf.append("'servicetags --refresh'");
        evt.sendAsynchronousEvent(buf.toString());
        return BigInteger.valueOf(CliConstants.FAILURE);
    } catch (Exception ex) {
        buf.insert(0, "Failed to update");
        logger.log(Level.SEVERE, buf.toString(), ex);
        buf.append(" Reason: ");
        buf.append(ex.getMessage());
        buf.append(".\n");
        buf.append("Ensure that the servicetag entries are all valid by invoking the command,");
        buf.append("'servicetags --refresh'");

        evt.sendAsynchronousEvent(buf.toString());
        return BigInteger.valueOf(CliConstants.FAILURE);
    } finally {
        if (reassureThread != null)
            reassureThread.safeStop();
    }
}

From source file:com.dearho.cs.subscriber.service.impl.SubscriberServiceImpl.java

/**
 * //  w  w  w .j a v  a2 s. c  o  m
 */
@Override
public Page querySubscriberRechargeLatestByPage(Page page, Subscriber subscriber) {

    StringBuffer hql = new StringBuffer();

    hql.append("SELECT a.id as id  FROM acc_trade_record_list a  where  type=1 and result=1  ");

    if (subscriber != null) {
        if (subscriber.getState() != null || subscriber.getEventState() != null
                || StringUtils.isNotEmpty(subscriber.getPhoneNo())
                || StringUtils.isNotEmpty(subscriber.getSex())) {
            hql.append(" and a.subscriber_id in ( select id from sub_subscriber where 1=1 ");
        }
        if (subscriber.getState() != null) {
            hql.append(" and state=" + subscriber.getState());
        }
        if (subscriber.getEventState() != null) {
            hql.append(" and event_state=" + subscriber.getEventState());
        }
        if (StringUtils.isNotEmpty(subscriber.getPhoneNo())) {
            hql.append(" and phone_no like '%" + subscriber.getPhoneNo() + "%'");
        }
        if (StringUtils.isNotEmpty(subscriber.getSex())) {
            hql.append(" and sex = '" + subscriber.getSex() + "'");
        }
        if (StringUtils.isNotEmpty(subscriber.getName())) {
            hql.append(" and name like '%" + subscriber.getName() + "%'");
        }
        if (subscriber.getState() != null || subscriber.getEventState() != null
                || StringUtils.isNotEmpty(subscriber.getPhoneNo())
                || StringUtils.isNotEmpty(subscriber.getSex())) {
            hql.append(" ) ");
        }
    }
    hql.append("group by a.subscriber_id  order by a.ts desc");
    //   hql.append(" group by a.subscriber_id   ");
    //   hql.append("order by a.create_time desc ");
    //hql.append(StringHelper.isEmpty(page.getOrderByString2()) ? "" : page.getOrderByString2());

    hql.insert(0, "select b.id from ( ");
    hql.append(" )b");

    page.setCountField("b.id");
    page = subscriberDao.querySubscriberByPage(page, hql.toString());
    return page;

}

From source file:com.lp.server.artikel.fastlanereader.ArtikellisteHandler.java

/**
 * builds the HQL (Hibernate Query Language) order by clause using the sort
 * criterias contained in the current query.
 * /* ww  w  . j  a  v a2 s.  c o m*/
 * @return the HQL order by clause.
 */
private String buildOrderByClause() {
    StringBuffer orderBy = new StringBuffer("");
    if (getQuery() != null) {
        SortierKriterium[] kriterien = getQuery().getSortKrit();
        boolean sortAdded = false;
        if (kriterien != null && kriterien.length > 0) {
            for (int i = 0; i < kriterien.length; i++) {
                if (!kriterien[i].kritName.endsWith(Facade.NICHT_SORTIERBAR)) {
                    if (kriterien[i].isKrit) {
                        if (sortAdded) {
                            orderBy.append(", ");
                        }
                        sortAdded = true;
                        orderBy.append(kriterien[i].kritName);
                        orderBy.append(" ");
                        orderBy.append(kriterien[i].value);
                    }
                }
            }
        } else {
            // no sort criteria found, add default sort
            if (sortAdded) {
                orderBy.append(", ");
            }
            orderBy.append("artikelliste.c_nr ASC ");
            sortAdded = true;
        }
        if (orderBy.indexOf("artikelliste.i_id") < 0) {
            // unique sort required because otherwise rowNumber of
            // selectedId
            // within sort() method may be different from the position of
            // selectedId
            // as returned in the page of getPageAt().
            if (sortAdded) {
                orderBy.append(", ");
            }
            orderBy.append(" artikelliste.i_id ");
            sortAdded = true;
        }
        if (sortAdded) {
            orderBy.insert(0, " ORDER BY ");
        }
    }
    return orderBy.toString();
}

From source file:edu.umd.ks.cm.util.siscm.dao.impl.SisCmDaoImpl.java

private String getNaturalLanguageForStatement(String booleanExpression,
        List<ReqComponentReference> reqComponentList) throws Exception {
    HashMap reqComponentMap = new HashMap();
    LinkedHashMap<Integer, Integer> parPositionMap = new LinkedHashMap<Integer, Integer>();
    ArrayList<Integer> parLeftList = new ArrayList<Integer>();

    for (ReqComponentReference reqComponent : reqComponentList) {
        String translation = this.reqComponentTranslator.translate(reqComponent.getReqComponent(),
                "KUALI.RULE.CATALOG", "en");
        if (translation != null && translation.length() > 0
                && translation.substring(translation.length() - 1).equals("."))
            translation = translation.substring(0, translation.length() - 1);
        reqComponentMap.put(reqComponent.getBooleanId(), translation);
    }/*w  w w .  j a  va  2 s  .  com*/

    BooleanFunction booleanFunction = new BooleanFunction(booleanExpression);
    List<String> funcSymbs = booleanFunction.getSymbols();

    for (int i = 0; i < funcSymbs.size(); i++) {
        if (funcSymbs.get(i).equals("(")) {
            parLeftList.add(i);
        }
        int parLeftLast = parLeftList.size() - 1;
        if (funcSymbs.get(i).equals(")")) {
            parPositionMap.put(parLeftList.get(parLeftLast), i);
            parLeftList.remove(parLeftLast);
        }
    }

    // For the expression (A + B + (C * D)) want to remove outer ()
    if (parPositionMap.containsKey(0) && parPositionMap.get(0) == funcSymbs.size() - 1) {
        parPositionMap.remove(0);
        funcSymbs.set(0, "null");
        funcSymbs.set(funcSymbs.size() - 1, "null");
    }

    if (!parPositionMap.isEmpty()) {
        for (Integer key : parPositionMap.keySet()) {
            StringBuffer funcSymb = new StringBuffer("");
            int pos = 0;
            String expr = "";
            for (int i = key + 1; i < parPositionMap.get(key); i++) {
                String funcSymbAdd = funcSymbs.get(i);
                if (!funcSymbAdd.equals("+") && !funcSymbAdd.equals("*") && !funcSymbAdd.equals("null")) {
                    expr = (String) reqComponentMap.get(funcSymbAdd);
                    if (pos == 0 && !funcSymbAdd.substring(0, 1).equals("V") && expr.length() > 2
                            && expr.substring(0, 1).equals("(")
                            && expr.substring(expr.length() - 1).equals(")")) {
                        expr = expr.substring(1, expr.length() - 1);
                    }
                    pos = 1;

                    //convert the first character of 'expr' to lower case, if necessary
                    if (expr.length() > 0) {
                        char ch0 = expr.charAt(0);
                        if (ch0 <= 'Z' && ch0 >= 'A') {
                            if (expr.length() > 1) {
                                char ch1 = expr.charAt(1);
                                if (ch1 >= 'a' && ch1 <= 'z') {
                                    expr = expr.substring(0, 1).toLowerCase() + expr.substring(1);
                                }
                            } else {
                                expr = expr.toLowerCase();
                            }
                        }
                    }

                    funcSymb.append(expr);
                } else if (funcSymbAdd.equals("+")) {
                    funcSymb.append("; or ");
                } else if (funcSymbAdd.equals("*")) {
                    funcSymb.append("; and ");
                }
            } // for int i               
            String id = "V" + Integer.toString(key);
            funcSymb.insert(0, "(");
            funcSymb.append(")");
            reqComponentMap.put(id, funcSymb.toString());

            funcSymbs.set(key, id);
            for (int i = key + 1; i < parPositionMap.get(key) + 1; i++)
                funcSymbs.set(i, "null");
        }
    }

    List<String> funcSymbsNew = new ArrayList<String>();
    for (int i = 0; i < funcSymbs.size(); i++) {
        if (!funcSymbs.get(i).equals("null"))
            funcSymbsNew.add(funcSymbs.get(i));
    }

    String nl = "";
    if (funcSymbsNew.size() == 1) {
        nl = (String) reqComponentMap.get(funcSymbsNew.get(0));
        if (nl.substring(0, 1).equals("(") && nl.substring(nl.length() - 1).equals(")"))
            nl = nl.substring(1, nl.length() - 1);
    } else {
        int pos = 0;
        String expr = "";
        for (int i = 0; i < funcSymbsNew.size(); i++) {
            if (!funcSymbsNew.get(i).equals("*") && !funcSymbsNew.get(i).equals("+")) {
                expr = (String) reqComponentMap.get(funcSymbsNew.get(i));
                if (pos == 0) {
                    if (expr.length() > 2 && expr.substring(0, 1).equals("(")
                            && expr.substring(expr.length() - 1).equals(")"))
                        expr = expr.substring(1, expr.length() - 1);
                    pos = 1;
                } else {
                    if (funcSymbsNew.get(i).substring(0, 1).equals("V") && expr.length() > 2
                            && expr.substring(0, 1).equals("(")
                            && expr.substring(expr.length() - 1).equals(")"))
                        expr = expr.substring(1, expr.length() - 1);
                }
                nl = nl + expr;
            } else if (funcSymbsNew.get(i).equals("+")) {
                if ((i > 0 && funcSymbsNew.get(i - 1).substring(0, 1).equals("V"))
                        || (i < (funcSymbsNew.size() - 1)
                                && funcSymbsNew.get(i + 1).substring(0, 1).equals("V")))
                    nl = nl + ". Or ";
                else
                    nl = nl + "; or ";
            } else if (funcSymbsNew.get(i).equals("*")) {
                if ((i > 0 && funcSymbsNew.get(i - 1).substring(0, 1).equals("V"))
                        || (i < (funcSymbsNew.size() - 1)
                                && funcSymbsNew.get(i + 1).substring(0, 1).equals("V")))
                    nl = nl + ". And ";
                else
                    nl = nl + "; and ";
            }
        }
    }

    //TODO: Fix Capitalization
    nl = nl.substring(0, 1).toUpperCase() + nl.substring(1);
    return nl.trim();
}