Example usage for java.lang StringBuffer delete

List of usage examples for java.lang StringBuffer delete

Introduction

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

Prototype

@Override
public synchronized StringBuffer delete(int start, int end) 

Source Link

Usage

From source file:org.apache.poi.ss.format.CellNumberFormatter.java

/** {@inheritDoc} */
public void formatValue(StringBuffer toAppendTo, Object valueObject) {
    double value = ((Number) valueObject).doubleValue();
    value *= scale;/*from   ww w . j av a 2  s  . co m*/

    // the '-' sign goes at the front, always, so we pick it out
    boolean negative = value < 0;
    if (negative)
        value = -value;

    // Split out the fractional part if we need to print a fraction
    double fractional = 0;
    if (slash != null) {
        if (improperFraction) {
            fractional = value;
            value = 0;
        } else {
            fractional = value % 1.0;
            //noinspection SillyAssignment
            value = (long) value;
        }
    }

    Set<StringMod> mods = new TreeSet<>();
    StringBuffer output = new StringBuffer(desc);

    if (exponent != null) {
        writeScientific(value, output, mods);
    } else if (improperFraction) {
        writeFraction(value, null, fractional, output, mods);
    } else {
        StringBuffer result = new StringBuffer();
        Formatter f = new Formatter(result);
        f.format(LOCALE, printfFmt, value);

        if (numerator == null) {
            writeFractional(result, output);
            writeInteger(result, output, integerSpecials, mods, integerCommas);
        } else {
            writeFraction(value, result, fractional, output, mods);
        }
    }

    // Now strip out any remaining '#'s and add any pending text ...
    ListIterator<Special> it = specials.listIterator();
    Iterator<StringMod> changes = mods.iterator();
    StringMod nextChange = (changes.hasNext() ? changes.next() : null);
    int adjust = 0;
    BitSet deletedChars = new BitSet(); // records chars already deleted
    while (it.hasNext()) {
        Special s = it.next();
        int adjustedPos = s.pos + adjust;
        if (!deletedChars.get(s.pos) && output.charAt(adjustedPos) == '#') {
            output.deleteCharAt(adjustedPos);
            adjust--;
            deletedChars.set(s.pos);
        }
        while (nextChange != null && s == nextChange.special) {
            int lenBefore = output.length();
            int modPos = s.pos + adjust;
            int posTweak = 0;
            switch (nextChange.op) {
            case StringMod.AFTER:
                // ignore adding a comma after a deleted char (which was a '#')
                if (nextChange.toAdd.equals(",") && deletedChars.get(s.pos))
                    break;
                posTweak = 1;
                //noinspection fallthrough
            case StringMod.BEFORE:
                output.insert(modPos + posTweak, nextChange.toAdd);
                break;

            case StringMod.REPLACE:
                int delPos = s.pos; // delete starting pos in original coordinates
                if (!nextChange.startInclusive) {
                    delPos++;
                    modPos++;
                }

                // Skip over anything already deleted
                while (deletedChars.get(delPos)) {
                    delPos++;
                    modPos++;
                }

                int delEndPos = nextChange.end.pos; // delete end point in original
                if (nextChange.endInclusive)
                    delEndPos++;

                int modEndPos = delEndPos + adjust; // delete end point in current

                if (modPos < modEndPos) {
                    if (nextChange.toAdd == "")
                        output.delete(modPos, modEndPos);
                    else {
                        char fillCh = nextChange.toAdd.charAt(0);
                        for (int i = modPos; i < modEndPos; i++)
                            output.setCharAt(i, fillCh);
                    }
                    deletedChars.set(delPos, delEndPos);
                }
                break;

            default:
                throw new IllegalStateException("Unknown op: " + nextChange.op);
            }
            adjust += output.length() - lenBefore;

            if (changes.hasNext())
                nextChange = changes.next();
            else
                nextChange = null;
        }
    }

    // Finally, add it to the string
    if (negative)
        toAppendTo.append('-');
    toAppendTo.append(output);
}

From source file:cgeo.geocaching.cgBase.java

