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:com.jaspersoft.jasperserver.api.engine.scheduling.quartz.ReportExecutionJobMailNotificationImpl.java

protected void attachOutput(ReportExecutionJob job, MimeMessageHelper messageHelper, ReportOutput output,
        boolean useZipFormat) throws MessagingException, JobExecutionException {
    String attachmentName;//from w w w.  j a  v a 2s.  c  om
    DataContainer attachmentData;
    if (output.getChildren().isEmpty()) {
        attachmentName = output.getFilename();
        attachmentData = output.getData();
    } else if (useZipFormat) { // use zip format
        attachmentData = job.createDataContainer();
        boolean close = true;
        ZipOutputStream zipOut = new ZipOutputStream(attachmentData.getOutputStream());
        try {
            zipOutput(job, output, zipOut);
            zipOut.finish();
            zipOut.flush();
            close = false;
            zipOut.close();
        } catch (IOException e) {
            throw new JSExceptionWrapper(e);
        } finally {
            if (close) {
                try {
                    zipOut.close();
                } catch (IOException e) {
                    log.error("Error closing stream", e);
                }
            }
        }

        attachmentName = output.getFilename() + ".zip";
    } else { // NO ZIP FORMAT
        attachmentName = output.getFilename();
        try {
            attachmentName = MimeUtility.encodeWord(attachmentName, job.getCharacterEncoding(), null);
        } catch (UnsupportedEncodingException e) {
            throw new JSExceptionWrapper(e);
        }
        StringBuffer primaryPage = null;
        for (Iterator it = output.getChildren().iterator(); it.hasNext();) {
            ReportOutput child = (ReportOutput) it.next();
            String childName = child.getFilename();

            // NOTE:  add the ".dat" extension to all image resources
            // email client will automatically append ".dat" extension to all the files with no extension
            // should do it in JasperReport side
            if (output.getFileType().equals(ContentResource.TYPE_HTML)) {
                if (primaryPage == null)
                    primaryPage = new StringBuffer(new String(output.getData().getData()));
                int fromIndex = 0;
                while ((fromIndex = primaryPage.indexOf("src=\"" + childName + "\"", fromIndex)) > 0) {
                    primaryPage.insert(fromIndex + 5 + childName.length(), ".dat");
                }
                childName = childName + ".dat";
            }

            try {
                childName = MimeUtility.encodeWord(childName, job.getCharacterEncoding(), null);
            } catch (UnsupportedEncodingException e) {
                throw new JSExceptionWrapper(e);
            }
            messageHelper.addAttachment(childName, new DataContainerResource(child.getData()));
        }
        if (primaryPage == null) {
            messageHelper.addAttachment(attachmentName, new DataContainerResource(output.getData()));
        } else {
            messageHelper.addAttachment(attachmentName,
                    new DataContainerResource(new MemoryDataContainer(primaryPage.toString().getBytes())));
        }
        return;
    }
    try {
        attachmentName = MimeUtility.encodeWord(attachmentName, job.getCharacterEncoding(), null);
    } catch (UnsupportedEncodingException e) {
        throw new JSExceptionWrapper(e);
    }
    messageHelper.addAttachment(attachmentName, new DataContainerResource(attachmentData));
}

From source file:com.sap.research.connectivity.gw.GWOperationsUtils.java