public static String requestJSON(String scheme, String host, String path, String method, String params) {
    int httpCode = -1;
    //String httpLocation = null;

    if (method == null) {
        method = "GET";
    } else {//w ww.  j  a  v  a2  s .  co  m
        method = method.toUpperCase();
    }

    boolean methodPost = false;
    if (method.equalsIgnoreCase("POST")) {
        methodPost = true;
    }

    URLConnection uc = null;
    HttpURLConnection connection = null;
    Integer timeout = 30000;
    final StringBuffer buffer = new StringBuffer();

    for (int i = 0; i < 3; i++) {
        if (i > 0) {
            Log.w(cgSettings.tag, "Failed to download data, retrying. Attempt #" + (i + 1));
        }

        buffer.delete(0, buffer.length());
        timeout = 30000 + (i * 15000);

        try {
            try {
                URL u = null;
                if (methodPost) {
                    u = new URL(scheme + host + path);
                } else {
                    u = new URL(scheme + host + path + "?" + params);
                }

                if (u.getProtocol().toLowerCase().equals("https")) {
                    trustAllHosts();
                    HttpsURLConnection https = (HttpsURLConnection) u.openConnection();
                    https.setHostnameVerifier(doNotVerify);
                    uc = https;
                } else {
                    uc = (HttpURLConnection) u.openConnection();
                }

                uc.setRequestProperty("Host", host);
                uc.setRequestProperty("Accept", "application/json, text/javascript, */*; q=0.01");
                if (methodPost) {
                    uc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                    uc.setRequestProperty("Content-Length", Integer.toString(params.length()));
                    uc.setRequestProperty("X-HTTP-Method-Override", "GET");
                } else {
                    uc.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
                }
                uc.setRequestProperty("X-Requested-With", "XMLHttpRequest");

                connection = (HttpURLConnection) uc;
                connection.setReadTimeout(timeout);
                connection.setRequestMethod(method);
                HttpURLConnection.setFollowRedirects(false); // TODO: Fix these (FilCab)
                connection.setDoInput(true);
                if (methodPost) {
                    connection.setDoOutput(true);

                    final OutputStream out = connection.getOutputStream();
                    final OutputStreamWriter wr = new OutputStreamWriter(out);
                    wr.write(params);
                    wr.flush();
                    wr.close();
                } else {
                    connection.setDoOutput(false);
                }

                InputStream ins = getInputstreamFromConnection(connection);
                final InputStreamReader inr = new InputStreamReader(ins);
                final BufferedReader br = new BufferedReader(inr, 1024);

                readIntoBuffer(br, buffer);

                httpCode = connection.getResponseCode();

                final String paramsLog = params.replaceAll(passMatch, "password=***");
                Log.i(cgSettings.tag + " | JSON",
                        "[POST " + (int) (params.length() / 1024) + "k | " + httpCode + " | "
                                + (int) (buffer.length() / 1024) + "k] Downloaded " + "http://" + host + path
                                + "?" + paramsLog);

                connection.disconnect();
                br.close();
                ins.close();
                inr.close();
            } catch (IOException e) {
                httpCode = connection.getResponseCode();

                Log.e(cgSettings.tag, "cgeoBase.requestJSON.IOException: " + httpCode + ": "
                        + connection.getResponseMessage() + " ~ " + e.toString());
            }
        } catch (Exception e) {
            Log.e(cgSettings.tag, "cgeoBase.requestJSON: " + e.toString());
        }

        if (StringUtils.isNotBlank(buffer)) {
            break;
        }

        if (httpCode == 403) {
            // we're not allowed to download content, so let's move
            break;
        }
    }

    String page = null;
    //This is reported as beeing deadCode (httpLocation is always null)
    //2011-08-09 - 302 is redirect so something should probably be done
    /*
     * if (httpCode == 302 && httpLocation != null) {
     * final Uri newLocation = Uri.parse(httpLocation);
     * if (newLocation.isRelative()) {
     * page = requestJSONgc(host, path, params);
     * } else {
     * page = requestJSONgc(newLocation.getHost(), newLocation.getPath(), params);
     * }
     * } else {
     */
    replaceWhitespace(buffer);
    page = buffer.toString();
    //}

    if (page != null) {
        return page;
    } else {
        return "";
    }
}

From source file:org.jmlspecs.util.QDoxUtil.java

private static String handleConstructDeclInJMLFileMode(StringBuffer bufferedFile, String fileAsString,
        List<JavaMethod> javaDeclMeths) throws IOException {

    BufferedReader buffer;/*from w  ww.j av a 2s.c om*/
    String line;
    for (Iterator<JavaMethod> iterator = javaDeclMeths.iterator(); iterator.hasNext();) {
        JavaMethod javaMethod = iterator.next();
        if (!javaMethod.isConstructor()) {
            continue;
        }
        int lineNumber = javaMethod.getLineNumber();
        buffer = new BufferedReader(new StringReader(fileAsString));
        line = buffer.readLine();
        int fileLineNumber = 1;
        boolean canStart = false;
        while (line != null) {
            if (lineNumber == fileLineNumber) {
                canStart = true;
            }
            if (canStart) {
                bufferedFile.append(line);
                bufferedFile.append("\n");
                JavaDocBuilder qDoxJavaMethodParser = new JavaDocBuilder();
                try {
                    qDoxJavaMethodParser.addSource(new StringReader(
                            "public class JMethodParser{\n" + bufferedFile.toString() + "\n}"));
                    if (qDoxJavaMethodParser.getClassByName("JMethodParser").getMethods().length == 1) {
                        // if match the wanted contructor
                        if (line.contains(";")) {
                            String lineProcessed = line.replace(";", "");
                            fileAsString = StringUtils.replaceOnce(fileAsString, bufferedFile.toString(),
                                    bufferedFile.toString().replace(line, lineProcessed) + "{}");
                        }
                        bufferedFile.delete(0, (bufferedFile.length() - 1));
                        break;
                    }
                } catch (com.thoughtworks.qdox.parser.ParseException e) {
                    // continue if it is not a valid method or constructor... [[[hemr]]]
                }
            }
            line = buffer.readLine();
            fileLineNumber++;
        }
    }

    return fileAsString;
}

From source file:org.zkoss.poi.ss.format.CellNumberFormatter.java

/** {@inheritDoc} */
public void formatValue(StringBuffer toAppendTo, Object valueObject) {
    double value = ((Number) valueObject).doubleValue();
    value *= scale;/*from w  ww  . j  a  va 2 s  . c  o m*/

    // For negative numbers:
    // - If the cell format has a negative number format, this method
    // is called with a positive value and the number format has
    // the negative formatting required, e.g. minus sign or brackets.
    // - If the cell format does not have a negative number format,
    // this method is called with a negative value and the number is
    // formatted with a minus sign at the start.
    boolean negative = value < 0;
    if (negative)
        value = -value;

    // Split out the fractional part if we need to print a fraction
    double fractional = 0;
    if (slash != null) {
        if (improperFraction) {
            fractional = value;
            value = 0;
        } else {
            fractional = value % 1.0;
            //noinspection SillyAssignment
            value = (long) value;
        }
    }

    Set<StringMod> mods = new TreeSet<StringMod>();
    StringBuffer output = new StringBuffer(desc);

    if (exponent != null) {
        writeScientific(value, output, mods);
    } else if (improperFraction) {
        writeFraction(value, null, fractional, output, mods);
    } else {
        StringBuffer result = new StringBuffer();
        Formatter f = new Formatter(result, locale); //ZSS-68
        f.format(locale, printfFmt, value); //ZSS-68

        if (numerator == null) {
            writeFractional(result, output);
            writeInteger(result, output, integerSpecials, mods, integerCommas, false);
        } else {
            writeFraction(value, result, fractional, output, mods);
        }
    }

    // Now strip out any remaining '#'s and add any pending text ...
    ListIterator<Special> it = specials.listIterator();
    Iterator<StringMod> changes = mods.iterator();
    StringMod nextChange = (changes.hasNext() ? changes.next() : null);
    int adjust = 0;
    BitSet deletedChars = new BitSet(); // records chars already deleted
    final String groupSeparator = "" + Formatters.getGroupingSeparator(locale); //ZSS-68
    while (it.hasNext()) {
        Special s = it.next();
        int adjustedPos = s.pos + adjust;
        if (!deletedChars.get(s.pos) && output.charAt(adjustedPos) == '#') {
            output.deleteCharAt(adjustedPos);
            adjust--;
            deletedChars.set(s.pos);
        }
        while (nextChange != null && s == nextChange.special) {
            int lenBefore = output.length();
            int modPos = s.pos + adjust;
            int posTweak = 0;
            switch (nextChange.op) {
            case StringMod.AFTER:
                // ignore adding a comma after a deleted char (which was a '#')
                if (nextChange.toAdd.equals(groupSeparator) && deletedChars.get(s.pos)) //20110321, henrichen@zkoss.org: respect current locale
                    break;
                posTweak = 1;
                //noinspection fallthrough
            case StringMod.BEFORE:
                output.insert(modPos + posTweak, nextChange.toAdd);
                break;

            case StringMod.REPLACE:
                int delPos = s.pos; // delete starting pos in original coordinates
                if (!nextChange.startInclusive) {
                    delPos++;
                    modPos++;
                }

                // Skip over anything already deleted
                while (deletedChars.get(delPos)) {
                    delPos++;
                    modPos++;
                }

                int delEndPos = nextChange.end.pos; // delete end point in original
                if (nextChange.endInclusive)
                    delEndPos++;

                int modEndPos = delEndPos + adjust; // delete end point in current

                if (modPos < modEndPos) {
                    if (nextChange.toAdd == "")
                        output.delete(modPos, modEndPos);
                    else {
                        char fillCh = nextChange.toAdd.charAt(0);
                        for (int i = modPos; i < modEndPos; i++)
                            output.setCharAt(i, fillCh);
                    }
                    deletedChars.set(delPos, delEndPos);
                }
                break;

            default:
                throw new IllegalStateException("Unknown op: " + nextChange.op);
            }
            adjust += output.length() - lenBefore;

            if (changes.hasNext())
                nextChange = changes.next();
            else
                nextChange = null;
        }
    }

    // Finally, add it to the string
    if (negative)
        toAppendTo.append('-');
    toAppendTo.append(output);
}

From source file:dao.CollabrumDaoDb.java

/**
 * delete a stream blob//from   ww  w  . j ava 2  s.  co  m
 * This method is called when stream blob is to be deleted
 * @param entryId - the entryid
 * @param collabrumId - the collabrum id 
 * @param userId - the user Id
 * @param userLogin - the user login
 * @throws BaseDaoException If we have a problem interpreting the data or the data is missing or incorrect
*/
public void deleteStreamBlob(String entryId, String collabrumId, String userId, String userLogin)
        throws BaseDaoException {

    if (RegexStrUtil.isNull(entryId) || RegexStrUtil.isNull(collabrumId) || RegexStrUtil.isNull(userId)
            || RegexStrUtil.isNull(userLogin)) {
        throw new BaseDaoException("params are null in deleteStreamBlob");
    }

    /** 
    * check authority to delete - diaryAdmin & isOrganizer are checked
    */
    if (!isOrganizer(collabrumId, userLogin, userId)) {
        StringBuffer sb = new StringBuffer("No permission to delete streamblobs in collabrum ");
        sb.append(collabrumId);
        sb.append(" userId ");
        sb.append(userId);
        throw new BaseDaoException(sb.toString());
    }

    /**
      *  Get scalability datasource, collblob is partitioned on collabrumId
      */
    String sourceName = scalabilityManager.getWriteBlobScalability(collabrumId);
    ds = scalabilityManager.getSource(sourceName);
    if (ds == null) {
        StringBuffer sb = new StringBuffer("ds is null for deleteStreamBlob() in collabrumDaoDb ");
        sb.append(sourceName);
        sb.append(" collabrumId = ");
        sb.append(collabrumId);
        throw new BaseDaoException(sb.toString());
    }

    boolean exists = false;
    String defId = null;
    try {
        Object[] params = { (Object) collabrumId };
        List result = defaultQuery.execute(params);
        if (result != null && result.size() > 0) {
            defId = ((Photo) result.get(0)).getValue(DbConstants.ENTRYID);
            if (!RegexStrUtil.isNull(defId) && defId.equals(entryId)) {
                exists = true;
            }
        }
    } catch (Exception e) {
        throw new BaseDaoException("error while" + defaultQuery.getSql());
    }

    Connection conn = null;
    try {
        conn = ds.getConnection();
        deleteStreamblobQuery.run(conn, entryId);
        if (exists) {
            deleteDefQuery.run(conn, collabrumId);
        }
    } catch (Exception e) {
        try {
            if (conn != null) {
                conn.close();
            }
        } catch (Exception e2) {
            throw new BaseDaoException("deleteStreamBlob/deleteDefQuery error ", e2);
        }
    }

    try {
        if (conn != null) {
            conn.close();
        }
    } catch (Exception e) {
        throw new BaseDaoException("deleteStreamBlob/deleteDefQuery error ", e);
    }

    /**
     * Jboss methods - 
     * fqn - full qualified name
     * check if the streamblob already set in the cache
     * If it exists, remove the bean from the cache.
     */
    Fqn fqn = cacheUtil.fqn(DbConstants.PHOTO);
    if (treeCache.exists(fqn, entryId)) {
        treeCache.remove(fqn, entryId);
    }

    StringBuffer buf = new StringBuffer(collabrumId);
    buf.append("-");
    buf.append(entryId);
    String key = buf.toString();
    fqn = cacheUtil.fqn(DbConstants.COL_STREAM_BLOB);
    if (treeCache.exists(fqn, key)) {
        treeCache.remove(fqn, key);
    }
    fqn = cacheUtil.fqn(DbConstants.DEFAULT_PHOTO);
    if (treeCache.exists(fqn, key)) {
        treeCache.remove(fqn, key);
    }

    /* default photo */
    fqn = cacheUtil.fqn(DbConstants.DEFAULT_PHOTO);
    if (!RegexStrUtil.isNull(defId)) {
        buf.delete(0, buf.length());
        buf.append(collabrumId);
        buf.append("-");
        buf.append(defId);
        key = buf.toString();
        if (treeCache.exists(fqn, key)) {
            treeCache.remove(fqn, key);
        }
    }

    fqn = cacheUtil.fqn(DbConstants.COLLABRUM);
    if (treeCache.exists(fqn, collabrumId)) {
        treeCache.remove(fqn, collabrumId);
    }

    fqn = cacheUtil.fqn(DbConstants.COLLABRUM_STREAM_BLOBS);
    if (treeCache.exists(fqn, collabrumId)) {
        treeCache.remove(fqn, collabrumId);
    }

    fqn = cacheUtil.fqn(DbConstants.COLL_CAT);
    StringBuffer sb = new StringBuffer(collabrumId);
    sb.append("-");
    sb.append(DbConstants.PHOTO_CATEGORY);
    if (treeCache.exists(fqn, sb.toString())) {
        treeCache.remove(fqn, sb.toString());
    }

    sb.delete(0, sb.length());
    sb.append(collabrumId);
    sb.append("-");
    sb.append(DbConstants.FILE_CATEGORY);
    if (treeCache.exists(fqn, sb.toString())) {
        treeCache.remove(fqn, sb.toString());
    }
}