private void addRelationshipInPersistenceMethods(JavaSourceFileEditor entityClassFile, String nav,
        String javaType, String associationType) {
    // TODO Auto-generated method stub
    ArrayList<JavaSourceMethod> globalMethodList = entityClassFile.getGlobalMethodList();
    String pluralRemoteEntity = GwUtils.getInflectorPlural(entityClassFile.CLASS_NAME, Locale.ENGLISH);
    String smallRemoteEntity = StringUtils.uncapitalize(entityClassFile.CLASS_NAME);

    for (JavaSourceMethod method : globalMethodList) {
        String methodName = method.getMethodName();
        /*/*from   w ww .j  a v a  2s  .com*/
         * We insert the relation in the persist and merge methods
         */
        if (methodName.endsWith("persist")) {
            StringBuffer methodBody = new StringBuffer(method.getMethodBody());
            methodBody.insert(methodBody.lastIndexOf("newEntity = newEntityRequest"),
                    makeGWPersistRelationshipCode(nav, javaType, associationType, "\t\t"));
            method.setMethodBody(methodBody.toString());
        } else if (methodName.endsWith("merge")) {
            StringBuffer methodBody = new StringBuffer(method.getMethodBody());
            methodBody.insert(methodBody.lastIndexOf("boolean modifyRequest = modifyEntityRequest"),
                    makeGWMergeRelationshipCode(nav, javaType, associationType, "\t\t"));
            method.setMethodBody(methodBody.toString());
        }

        /*
         * We insert the relation in the findAll and find<Entity>Entries methods
         */
        else if (methodName.endsWith("findAll" + pluralRemoteEntity)
                || methodName.endsWith("find" + entityClassFile.CLASS_NAME + "Entries")) {
            StringBuffer methodBody = new StringBuffer(method.getMethodBody());
            int insertPosition = methodBody.indexOf("} catch (Exception relationshipsException)");
            boolean isFirstManyToMany = true;
            if ("OneToMany ManyToMany".contains(associationType)) {
                String manyToManyInsertReferenceString = StringUtils.uncapitalize(entityClassFile.CLASS_NAME)
                        + "Link.isCollection()) {";
                if (methodBody.indexOf(manyToManyInsertReferenceString) > -1) {
                    insertPosition = methodBody.indexOf(manyToManyInsertReferenceString);
                    isFirstManyToMany = false;
                }
            }
            methodBody.insert(insertPosition,
                    makeGWShowRelationshipCode(entityClassFile.CLASS_NAME, smallRemoteEntity + "Instance",
                            smallRemoteEntity + "Item", ODATA_KEY, nav, javaType, associationType, "\t\t",
                            isFirstManyToMany));
            method.setMethodBody(methodBody.toString());
        }
        /*
         * We insert the relation in the find<Entity> method
         */
        else if (methodName.endsWith("find" + entityClassFile.CLASS_NAME)) {
            StringBuffer methodBody = new StringBuffer(method.getMethodBody());
            int insertPosition = methodBody.indexOf("} catch (Exception relationshipsException)");
            boolean isFirstManyToMany = true;
            if ("OneToMany ManyToMany".contains(associationType)) {
                String manyToManyInsertReferenceString = StringUtils.uncapitalize(entityClassFile.CLASS_NAME)
                        + "Link.isCollection()) {";
                if (methodBody.indexOf(manyToManyInsertReferenceString) > -1) {
                    insertPosition = methodBody.indexOf(manyToManyInsertReferenceString);
                    isFirstManyToMany = false;
                }
            }
            methodBody.insert(insertPosition,
                    makeGWShowRelationshipCode(entityClassFile.CLASS_NAME,
                            "virtual" + entityClassFile.CLASS_NAME, smallRemoteEntity,
                            "OEntityKey.parse(" + GwUtils.GW_CONNECTION_FIELD_NAME
                                    + ".getDecodedRemoteKey(Id))",
                            nav, javaType, associationType, "\t\t\t", isFirstManyToMany));
            method.setMethodBody(methodBody.toString());
        }
    }
}

From source file:eu.medsea.mimeutil.detector.OpendesktopMimeDetector.java

private String getString(int offset, boolean regularExpression) {
    int position = content.position();
    content.position(offset);//from w  w  w.  j  a  v  a2s.com
    StringBuffer buf = new StringBuffer();
    char c = 0;
    while ((c = (char) content.get()) != 0) {
        if (regularExpression) {
            switch (c) {
            case '.':
                buf.append("\\");
                break;
            case '*':
            case '+':
            case '?':
                buf.append(".");
            }
        }
        buf.append(c);
    }
    // Reset position
    content.position(position + 4);

    if (regularExpression) {
        buf.insert(0, '^');
        buf.append('$');
    }
    return buf.toString();
}

From source file:axiom.main.Server.java