From source file:dao.CarryonDaoDb.java

/**
 * Given a entryid, delete carryon info for the user.
 * @param entryid - the entry id/*from ww  w .  jav a2s .c  o  m*/
 * @param memberId - the member id
 * @param category - the category
 * @param member - the member
 * @throws BaseDaoException If we have a problem interpreting the data or the data is missing or incorrect
 */
public void deleteCarryon(String entryid, String memberId, String category, String member)
        throws BaseDaoException {

    if (RegexStrUtil.isNull(memberId) || RegexStrUtil.isNull(entryid) || RegexStrUtil.isNull(member)) {
        throw new BaseDaoException("null parameters passed");
    }

    if (WebUtil.isSanEnabled()) {
        Photo photo = getPhoto(memberId, entryid, DbConstants.READ_FROM_SLAVE);
        String btitle = null;
        if (photo != null) {
            btitle = photo.getValue(DbConstants.BTITLE);
        }
        try {
            SanUtils sanUtils = new SanUtils();
            sanUtils.deleteSanFile(member, SanConstants.sanUserPath, btitle);
        } catch (SanException e) {
            throw new BaseDaoException("deleteSanFile() in CarryonDaoDb " + member + " destFileName " + btitle,
                    e);
        }
    }

    /**
     * Set the source based on scalability
     */
    String sourceName = scalabilityManager.getWriteBlobScalability(memberId);
    ds = scalabilityManager.getSource(sourceName);
    if (ds == null) {
        throw new BaseDaoException("ds is null for sourceName = " + sourceName);
    }

    boolean exists = false;
    try {
        Object[] params = { (Object) entryid };
        List result = defaultQuery.execute(params);
        if (result != null && result.size() > 0) {
            exists = true;
        }
    } catch (Exception e) {
        throw new BaseDaoException("error while" + defaultQuery.getSql());
    }

    /**
     * if this is a default blob, delete blob and default entry in a transaction
     * if this is anot a default blob, delete the blob in the regular way.
     */
    if (exists) {
        Connection conn = null;
        try {
            conn = ds.getConnection();
            conn.setAutoCommit(false);
            deleteCarryonQuery.run(conn, entryid, memberId);
            deleteDefQuery.run(conn, memberId);
        } catch (Exception e) {
            try {
                conn.rollback();
            } catch (Exception e1) {
                try {
                    if (conn != null) {
                        conn.setAutoCommit(true);
                        conn.close();
                    }
                } catch (Exception e2) {
                    throw new BaseDaoException(
                            "error in deleting carryon entry, conn.close() while deleting carryonentry in transaction"
                                    + member + " entryid = " + entryid,
                            e2);
                }
                throw new BaseDaoException(
                        "error in rollback() carryon delete entry" + member + " entryid = " + entryid, e1);
            }
            throw new BaseDaoException("error in carryondelete entry" + member + " entryid = " + entryid, e);
        }

        try {
            conn.commit();
        } catch (Exception e3) {
            throw new BaseDaoException("commit exception", e3);
        }

        try {
            if (conn != null) {
                conn.setAutoCommit(true);
                conn.close();
            }
        } catch (Exception e4) {
            try {
                if (conn != null) {
                    conn.close();
                }
            } catch (Exception e5) {
                throw new BaseDaoException("connection close exception", e5);
            }
            throw new BaseDaoException("setAutoCommit(true)/connection close exception", e4);
        }
    } else { // not a default entry 
        try {
            deleteQuery.run(entryid, memberId);
        } catch (Exception e) {
            StringBuffer sb = new StringBuffer(
                    "error occured while executing in CarryonDeleteQuery(),  entryid = ");
            sb.append(entryid);
            sb.append(" memberId = ");
            sb.append(memberId);
            throw new BaseDaoException(sb.toString(), e);
        }
    }

    /* remove this entry from carryon hits, if this entry exists */
    try {
        deleteCarryonHits(entryid, memberId);
    } catch (Exception e) {
        throw new BaseDaoException("deleteCarryonHits error");
    }

    /**
     * deleteTagsQuery
     */
    sourceName = scalabilityManager.getWriteZeroScalability();
    ds = scalabilityManager.getSource(sourceName);
    if (ds == null) {
        throw new BaseDaoException("ds is null for sourceName = " + sourceName);
    }
    try {
        deleteTagsQuery.run(memberId, entryid);
        deleteRecentQuery.run(memberId, entryid);
    } catch (Exception e) {
        throw new BaseDaoException("deleteTagsQuery error " + deleteTagsQuery.getSql() + " recent Query = "
                + deleteRecentQuery.getSql(), e);
    }

    /**
     * remove from userstreamblob based on the key (memberId+entryid)
     */
    StringBuffer sb = new StringBuffer(memberId);
    sb.append("-");
    sb.append(entryid);
    String key = sb.toString();
    Fqn fqn = cacheUtil.fqn(DbConstants.USER_STREAM_BLOB_ENTRY);
    if (treeCache.exists(fqn, key)) {
        treeCache.remove(fqn, key);
    }

    fqn = cacheUtil.fqn(DbConstants.USER_STREAM_BLOB_DATA);
    if (treeCache.exists(fqn, key)) {
        treeCache.remove(fqn, key);
    }

    fqn = cacheUtil.fqn(DbConstants.RECENT_CARRYON);
    if (treeCache.exists(fqn, DbConstants.RECENT_CARRYON)) {
        treeCache.remove(fqn, DbConstants.RECENT_CARRYON);
    }

    /* remove all entries for this user, key based on memberId */
    fqn = cacheUtil.fqn(DbConstants.USER_STREAM_BLOB);
    if (treeCache.exists(fqn, memberId)) {
        treeCache.remove(fqn, memberId);
    }

    /**
     * get stream blobs
     */
    fqn = cacheUtil.fqn(DbConstants.USER_STREAM_BLOBS_CAT);
    sb.delete(0, sb.length());
    sb.append(memberId);
    sb.append("-");
    sb.append(category);
    if (treeCache.exists(fqn, sb.toString())) {
        treeCache.remove(fqn, sb.toString());
    }

    fqn = cacheUtil.fqn(DbConstants.USER_PAGE);
    if (treeCache.exists(fqn, member)) {
        treeCache.remove(fqn, member);
    }
}

From source file:com.mysql.stresstool.RunnableQueryInsertDR.java

@Override
public boolean createSchema(StressTool sTool) {

    // Custom schema creation this is the default for the stresstool but can be anything  
    String DropTables1 = "Drop table IF EXISTS tbtest";
    String DropTables2 = "Drop table IF EXISTS tbtest_child";

    String TruncateTables1 = "Truncate table tbtest";
    String TruncateTables2 = "Truncate table tbtest_child";

    Connection conn = null;//ww  w  .j  a va2 s .  co  m
    Statement stmt = null;

    try {
        if (jdbcUrlMap.get("dbType") != null && !((String) jdbcUrlMap.get("dbType")).equals("MySQL")) {
            conn = DriverManager.getConnection((String) jdbcUrlMap.get("dbType"), "test", "test");
        } else
            conn = DriverManager.getConnection((String) jdbcUrlMap.get("jdbcUrl"));

        conn.setAutoCommit(false);
        stmt = conn.createStatement();

        StringBuffer sb = new StringBuffer();

        for (int iTable = 1; iTable <= this.getNumberOfprimaryTables(); iTable++) {
            sb.append("CREATE TABLE IF NOT EXISTS tbtest" + iTable);

            //            if (this.isUseAutoIncrement()){
            //               sb.append("`autoInc` bigint(11) AUTO_INCREMENT NOT NULL,");
            //            }
            //            sb.append(" `a` int(11) NOT NULL,"); 
            //            sb.append(" `uuid` char(36) NOT NULL,");
            //            sb.append(" `b` varchar(100) NOT NULL,");
            //            sb.append(" `c` char(200)  NOT NULL,");
            //            sb.append(" `counter` bigint(20) NULL, ");
            //            sb.append(" `time` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,");
            //            sb.append(" `partitionid` int NOT NULL DEFAULT 0,");
            //            sb.append(" `date` DATE NOT NULL,");
            //            sb.append(" `strrecordtype` char(3) NULL");
            //            if (this.isUseAutoIncrement()){
            //                if(this.partitionType.equals("range")){
            //               sb.append(", PRIMARY KEY  (`autoInc`,`date`),  INDEX `IDX_a` (a),  INDEX `IDX_uuid` (uuid) ");
            //                }
            //                else{
            //               sb.append(", PRIMARY KEY  (`autoInc`,`partitionid`),  INDEX `IDX_a` (a),  INDEX `IDX_uuid` (uuid) ");
            //                }
            //            }
            //            else{
            //               if(!this.doSimplePk)
            //                   if(this.partitionType.equals("range")){
            //                      sb.append(", PRIMARY KEY  (`uuid`,`date`),  INDEX `IDX_a` (a) ");
            //                   }
            //                   else{
            //                  sb.append(", PRIMARY KEY  (`uuid`,`partitionid`),  INDEX `IDX_a` (a) ");
            //                   }
            //               else{ 
            //                   if(this.partitionType.equals("range")){
            //                  sb.append(", PRIMARY KEY  (`a`,`date`),  INDEX `IDX_uuid` (uuid) ");
            //                   }
            //                   else{
            //                  sb.append(", PRIMARY KEY  (`a`,`partitionid`),  INDEX `IDX_uuid` (uuid) ");
            //                   }
            //               }
            //            }
            sb.append(
                    "(`emp_no` int(4) unsigned AUTO_INCREMENT NOT NULL,`birth_date` date NOT NULL,`first_name` varchar(14) NOT NULL,"
                            + "`last_name` varchar(16) NOT NULL,`gender` enum('M','F') NOT NULL,`hire_date` date NOT NULL,"
                            + "`city_id` int(4) DEFAULT NULL,`CityName` varchar(150) DEFAULT NULL,`CountryCode` char(3) DEFAULT NULL,"
                            + "`UUID` char(36) DEFAULT NULL, PRIMARY KEY (`emp_no`)) ");

            sb.append(" ENGINE=" + sTool.tableEngine);

            if (!sb.toString().equals(""))
                stmt.addBatch(sb.toString());

            sb.delete(0, sb.length());
        }
        String tbts1 = sb.toString();

        sb = new StringBuffer();
        for (int iTable = 1; iTable <= this.getNumberOfSecondaryTables(); iTable++) {
            sb.append("CREATE TABLE IF NOT EXISTS tbtest_child" + iTable);
            sb.append("(`a` int(11) NOT NULL,");
            sb.append("`bb` int(11) AUTO_INCREMENT NOT NULL,");
            sb.append(" `date` DATE NOT NULL,");
            sb.append(" `partitionid` int NOT NULL DEFAULT 0,");
            if (operationShort)
                sb.append(" `stroperation` VARCHAR(254)  NULL,");
            else
                sb.append(" `stroperation` TEXT(41845)  NULL,");

            sb.append(" `time` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP");
            sb.append(", PRIMARY KEY  (`a`,`bb`), UNIQUE(`bb`)");
            sb.append(") ENGINE=" + sTool.tableEngine);

            if (!sb.toString().equals(""))
                stmt.addBatch(sb.toString());

            sb.delete(0, sb.length());

        }
        String tbts2 = sb.toString();

        System.out.println(tbts1);
        if (!doSimplePk)
            System.out.println(tbts2);

        if (sTool.droptable) {
            System.out.println(
                    "****============================================================================*******");
            for (int iTable = 1; iTable <= this.getNumberOfprimaryTables(); iTable++) {
                System.out.println(
                        "**** Please wait DROP table tbtest" + iTable + " it could take a LOT of time *******");
                stmt.execute(DropTables1 + iTable);
            }

            if (!doSimplePk) {
                for (int iTable = 1; iTable <= this.getNumberOfSecondaryTables(); iTable++) {
                    System.out.println("**** Please wait DROP table tbtest_child" + iTable
                            + " it could take a LOT of time *******");
                    stmt.execute(DropTables2 + iTable);
                }

            }
            stmt.execute("COMMIT");
            System.out.println("**** DROP finished *******");
            System.out.println(
                    "****============================================================================*******");

        }

        if (sTool.createtable)
            stmt.executeBatch();

        if (sTool.truncate) {
            System.out.println(
                    "****============================================================================*******");

            for (int iTable = 1; iTable <= this.getNumberOfprimaryTables(); iTable++) {
                System.out.println("**** Please wait TRUNCATE table tbtest" + iTable
                        + " it could take a LOT of time *******");
                stmt.execute(TruncateTables1 + iTable);
            }

            if (!doSimplePk) {
                for (int iTable = 1; iTable <= this.getNumberOfSecondaryTables(); iTable++) {
                    System.out.println("**** Please wait TRUNCATE table tbtest_child" + iTable
                            + " it could take a LOT of time *******");
                    stmt.execute(TruncateTables2 + iTable);
                }
            }
            System.out.println("**** TRUNCATE finish *******");
            System.out.println(
                    "****============================================================================*******");

        }

    } catch (Exception ex) {
        ex.printStackTrace(

        );
        return false;
    } finally {

        try {
            conn.close();
            return true;
        } catch (SQLException ex1) {
            ex1.printStackTrace();
            return false;
        }

    }

}