private void shutdownDefaultDb() {
    Object apps[] = getApplications();

    for (int i = 0; i < apps.length; i++) {
        Application app = (Application) apps[i];
        File db = new File(this.getDbHome(), TransSource.TRANSACTIONS_DB_DIR + "_" + app.getName());
        StringBuffer url = new StringBuffer(db.getPath());
        if (!url.toString().endsWith(File.separator)) {
            url.append(File.separator);
        }//  w w w . jav  a2  s.  com

        url.append(app.getName() + File.separator + TransSource.TRANSACTIONS_DB_DIR);
        if (!url.toString().endsWith(File.separator)) {
            url.append(File.separator);
        }
        url.append(TransSource.TRANSACTIONS_DB_NAME);

        url.insert(0, TransSource.DEFAULT_URL);

        Connection conn = null;
        PreparedStatement pstmt = null;
        try {
            conn = DriverManager.getConnection(url.toString());
            pstmt = conn.prepareStatement("SHUTDOWN");
            pstmt.execute();
        } catch (Exception ex) {
            // ignore, if shutdown failed, must not be using the default db
        } finally {
            if (pstmt != null) {
                try {
                    pstmt.close();
                } catch (SQLException sqle) {
                }
                pstmt = null;
            }
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException sqle) {
                }
                conn = null;
            }
        }
    }
}

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

/**
 * Get the limit clause to perform search result truncation.  Will return
 * something of the form:/*from   ww  w .  j  a  v  a  2s .  co  m*/
 *
 * <code>
 * LIMIT [limit]
 * </code>
 */
private void buildRowLimitAndOffset(StringBuffer queryBuf, List<Serializable> params) {
    // prepare the LIMIT clause
    if (limit > 0 || offset > 0) {
        queryBuf.insert(0, "SELECT /*+ FIRST_ROWS(n) */ rec.*, ROWNUM rnum  FROM (");
        queryBuf.append(") ");
    }

    if (limit > 0) {
        queryBuf.append("rec WHERE rownum<=? ");
        if (offset > 0) {
            params.add(Integer.valueOf(limit + offset));
        } else {
            params.add(Integer.valueOf(limit));
        }
    }

    if (offset > 0) {
        queryBuf.insert(0, "SELECT * FROM (");
        queryBuf.append(") WHERE rnum>?");
        params.add(Integer.valueOf(offset));
    }
}

From source file:com.qut.middleware.delegator.openid.authn.impl.AuthnProcessorImpl.java

private void verifyOpenIDAuthnResponse(AuthnProcessorData processorData, List<AttributeType> esoeAttributes)
        throws OpenIDException, NoSuchAlgorithmException {
    ParameterList response;//  www.ja  v a2s.  co m
    DiscoveryInformation discovered;
    StringBuffer receivingURL;
    String queryString;
    VerificationResult verification;
    Identifier verified;
    AuthSuccess authSuccess;

    response = new ParameterList(processorData.getHttpRequest().getParameterMap());

    /* Retrieve the stored discovery information */
    discovered = (DiscoveryInformation) processorData.getHttpRequest().getSession()
            .getAttribute(ConfigurationConstants.OPENID_USER_SESSION_IDENTIFIER);

    /* Extract the receiving URL from the HTTP request */
    receivingURL = processorData.getHttpRequest().getRequestURL();

    /*
     * If a Layer 7 type device is offloading https change the recievingURL accordingly to ensure
     * correct verification
     */
    if (httpsOffload) {
        receivingURL.delete(0, 4);
        receivingURL.insert(0, "https");
    }

    queryString = processorData.getHttpRequest().getQueryString();
    if (queryString != null && queryString.length() > 0)
        receivingURL.append("?").append(processorData.getHttpRequest().getQueryString());

    /* Verify the response */
    this.logger.debug("About to verify response, accepted at receivingURL of " + receivingURL
            + " server set return to as " + response.toString());

    verification = manager.verify(receivingURL.toString(), response, discovered);
    verified = verification.getVerifiedId();
    if (verified != null) {
        AttributeType esoeAttribute;
        MessageDigest algorithm;
        byte messageDigest[];

        authSuccess = (AuthSuccess) verification.getAuthResponse();

        /*
         * Merge verified ID to ESOE view, OpenID identifiers aren't really compatible with most applications as an
         * identifier, so we'll md5 hash them for presentation as uid
         */
        algorithm = MessageDigest.getInstance("MD5");
        algorithm.reset();
        algorithm.update(verification.getVerifiedId().getIdentifier().getBytes());
        messageDigest = algorithm.digest();

        esoeAttribute = new AttributeType();
        esoeAttribute.setNameFormat(AttributeFormatConstants.basic);
        esoeAttribute.setName(this.userIdentifier);
        esoeAttribute.getAttributeValues()
                .add(new String(Hex.encodeHex(messageDigest)) + ConfigurationConstants.OPENID_NAMESPACE);
        esoeAttributes.add(esoeAttribute);

        /*
         * Store openID identifier in attributes for use by applications
         */
        esoeAttribute = new AttributeType();
        esoeAttribute.setNameFormat(AttributeFormatConstants.basic);
        esoeAttribute.setName(ConfigurationConstants.OPENID_IDENTIFIER_ATTRIBUTE);
        esoeAttribute.getAttributeValues().add(verification.getVerifiedId().getIdentifier());
        esoeAttributes.add(esoeAttribute);

        /*
         * Retrieve requested attributes (if provided, given low deployments of attribute exchange currently we
         * don't fail when this isn't presented)
         */
        if (authSuccess.hasExtension(AxMessage.OPENID_NS_AX)) {
            FetchResponse fetchResp = (FetchResponse) authSuccess.getExtension(AxMessage.OPENID_NS_AX);

            for (OpenIDAttribute attribute : this.requestedAttributes) {
                List<String> values = fetchResp.getAttributeValues(attribute.getLabel());

                /* Merge to ESOE view */
                esoeAttribute = new AttributeType();
                esoeAttribute.setNameFormat(AttributeFormatConstants.basic);
                esoeAttribute.setName(attribute.getEsoeAttributeName());
                for (String value : values) {
                    esoeAttribute.getAttributeValues().add(attribute.getValuePrepend() + value);
                }
                esoeAttributes.add(esoeAttribute);
            }
        }
    } else {
        throw new OpenIDException("Attempt by manager to verify result returned null");
    }
}