From source file:org.sakaiproject.reports.logic.impl.ReportsManagerImpl.java

public String replaceSystemValues(String string, Map beans) {

    StringBuffer buffer = new StringBuffer(string);
    Set beanNames = beans.keySet();
    for (Iterator it = beanNames.iterator(); it.hasNext();) {
        String beanName = (String) it.next();
        // see if the string contains reference(s) to the supported beans
        for (int i = buffer.indexOf(beanName), j = beanName.length(); i != -1; i = buffer.indexOf(beanName)) {
            // if it does, parse the property of the bean the report query references
            int k = buffer.indexOf("}", i + j);
            if (k == -1)
                throw new RuntimeException("Missing closing brace \"}\" in report query: " + string);
            String property = buffer.substring(i + j, k);

            // construct the bean property's corresponding "getter" method
            String getter = null;
            String param = null;/*from  w  w w .java2  s  .  c  o  m*/
            if (beanName.indexOf(".attribute.") != -1) {
                getter = "getAttribute";
                param = property;
            } else if (beanName.indexOf(".property.") != -1) {
                getter = "getProperties";
                param = null;
            } else {
                getter = "get" + Character.toUpperCase(property.charAt(0)) + property.substring(1);
                param = null;
            }

            try {
                // use reflection to invoke the method on the bean
                Object bean = beans.get(beanName);
                Class clasz = bean.getClass();
                Class[] args = param == null ? (Class[]) null : new Class[] { String.class };
                Method method = clasz.getMethod(getter, args);
                Object result = method.invoke(bean, (param == null ? (Object[]) null : new Object[] { param }));

                if (beanName.indexOf(".property.") != -1) {
                    clasz = org.sakaiproject.entity.api.ResourceProperties.class;
                    getter = "getProperty";
                    args = new Class[] { String.class };
                    param = property;
                    method = clasz.getMethod(getter, args);
                    result = method.invoke(result, new Object[] { param });
                }

                // replace the bean expression in the report query with the actual value of calling the bean's corresponding getter method
                buffer.delete(i, k + 1);
                buffer.insert(i,
                        (result == null ? "null"
                                : result instanceof Time ? ((Time) result).toStringSql()
                                        : result.toString().replaceAll("'", "''")));
            } catch (Exception ex) {
                throw new RuntimeException(ex.getMessage(), ex);
            }
        }
    }
    return buffer.toString();
}

From source file:ubc.pavlab.aspiredb.server.service.ProjectServiceImpl.java

@Override
@RemoteMethod/*from  w w w.  j  a va 2 s  . c o  m*/
public String addSubjectVariantsPhenotypeToProject(final String variantFilename, final String phenotypeFilename,
        final boolean createProject, final String projectName, final String variantType, final boolean dryRun) {

    // Run the upload task on a separate thread so we don't block the current thread and return a proxy error on the
    // front end
    class ProjectUploadThread extends Thread {

        SecurityContext context;

        public ProjectUploadThread(SecurityContext context) {
            this.context = context;
        }

        @Override
        public void run() {

            SecurityContextHolder.setContext(this.context);

            StopWatch timer = new StopWatch();
            timer.start();

            StringBuffer returnMsg = new StringBuffer();
            StringBuffer errMsg = new StringBuffer();

            VariantUploadServiceResult variantResult = null;
            Collection<Variant2VariantOverlap> overlap = null;
            PhenotypeUploadServiceResult phenResult = null;

            final String STR_FMT = "%35s: %5s\n";

            returnMsg.append(String.format(STR_FMT, "Project", projectName) + "\n");

            if (variantFilename.length() > 0) {

                try {
                    variantResult = addSubjectVariantsToProject(variantFilename, createProject, projectName,
                            variantType, dryRun);
                    returnMsg.append(
                            String.format(STR_FMT, "Number of Subjects", getSubjects(projectName).size()));
                    returnMsg.append(String.format(STR_FMT, "Number of Variants",
                            variantResult.getVariantsToAdd().size()));
                    for (String err : variantResult.getErrorMessages()) {
                        errMsg.append(err + "\n");
                    }

                    if (!dryRun) {
                        // only run SpecialProject overlap if projectName is not a special project
                        try {
                            SpecialProject.valueOf(projectName);
                        } catch (IllegalArgumentException argEx) {
                            for (Project specialProject : projectDao.getSpecialOverlapProjects()) {
                                try {
                                    overlap = projectManager.populateProjectToProjectOverlap(projectName,
                                            specialProject.getName(), variantResult.getVariantsToAdd());
                                    returnMsg.append(String.format(STR_FMT,
                                            "Number of Overlaps with " + specialProject.getName(),
                                            overlap.size()));
                                } catch (Exception e) {
                                    log.error(e.getLocalizedMessage(), e);
                                    errMsg.append(e.getLocalizedMessage() + "\n");
                                }
                            }
                        }
                    }

                } catch (Exception e) {
                    log.error(e.getLocalizedMessage(), e);
                    errMsg.append(e.getLocalizedMessage() + "\n");
                }
            }

            if (phenotypeFilename.length() > 0) {
                try {
                    phenResult = addSubjectPhenotypeToProject(phenotypeFilename, createProject, projectName,
                            dryRun);
                    if (returnMsg.indexOf("Number of Subjects") == -1) {
                        returnMsg.append(
                                String.format(STR_FMT, "Number of Subjects", getSubjects(projectName).size()));
                    }
                    returnMsg.append(String.format(STR_FMT, "Number of Phenotypes",
                            phenResult.getPhenotypesToAdd().size()));
                    for (String err : phenResult.getErrorMessages()) {
                        errMsg.append(err + "\n");
                    }
                } catch (Exception e) {
                    log.error(e.getLocalizedMessage(), e);
                    errMsg.append(e.getLocalizedMessage() + "\n");
                }
            }

            log.info("Uploading took " + timer.getTime() + " ms");

            // trim errorMssage
            final int ERRMSG_LIMIT = 500;
            if (errMsg.length() > ERRMSG_LIMIT) {
                errMsg.delete(ERRMSG_LIMIT, errMsg.length() - 1);
                errMsg.append("\n...\n");
            }

            String returnStr = returnMsg.toString();
            returnStr += errMsg.length() > 0 ? "\nExceptions\n" + errMsg : "";

            log.info(returnStr);

            if (!dryRun) {
                // email users that the upload has finished

                // if ( timer.getTime() > ConfigUtils.getLong( "aspiredb.uploadTimeThreshold", 60000 ) ) {
                emailUploadFinished(projectName, returnStr);
                // }
            }

        }
    }

    ProjectUploadThread thread = new ProjectUploadThread(SecurityContextHolder.getContext());
    thread.setName(ProjectUploadThread.class.getName() + "_" + projectName + "_load_thread_"
            + RandomStringUtils.randomAlphanumeric(5));
    // To prevent VM from waiting on this thread to shutdown (if shutting down).
    thread.setDaemon(true);
    thread.start();

    return thread.getName();
}

From source file:com.wabacus.system.component.application.report.EditableListReportType2.java