From source file:com.ss.language.model.gibblda.Estimator.java

/**
 * ???/*  ww w.j a  v  a2s  .  c om*/
 * 
 * @param docs
 */
private void writeEachwordsEachWord(Document[] docs) {
    if (docs != null && docs.length > 0) {
        BufferedReader br = null;
        try {
            br = new BufferedReader(new InputStreamReader(
                    new FileInputStream(trnModel.data.localDict.getWordIdsFile()), "UTF-8"));
            for (String wordId = br.readLine(); wordId != null; wordId = br.readLine()) {
                wordId = wordId == null ? "" : wordId.trim();
                if (wordId.isEmpty()) {
                    continue;
                }
                StringBuffer sb = new StringBuffer();
                for (Document doc : docs) {
                    String[] words = doc.getAllWords();
                    if (words != null && words.length > 0) {
                        int times = 0;
                        for (String w : words) {
                            if (wordId.equals(w)) {
                                times += 1;
                            }
                        }
                        if (times > 0) {
                            sb.append("(");
                            sb.append(doc.getDocId());
                            sb.append(":");
                            sb.append(times);
                            sb.append("),");
                        }
                    }
                }
                // ???
                if (sb.length() > 0) {
                    File file = new File(
                            option.dir + File.separator + option.wordMapFileName + "-statistic.txt");
                    sb.insert(0, "[");
                    sb.insert(sb.length() - 1, "]");
                    FileUtils.write(file, sb.subSequence(0, sb.length() - 1) + IOUtils.LINE_SEPARATOR, "UTF-8",
                            true);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (Exception e) {
                }
            }
        }
    }
}

From source file:com.sfs.whichdoctor.analysis.FinancialSummaryAnalysisDAOImpl.java

/**
 * Builds the where./* w  ww. j av  a 2  s. c  o  m*/
 *
 * @param people the people
 * @param organisations the organisations
 *
 * @return the string
 */
private String buildWHERE(final Collection<PersonBean> people,
        final Collection<OrganisationBean> organisations) {

    StringBuffer sqlWHERE = new StringBuffer();

    if (people != null) {
        for (PersonBean person : people) {
            if (sqlWHERE.length() > 0) {
                sqlWHERE.append(" OR ");
            }
            sqlWHERE.append("financial_summary.PersonId = ");
            sqlWHERE.append(person.getGUID());
        }
    }
    if (organisations != null) {
        for (OrganisationBean organisation : organisations) {
            if (sqlWHERE.length() > 0) {
                sqlWHERE.append(" OR ");
            }
            sqlWHERE.append("financial_summary.OrganisationId = ");
            sqlWHERE.append(organisation.getGUID());
        }
    }

    if (sqlWHERE.length() > 0) {
        sqlWHERE.insert(0, " AND (");
        sqlWHERE.append(")");
    }
    return sqlWHERE.toString();
}

From source file:SignificantFigures.java

/**
 * Formats this number.//from   w  ww  .  j a  va 2  s  .c om
 * If the number is less than 10^-3 or greater than or equal to 10^7,
 * or the number might have an ambiguous number of significant figures,
 * scientific notation will be used.
 * <p>
 * A string such as "NaN" or "Infinity" may be returned by this method.
 *
 * @return representation of this number.
 *
 * @since ostermillerutils 1.00.00
 */
@Override
public String toString() {
    if (digits == null)
        return original;
    StringBuffer digits = new StringBuffer(this.digits.toString());
    int length = digits.length();
    if (mantissa <= -4 || mantissa >= 7 || (mantissa >= length && digits.charAt(digits.length() - 1) == '0')
            || (isZero && mantissa != 0)) {
        // use scientific notation.
        if (length > 1) {
            digits.insert(1, '.');
        }
        if (mantissa != 0) {
            digits.append("E" + mantissa);
        }
    } else if (mantissa <= -1) {
        digits.insert(0, "0.");
        for (int i = mantissa; i < -1; i++) {
            digits.insert(2, '0');
        }
    } else if (mantissa + 1 == length) {
        if (length > 1 && digits.charAt(digits.length() - 1) == '0') {
            digits.append('.');
        }
    } else if (mantissa < length) {
        digits.insert(mantissa + 1, '.');
    } else {
        for (int i = length; i <= mantissa; i++) {
            digits.append('0');
        }
    }
    if (!sign) {
        digits.insert(0, '-');
    }
    return digits.toString();
}

From source file:com.sfs.whichdoctor.dao.SavedSearchDAOImpl.java

/**
 * Used to get a Collection of SearchBean details for a public.
 *
 * @param filter the filter/* w w  w .j a v a2s. c om*/
 * @param subtype the subtype
 * @param username the username
 * @return the collection
 * @throws WhichDoctorDaoException the which doctor dao exception
 */
@SuppressWarnings("unchecked")
public final Collection<SearchBean> load(final String filter, final String subtype, final String username)
        throws WhichDoctorDaoException {

    final StringBuffer loadSearch = new StringBuffer();

    ArrayList<Object> parameters = new ArrayList<Object>();

    if (StringUtils.isNotBlank(filter)) {
        loadSearch.append(" AND (savedsearch.Name LIKE ? OR savedsearch.Description LIKE ?)");
        parameters.add("%" + filter + "%");
        parameters.add("%" + filter + "%");
    }
    if (StringUtils.isNotBlank(subtype)) {
        loadSearch.append(" AND Type = ?");
        parameters.add(subtype);
    }
    if (StringUtils.isNotBlank(username)) {
        loadSearch.append(" AND (savedsearch.UserDn = ? OR savedsearch.PublicSearch = true)");
        parameters.add(username);
    } else {
        loadSearch.append(" AND savedsearch.publicSearch = true");
    }

    if (loadSearch.length() > 0) {
        /* Delete the AND from the beginning of the search if defined */
        final int subtract = 5;
        loadSearch.delete(0, subtract);
        loadSearch.insert(0, " WHERE ");
    }
    loadSearch.insert(0, this.getSQL().getValue("search/load"));
    loadSearch.append(" ORDER BY savedsearch.Name");

    dataLogger.info("Retrieving saved public searches");

    Collection<SearchBean> savedsearches = new ArrayList<SearchBean>();

    try {
        savedsearches = this.getJdbcTemplateReader().query(loadSearch.toString(), parameters.toArray(),
                new RowMapper() {
                    public Object mapRow(final ResultSet rs, final int rowNum) throws SQLException {
                        return loadSearch(rs);
                    }
                });

    } catch (IncorrectResultSizeDataAccessException ie) {
        dataLogger.debug("No results found for search: " + ie.getMessage());
    }
    return savedsearches;
}