protected String showDataRowInAddMode(List<ColBean> lstColBeans, int rowidx) {
    if (rrequest.getShowtype() != Consts.DISPLAY_ON_PAGE || this.realAccessMode.equals(Consts.READONLY_MODE)) {
        return super.showDataRowInAddMode(lstColBeans, rowidx);
    }/*  w w  w.ja  v a 2 s  . com*/
    StringBuffer resultBuf = new StringBuffer();
    boolean isReadonlyByRowInterceptor = false;
    RowDataBean rowInterceptorObjTmp = null;
    String trstylepropertyTmp = this.rbean.getDbean().getValuestyleproperty(rrequest, false);
    if (this.rbean.getInterceptor() != null) {
        rowInterceptorObjTmp = new RowDataBean(this, trstylepropertyTmp, lstColBeans, null, rowidx,
                this.cacheDataBean.getTotalColCount());
        this.rbean.getInterceptor().beforeDisplayReportDataPerRow(this.rrequest, this.rbean,
                rowInterceptorObjTmp);
        if (rowInterceptorObjTmp.getInsertDisplayRowHtml() != null)
            resultBuf.append(rowInterceptorObjTmp.getInsertDisplayRowHtml());
        if (!rowInterceptorObjTmp.isShouldDisplayThisRow()) {
            this.global_rowindex++;
            return resultBuf.toString();
        }
        trstylepropertyTmp = rowInterceptorObjTmp.getRowstyleproperty();
        isReadonlyByRowInterceptor = rowInterceptorObjTmp.isReadonly();
    }
    EditableReportColDataBean ercdatabeanTmp;
    String col_displayvalue;
    StringBuffer tdPropsBuf = null;
    ColDisplayData colDisplayData;
    resultBuf.append(showDataRowTrStart(rowInterceptorObjTmp, trstylepropertyTmp, rowidx, false));
    resultBuf.append(" EDIT_TYPE=\"add\">");//?
    int colDisplayModeTmp;
    boolean isReadonlyByColInterceptor;
    for (ColBean cbean : lstColBeans) {
        //if(Consts.COL_DISPLAYTYPE_HIDDEN.equals(cbean.getDisplaytype())) continue; //??
        tdPropsBuf = new StringBuffer();
        boolean isEditableCol = false;
        resultBuf.append("<td class='" + getDataTdClassName() + "'");
        if (cbean.getUpdateColBeanDest(false) != null) {
            resultBuf.append(" updatecolDest=\"").append(cbean.getUpdateColBeanDest(false).getProperty())
                    .append("\"");
        } else if (cbean.getUpdateColBeanSrc(false) != null) {
            resultBuf.append(" updatecolSrc=\"").append(cbean.getUpdateColBeanSrc(false).getProperty())
                    .append("\"");
        }
        colDisplayModeTmp = this.cacheDataBean.getColDisplayModeAfterAuthorize(cbean, true);
        if (colDisplayModeTmp < 0) {
            resultBuf.append(" id=\"").append(EditableReportAssistant.getInstance().getInputBoxId(cbean))
                    .append("__td" + rowidx).append("\"");
            resultBuf.append(" value_name=\"").append(Consts_Private.COL_NONDISPLAY_PERMISSION_PREX)
                    .append(EditableReportAssistant.getInstance().getColParamName(cbean)).append("\"");
            resultBuf.append(" style=\"display:none;\"></td>");
            continue;
        }
        ercdatabeanTmp = EditableReportColDataBean.createInstance(rrequest, this.cacheDataBean,
                ersqlbean.getInsertbean(), cbean, "", this.currentSecretColValuesBean);
        if (!ercdatabeanTmp.isEditable()) {
            if (colDisplayModeTmp == 0) {//???
                resultBuf.append(" style=\"display:none;\"></td>");
                continue;
            }
            col_displayvalue = getNonEditableColDisplayValueInAddMode(cbean, rowInterceptorObjTmp, rowidx);
        } else {
            resultBuf.append(" id=\"").append(EditableReportAssistant.getInstance().getInputBoxId(cbean))
                    .append("__td" + rowidx + "\" ");
            resultBuf.append(" value_name=\"").append(ercdatabeanTmp.getValuename()).append("\"");
            resultBuf.append(" value=\"").append(Tools.htmlEncode(ercdatabeanTmp.getValue())).append("\"");
            if (isReadonlyByRowInterceptor) {
                col_displayvalue = getNonEditableColDisplayValueInAddMode(cbean, rowInterceptorObjTmp, rowidx);
            } else if (colDisplayModeTmp > 0) {
                col_displayvalue = showInputBoxForCol(tdPropsBuf,
                        (EditableReportColBean) cbean.getExtendConfigDataForReportType(KEY), rowidx, null,
                        cbean, ercdatabeanTmp);
                isEditableCol = true;
            } else {
                resultBuf.append(" style=\"display:none;\"></td>");
                continue;
            }
        }
        colDisplayData = ColDisplayData.getColDataFromInterceptor(this, cbean, null, rowidx,
                cbean.getValuestyleproperty(rrequest, false), col_displayvalue);
        isReadonlyByColInterceptor = colDisplayData.getColdataByInterceptor() != null
                && colDisplayData.getColdataByInterceptor().isReadonly();
        if (isReadonlyByColInterceptor && isEditableCol) {
            col_displayvalue = getNonEditableColDisplayValueInAddMode(cbean, rowInterceptorObjTmp, rowidx);
            tdPropsBuf.delete(0, tdPropsBuf.length());
        } else {
            col_displayvalue = colDisplayData.getValue();
        }
        resultBuf.append(" ").append(tdPropsBuf.toString());
        resultBuf.append(" ").append(colDisplayData.getStyleproperty()).append(">");
        resultBuf.append(this.getColDisplayValueWrapStart(cbean, false,
                isReadonlyByColInterceptor || !isEditableCol, false));
        resultBuf.append(col_displayvalue);
        resultBuf.append(this.getColDisplayValueWrapEnd(cbean, false,
                isReadonlyByColInterceptor || !isEditableCol, false));
        resultBuf.append("</td>");
    }
    resultBuf.append("</tr>");
    this.global_rowindex++;
    this.global_sequence++;
    return resultBuf.toString();
}