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:carnero.cgeo.cgBase.java

public String requestJSON(String scheme, String host, String path, String method, String params) {
    int httpCode = -1;
    String httpLocation = null;/*w  w  w.j  a va  2s .  co  m*/

    if (method == null) {
        method = "GET";
    } else {
        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);
                }

                final String encoding = connection.getContentEncoding();
                InputStream ins;

                if (encoding != null && encoding.equalsIgnoreCase("gzip")) {
                    ins = new GZIPInputStream(connection.getInputStream());
                } else if (encoding != null && encoding.equalsIgnoreCase("deflate")) {
                    ins = new InflaterInputStream(connection.getInputStream(), new Inflater(true));
                } else {
                    ins = connection.getInputStream();
                }
                final InputStreamReader inr = new InputStreamReader(ins);
                final BufferedReader br = new BufferedReader(inr);

                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 (buffer != null && buffer.length() > 0) {
            break;
        }

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

    String page = null;
    if (httpCode == 302 && httpLocation != null) {
        final Uri newLocation = Uri.parse(httpLocation);
        if (newLocation.isRelative() == true) {
            page = requestJSONgc(host, path, params);
        } else {
            page = requestJSONgc(newLocation.getHost(), newLocation.getPath(), params);
        }
    } else {
        page = replaceWhitespace(buffer);
    }

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

From source file:carnero.cgeo.cgBase.java

public String requestJSONgc(String host, String path, String params) {
    int httpCode = -1;
    String httpLocation = null;/*from w w  w . jav a  2  s  .co  m*/

    // prepare cookies
    String cookiesDone = null;
    if (cookies == null || cookies.isEmpty() == true) {
        if (cookies == null) {
            cookies = new HashMap<String, String>();
        }

        final Map<String, ?> prefsAll = prefs.getAll();
        final Set<String> prefsKeys = prefsAll.keySet();

        for (String key : prefsKeys) {
            if (key.matches("cookie_.+") == true) {
                final String cookieKey = key.substring(7);
                final String cookieValue = (String) prefsAll.get(key);

                cookies.put(cookieKey, cookieValue);
            }
        }
    }

    if (cookies != null) {
        final Object[] keys = cookies.keySet().toArray();
        final ArrayList<String> cookiesEncoded = new ArrayList<String>();

        for (int i = 0; i < keys.length; i++) {
            String value = cookies.get(keys[i].toString());
            cookiesEncoded.add(keys[i] + "=" + value);
        }

        if (cookiesEncoded.size() > 0) {
            cookiesDone = implode("; ", cookiesEncoded.toArray());
        }
    }

    if (cookiesDone == null) {
        Map<String, ?> prefsValues = prefs.getAll();

        if (prefsValues != null && prefsValues.size() > 0) {
            final Object[] keys = prefsValues.keySet().toArray();
            final ArrayList<String> cookiesEncoded = new ArrayList<String>();
            final int length = keys.length;

            for (int i = 0; i < length; i++) {
                if (keys[i].toString().length() > 7
                        && keys[i].toString().substring(0, 7).equals("cookie_") == true) {
                    cookiesEncoded
                            .add(keys[i].toString().substring(7) + "=" + prefsValues.get(keys[i].toString()));
                }
            }

            if (cookiesEncoded.size() > 0) {
                cookiesDone = implode("; ", cookiesEncoded.toArray());
            }
        }
    }

    if (cookiesDone == null) {
        cookiesDone = "";
    }

    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 {
            // POST
            final URL u = new URL("http://" + host + path);
            uc = u.openConnection();

            uc.setRequestProperty("Host", host);
            uc.setRequestProperty("Cookie", cookiesDone);
            uc.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
            uc.setRequestProperty("X-Requested-With", "XMLHttpRequest");
            uc.setRequestProperty("Accept", "application/json, text/javascript, */*; q=0.01");
            uc.setRequestProperty("Referer", host + "/" + path);

            if (settings.asBrowser == 1) {
                uc.setRequestProperty("Accept-Charset", "utf-8, iso-8859-1, utf-16, *;q=0.7");
                uc.setRequestProperty("Accept-Language", "en-US");
                uc.setRequestProperty("User-Agent", idBrowser);
                uc.setRequestProperty("Connection", "keep-alive");
                uc.setRequestProperty("Keep-Alive", "300");
            }

            connection = (HttpURLConnection) uc;
            connection.setReadTimeout(timeout);
            connection.setRequestMethod("POST");
            HttpURLConnection.setFollowRedirects(false); // TODO: Fix these (FilCab)
            connection.setDoInput(true);
            connection.setDoOutput(true);

            final OutputStream out = connection.getOutputStream();
            final OutputStreamWriter wr = new OutputStreamWriter(out);
            wr.write(params);
            wr.flush();
            wr.close();

            String headerName = null;
            final SharedPreferences.Editor prefsEditor = prefs.edit();
            for (int j = 1; (headerName = uc.getHeaderFieldKey(j)) != null; j++) {
                if (headerName != null && headerName.equalsIgnoreCase("Set-Cookie")) {
                    int index;
                    String cookie = uc.getHeaderField(j);

                    index = cookie.indexOf(";");
                    if (index > -1) {
                        cookie = cookie.substring(0, cookie.indexOf(";"));
                    }

                    index = cookie.indexOf("=");
                    if (index > -1 && cookie.length() > (index + 1)) {
                        String name = cookie.substring(0, cookie.indexOf("="));
                        String value = cookie.substring(cookie.indexOf("=") + 1, cookie.length());

                        cookies.put(name, value);
                        prefsEditor.putString("cookie_" + name, value);
                    }
                }
            }
            prefsEditor.commit();

            final String encoding = connection.getContentEncoding();
            InputStream ins;

            if (encoding != null && encoding.equalsIgnoreCase("gzip")) {
                ins = new GZIPInputStream(connection.getInputStream());
            } else if (encoding != null && encoding.equalsIgnoreCase("deflate")) {
                ins = new InflaterInputStream(connection.getInputStream(), new Inflater(true));
            } else {
                ins = connection.getInputStream();
            }
            final InputStreamReader inr = new InputStreamReader(ins);
            final BufferedReader br = new BufferedReader(inr);

            readIntoBuffer(br, buffer);

            httpCode = connection.getResponseCode();
            httpLocation = uc.getHeaderField("Location");

            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) {
            Log.e(cgSettings.tag, "cgeoBase.requestJSONgc.IOException: " + e.toString());
        } catch (Exception e) {
            Log.e(cgSettings.tag, "cgeoBase.requestJSONgc: " + e.toString());
        }

        if (buffer != null && buffer.length() > 0) {
            break;
        }
    }

    String page = null;
    if (httpCode == 302 && httpLocation != null) {
        final Uri newLocation = Uri.parse(httpLocation);
        if (newLocation.isRelative() == true) {
            page = requestJSONgc(host, path, params);
        } else {
            page = requestJSONgc(newLocation.getHost(), newLocation.getPath(), params);
        }
    } else {
        page = replaceWhitespace(buffer);
    }

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

From source file:LayoutExample.java

/**
 * Generates code for the example layout.
 *//* ww w.j  a v  a2s.c o m*/
StringBuffer generateLayoutCode() {
    StringBuffer code = new StringBuffer();
    code.append("\t\tGridLayout gridLayout = new GridLayout ();\n");
    if (gridLayout.numColumns != 1) {
        code.append("\t\tgridLayout.numColumns = " + gridLayout.numColumns + ";\n");
    }
    if (gridLayout.makeColumnsEqualWidth) {
        code.append("\t\tgridLayout.makeColumnsEqualWidth = true;\n");
    }
    if (gridLayout.marginHeight != 5) {
        code.append("\t\tgridLayout.marginHeight = " + gridLayout.marginHeight + ";\n");
    }
    if (gridLayout.marginWidth != 5) {
        code.append("\t\tgridLayout.marginWidth = " + gridLayout.marginWidth + ";\n");
    }
    if (gridLayout.horizontalSpacing != 5) {
        code.append("\t\tgridLayout.horizontalSpacing = " + gridLayout.horizontalSpacing + ";\n");
    }
    if (gridLayout.verticalSpacing != 5) {
        code.append("\t\tgridLayout.verticalSpacing = " + gridLayout.verticalSpacing + ";\n");
    }
    code.append("\t\tshell.setLayout (gridLayout);\n");

    boolean first = true;
    for (int i = 0; i < children.length; i++) {
        Control control = children[i];
        code.append(getChildCode(control, i));
        GridData data = (GridData) control.getLayoutData();
        if (data != null) {
            code.append("\t\t");
            if (first) {
                code.append("GridData ");
                first = false;
            }
            code.append("data = new GridData ();\n");
            if (data.widthHint != SWT.DEFAULT) {
                code.append("\t\tdata.widthHint = " + data.widthHint + ";\n");
            }
            if (data.heightHint != SWT.DEFAULT) {
                code.append("\t\tdata.heightHint = " + data.heightHint + ";\n");
            }
            if (data.horizontalAlignment != GridData.BEGINNING) {
                String alignment;
                int hAlignment = data.horizontalAlignment;
                if (hAlignment == GridData.CENTER)
                    alignment = "GridData.CENTER";
                else if (hAlignment == GridData.END)
                    alignment = "GridData.END";
                else
                    alignment = "GridData.FILL";
                code.append("\t\tdata.horizontalAlignment = " + alignment + ";\n");
            }
            if (data.verticalAlignment != GridData.CENTER) {
                String alignment;
                int vAlignment = data.verticalAlignment;
                if (vAlignment == GridData.BEGINNING)
                    alignment = "GridData.BEGINNING";
                else if (vAlignment == GridData.END)
                    alignment = "GridData.END";
                else
                    alignment = "GridData.FILL";
                code.append("\t\tdata.verticalAlignment = " + alignment + ";\n");
            }
            if (data.horizontalIndent != 0) {
                code.append("\t\tdata.horizontalIndent = " + data.horizontalIndent + ";\n");
            }
            if (data.horizontalSpan != 1) {
                code.append("\t\tdata.horizontalSpan = " + data.horizontalSpan + ";\n");
            }
            if (data.verticalSpan != 1) {
                code.append("\t\tdata.verticalSpan = " + data.verticalSpan + ";\n");
            }
            if (data.grabExcessHorizontalSpace) {
                code.append("\t\tdata.grabExcessHorizontalSpace = true;\n");
            }
            if (data.grabExcessVerticalSpace) {
                code.append("\t\tdata.grabExcessVerticalSpace = true;\n");
            }
            if (code.substring(code.length() - 33).equals("GridData data = new GridData ();\n")) {
                code.delete(code.length() - 33, code.length());
                first = true;
            } else if (code.substring(code.length() - 24).equals("data = new GridData ();\n")) {
                code.delete(code.length() - 24, code.length());
            } else {
                code.append("\t\t" + names[i] + ".setLayoutData (data);\n");
            }
        }
    }
    return code;
}

From source file:dao.CollabrumDaoDb.java

/**
 * add the stream blob//from w  w  w.j  a va2  s. c om
 * This method is called to add a stream blob to collabrum
 * @param bsize - the blob size
 * @param blobtype - the blob type
 * @param mtype - the mime type
 * @param btitle - the blob title
 * @param blob - the blob itself
 * @param zoom - zoom
 * @param userId - the user id
 * @param collabrumId - collabrum Id
 * @param userLogin - the user Login
 * @param usertags - the user tags
 * @param caption - caption
 * @throws BaseDaoException If we have a problem interpreting the data or the data is missing or incorrect
*/
public void addStreamBlob(long bsize, int blobtype, String mtype, String btitle, byte[] blob, int zoom,
        String userId, String collabrumId, String userLogin, String usertags, String caption)
        throws BaseDaoException {

    if ((bsize <= 0) || RegexStrUtil.isNull(mtype) || RegexStrUtil.isNull(btitle) || (blob == null)) {
        throw new BaseDaoException("params are null");
    }

    /**
    * check authority to add - diaryAdmin & isOrganizer are checked
    */
    if (!isOrganizer(collabrumId, userLogin, userId)) {
        StringBuffer sb = new StringBuffer("user does not have permission to add 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 null, addStreamBlob() in collabrumDaoDb ");
        sb.append(sourceName);
        sb.append("collabrumId = ");
        sb.append(collabrumId);
        throw new BaseDaoException(sb.toString());
    }
    if (RegexStrUtil.isNull(caption)) {
        caption = btitle;
    }

    Connection conn = null;
    String entryId = null;
    try {
        conn = ds.getConnection();
        addStreamblobQuery.run(conn, blob, blobtype, mtype, btitle, bsize, zoom, collabrumId, userId, caption);
        List entryIdResult = getEntryIdQuery.run(conn, collabrumId);
        if (entryIdResult != null && entryIdResult.size() > 0) {
            if ((Photo) entryIdResult.get(0) != null) {
                entryId = ((Photo) entryIdResult.get(0)).getValue(DbConstants.ENTRYID);
            }
        }
    } catch (Exception e) {
        try {
            if (conn != null) {
                conn.close();
            }
        } catch (Exception e2) {
            throw new BaseDaoException("addBlob error ", e2);
        }
    }

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

    if (entryId != null) {
        addTags(entryId, collabrumId, usertags);
    }

    /**
     * remove the collabrum, get the latest photos
     */
    Fqn fqn = cacheUtil.fqn(DbConstants.COLLABRUM);
    if (treeCache.exists(fqn, collabrumId)) {
        treeCache.remove(fqn, collabrumId);
    }
    fqn = cacheUtil.fqn(DbConstants.COLLABRUM_EDIT);
    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:org.sakaiproject.tool.messageforums.PrivateMessagesTool.java

private PrivateMessage getPvtMsgForward(PrivateMessage currentMessage, boolean isDraft) {

    if (!isDraft) {
        if (getSelectedComposeToList().size() < 1 && getSelectedComposeBccList().size() < 1) {
            setErrorMessage(getResourceBundleString(SELECT_MSG_RECIPIENT));
            return null;
        }//from ww  w  .  ja  v  a2s . com
    }
    if (!hasValue(getForwardSubject())) {
        if (isDraft) {
            setErrorMessage(getResourceBundleString(MISSING_SUBJECT_DRAFT));
        } else {
            setErrorMessage(getResourceBundleString(MISSING_SUBJECT));
        }
        return null;
    }

    PrivateMessage rrepMsg = messageManager.createPrivateMessage();

    StringBuilder alertMsg = new StringBuilder();
    rrepMsg.setTitle(getForwardSubject());
    rrepMsg.setDraft(Boolean.FALSE);
    rrepMsg.setDeleted(Boolean.FALSE);

    rrepMsg.setAuthor(getAuthorString());
    rrepMsg.setApproved(Boolean.FALSE);
    rrepMsg.setBody(FormattedText.processFormattedText(getForwardBody(), alertMsg));

    rrepMsg.setLabel(getSelectedLabel());

    rrepMsg.setInReplyTo(currentMessage);

    //Add the recipientList as String for display in Sent folder
    // Since some users may be hidden, if some of these are recipients
    // filter them out (already checked if no recipients)
    // if only 1 recipient no need to check visibility
    StringBuffer sendToString = new StringBuffer();
    StringBuffer sendToHiddenString = new StringBuffer();

    if (selectedComposeToList.size() == 1) {
        MembershipItem membershipItem = (MembershipItem) courseMemberMap.get(selectedComposeToList.get(0));
        if (membershipItem != null) {
            sendToString.append(membershipItem.getName()).append("; ");
        }
    } else {
        for (int i = 0; i < selectedComposeToList.size(); i++) {
            MembershipItem membershipItem = (MembershipItem) courseMemberMap.get(selectedComposeToList.get(i));
            if (membershipItem != null) {
                if (membershipItem.isViewable()) {
                    sendToString.append(membershipItem.getName()).append("; ");
                } else {
                    sendToHiddenString.append(membershipItem.getName()).append("; ");
                }
            }
        }
    }

    //add bcc recipients place holder:
    if (selectedComposeBccList.size() > 0
            && !sendToString.toString().contains(getResourceBundleString(RECIPIENTS_UNDISCLOSED))) {
        sendToString.append(getResourceBundleString(RECIPIENTS_UNDISCLOSED)).append("; ");
    }

    StringBuffer sendToBccString = new StringBuffer();
    StringBuffer sendToBccHiddenString = new StringBuffer();
    for (int i = 0; i < selectedComposeBccList.size(); i++) {
        MembershipItem membershipItem = (MembershipItem) courseMemberMap.get(selectedComposeBccList.get(i));
        if (membershipItem != null) {
            if (membershipItem.isViewable()) {
                sendToBccString.append(membershipItem.getName()).append("; ");
            } else {
                sendToBccHiddenString.append(membershipItem.getName()).append("; ");
            }
        }
    }

    //clean sendToString
    if (!"".equals(sendToString.toString())) {
        sendToString.delete(sendToString.length() - 2, sendToString.length()); //remove last comma and space
    }

    if ("".equals(sendToHiddenString.toString())) {
        rrepMsg.setRecipientsAsText(sendToString.toString());
    } else {
        sendToHiddenString.delete(sendToHiddenString.length() - 2, sendToHiddenString.length()); //remove last comma and space    
        rrepMsg.setRecipientsAsText(sendToString.toString() + " (" + sendToHiddenString.toString() + ")");
    }

    //clean sendToBccString
    if (!"".equals(sendToBccString.toString())) {
        sendToBccString.delete(sendToBccString.length() - 2, sendToBccString.length()); //remove last comma and space
    }

    if ("".equals(sendToBccHiddenString.toString())) {
        rrepMsg.setRecipientsAsTextBcc(sendToBccString.toString());
    } else {
        sendToBccHiddenString.delete(sendToBccHiddenString.length() - 2, sendToBccHiddenString.length()); //remove last comma and space    
        rrepMsg.setRecipientsAsTextBcc(
                sendToBccString.toString() + " (" + sendToBccHiddenString.toString() + ")");
    }

    //Add attachments
    for (int i = 0; i < allAttachments.size(); i++) {
        prtMsgManager.addAttachToPvtMsg(rrepMsg, ((DecoratedAttachment) allAttachments.get(i)).getAttachment());
    }

    return rrepMsg;
}

From source file:org.sakaiproject.tool.messageforums.PrivateMessagesTool.java

public PrivateMessage constructMessage(boolean clearAttachments, PrivateMessage aMsg) {
    if (aMsg == null) {
        aMsg = messageManager.createPrivateMessage();
    } else {/*from  w  w  w . ja  v a  2s.  c  o m*/
        //set the date for now:
        aMsg.setCreated(new Date());
    }

    if (aMsg != null) {
        StringBuilder alertMsg = new StringBuilder();
        aMsg.setTitle(getComposeSubject());
        aMsg.setBody(FormattedText.processFormattedText(getComposeBody(), alertMsg));

        aMsg.setAuthor(getAuthorString());
        aMsg.setDraft(Boolean.FALSE);
        aMsg.setApproved(Boolean.FALSE);
        aMsg.setLabel(getSelectedLabel());

        // this property added so can delete forum messages
        // since that and PM share same message object and
        // delete is not null....
        aMsg.setDeleted(Boolean.FALSE);

        // Add the recipientList as String for display in Sent folder
        // Any hidden users will be tacked on at the end
        StringBuffer sendToString = new StringBuffer("");
        StringBuffer sendToHiddenString = new StringBuffer("");

        if (selectedComposeToList.size() == 1) {
            MembershipItem membershipItem = (MembershipItem) courseMemberMap.get(selectedComposeToList.get(0));
            if (membershipItem != null) {
                sendToString.append(membershipItem.getName()).append("; ");
            }
        } else {
            for (int i = 0; i < selectedComposeToList.size(); i++) {
                MembershipItem membershipItem = (MembershipItem) courseMemberMap
                        .get(selectedComposeToList.get(i));
                if (membershipItem != null) {
                    if (membershipItem.isViewable()) {
                        sendToString.append(membershipItem.getName()).append("; ");
                    } else {
                        sendToHiddenString.append(membershipItem.getName()).append("; ");
                    }
                }
            }
        }

        //add bcc recipients place holder:
        if (selectedComposeBccList.size() > 0
                && !sendToString.toString().contains(getResourceBundleString(RECIPIENTS_UNDISCLOSED))) {
            sendToString.append(getResourceBundleString(RECIPIENTS_UNDISCLOSED)).append("; ");
        }

        //create bcc string to use to display the user's who got BCC'ed
        StringBuffer sendToBccString = new StringBuffer("");
        StringBuffer sendToBccHiddenString = new StringBuffer("");
        for (int i = 0; i < selectedComposeBccList.size(); i++) {
            MembershipItem membershipItem = (MembershipItem) courseMemberMap.get(selectedComposeBccList.get(i));
            if (membershipItem != null) {
                if (membershipItem.isViewable()) {
                    sendToBccString.append(membershipItem.getName()).append("; ");
                } else {
                    sendToBccHiddenString.append(membershipItem.getName()).append("; ");
                }
            }
        }

        if (!"".equals(sendToString.toString())) {
            sendToString.delete(sendToString.length() - 2, sendToString.length()); //remove last comma and space
        }

        if ("".equals(sendToHiddenString.toString())) {
            aMsg.setRecipientsAsText(sendToString.toString());
        } else {
            sendToHiddenString.delete(sendToHiddenString.length() - 2, sendToHiddenString.length()); //remove last comma and space
            aMsg.setRecipientsAsText(sendToString.toString() + " " + PrivateMessage.HIDDEN_RECIPIENTS_START
                    + sendToHiddenString.toString() + PrivateMessage.HIDDEN_RECIPIENTS_END);
        }
        //clean up sendToBccString
        if (!"".equals(sendToBccString.toString())) {
            sendToBccString.delete(sendToBccString.length() - 2, sendToBccString.length()); //remove last comma and space
        }

        if ("".equals(sendToBccHiddenString.toString())) {
            aMsg.setRecipientsAsTextBcc(sendToBccString.toString());
        } else {
            sendToBccHiddenString.delete(sendToBccHiddenString.length() - 2, sendToBccHiddenString.length()); //remove last comma and space
            aMsg.setRecipientsAsTextBcc(
                    sendToBccString.toString() + " " + PrivateMessage.HIDDEN_RECIPIENTS_START
                            + sendToBccHiddenString.toString() + PrivateMessage.HIDDEN_RECIPIENTS_END);
        }

    }
    //Add attachments
    for (int i = 0; i < attachments.size(); i++) {
        prtMsgManager.addAttachToPvtMsg(aMsg, ((DecoratedAttachment) attachments.get(i)).getAttachment());
    }
    if (clearAttachments) {
        //clear
        attachments.clear();
        oldAttachments.clear();
    }

    return aMsg;
}

From source file:org.sakaiproject.tool.messageforums.PrivateMessagesTool.java

private PrivateMessage getPvtMsgReplyMessage(PrivateMessage currentMessage, boolean isDraft) {
    if (setDetailMsgCount != 1) {
        setErrorMessage(getResourceBundleString(MULTIPLE_WINDOWS,
                new Object[] { ServerConfigurationService.getString("ui.service", "Sakai") }));
        return null;
    } else {//w w  w . j  a v  a 2s  .  c o  m

        //PrivateMessage currentMessage = getDetailMsg().getMsg() ;
        //by default add user who sent original message    
        for (Iterator i = totalComposeToList.iterator(); i.hasNext();) {
            MembershipItem membershipItem = (MembershipItem) i.next();

            if (MembershipItem.TYPE_USER.equals(membershipItem.getType())) {
                if (membershipItem.getUser() != null) {
                    if (membershipItem.getUser().getId().equals(currentMessage.getCreatedBy())) {
                        selectedComposeToList.add(membershipItem.getId());
                    }
                }
            }
        }

        if (!hasValue(getReplyToSubject())) {
            if (isDraft) {
                setErrorMessage(getResourceBundleString(MISSING_SUBJECT_DRAFT));
            } else {
                setErrorMessage(getResourceBundleString(MISSING_SUBJECT));
            }
            return null;
        }
        if (!isDraft) {
            if (selectedComposeToList.size() < 1 && selectedComposeBccList.size() < 1) {
                setErrorMessage(getResourceBundleString(SELECT_RECIPIENT_LIST_FOR_REPLY));
                return null;
            }
        }

        PrivateMessage rrepMsg = messageManager.createPrivateMessage();

        StringBuilder alertMsg = new StringBuilder();
        rrepMsg.setTitle(getReplyToSubject());
        rrepMsg.setBody(FormattedText.processFormattedText(getReplyToBody(), alertMsg));
        rrepMsg.setDraft(Boolean.FALSE);
        rrepMsg.setDeleted(Boolean.FALSE);

        rrepMsg.setAuthor(getAuthorString());
        rrepMsg.setApproved(Boolean.FALSE);

        rrepMsg.setLabel(getSelectedLabel());

        rrepMsg.setInReplyTo(currentMessage);

        //Add the recipientList as String for display in Sent folder
        // Since some users may be hidden, if some of these are recipients
        // filter them out (already checked if no recipients)
        // if only 1 recipient no need to check visibility
        StringBuffer sendToString = new StringBuffer("");
        StringBuffer sendToHiddenString = new StringBuffer("");

        if (selectedComposeToList.size() == 1) {
            MembershipItem membershipItem = (MembershipItem) courseMemberMap.get(selectedComposeToList.get(0));
            if (membershipItem != null) {
                sendToString.append(membershipItem.getName()).append("; ");
            }
        } else {
            for (int i = 0; i < selectedComposeToList.size(); i++) {
                MembershipItem membershipItem = (MembershipItem) courseMemberMap
                        .get(selectedComposeToList.get(i));
                if (membershipItem != null) {
                    if (membershipItem.isViewable()) {
                        sendToString.append(membershipItem.getName()).append("; ");
                    } else {
                        sendToHiddenString.append(membershipItem.getName()).append("; ");
                    }
                }
            }
        }

        //add bcc recipients place holder:
        if (selectedComposeBccList.size() > 0
                && !sendToString.toString().contains(getResourceBundleString(RECIPIENTS_UNDISCLOSED))) {
            sendToString.append(getResourceBundleString(RECIPIENTS_UNDISCLOSED)).append("; ");
        }

        //create sendToBccString
        StringBuffer sendToBccString = new StringBuffer("");
        StringBuffer sendToBccHiddenString = new StringBuffer("");
        for (int i = 0; i < selectedComposeBccList.size(); i++) {
            MembershipItem membershipItem = (MembershipItem) courseMemberMap.get(selectedComposeBccList.get(i));
            if (membershipItem != null) {
                if (membershipItem.isViewable()) {
                    sendToBccString.append(membershipItem.getName()).append("; ");
                } else {
                    sendToBccHiddenString.append(membershipItem.getName()).append("; ");
                }
            }
        }

        //clean sendToString
        if (!"".equals(sendToString.toString())) {
            sendToString.delete(sendToString.length() - 2, sendToString.length()); //remove last comma and space
        }

        if ("".equals(sendToHiddenString.toString())) {
            rrepMsg.setRecipientsAsText(sendToString.toString());
        } else {
            sendToHiddenString.delete(sendToHiddenString.length() - 2, sendToHiddenString.length()); //remove last comma and space    
            rrepMsg.setRecipientsAsText(sendToString.toString() + " " + PrivateMessage.HIDDEN_RECIPIENTS_START
                    + sendToHiddenString.toString() + PrivateMessage.HIDDEN_RECIPIENTS_END);
        }

        //clean sendToBccString
        //clean sendToString
        if (!"".equals(sendToBccString.toString())) {
            sendToBccString.delete(sendToBccString.length() - 2, sendToBccString.length()); //remove last comma and space
        }

        if ("".equals(sendToBccHiddenString.toString())) {
            rrepMsg.setRecipientsAsTextBcc(sendToBccString.toString());
        } else {
            sendToBccHiddenString.delete(sendToBccHiddenString.length() - 2, sendToBccHiddenString.length()); //remove last comma and space    
            rrepMsg.setRecipientsAsTextBcc(
                    sendToBccString.toString() + " " + PrivateMessage.HIDDEN_RECIPIENTS_START
                            + sendToBccHiddenString.toString() + PrivateMessage.HIDDEN_RECIPIENTS_END);
        }

        //Add attachments
        for (int i = 0; i < allAttachments.size(); i++) {
            prtMsgManager.addAttachToPvtMsg(rrepMsg,
                    ((DecoratedAttachment) allAttachments.get(i)).getAttachment());
        }

        return rrepMsg;

    }
}

From source file:org.sakaiproject.tool.messageforums.PrivateMessagesTool.java

private PrivateMessage processPvtMsgReplyAllSendHelper(boolean preview, Boolean isDraft) {

    PrivateMessage currentMessage = getDetailMsg().getMsg();

    String msgauther = currentMessage.getAuthor();//string   "Test"      

    //Select Forward Recipients

    if (!hasValue(getForwardSubject())) {
        if (isDraft) {
            setErrorMessage(getResourceBundleString(MISSING_SUBJECT_DRAFT));
        } else {/*from  w  w w.  j  ava 2 s .c  o m*/
            setErrorMessage(getResourceBundleString(MISSING_SUBJECT));
        }
        return null;
    }

    PrivateMessage rrepMsg = messageManager.createPrivateMessage();

    StringBuilder alertMsg = new StringBuilder();
    rrepMsg.setTitle(getForwardSubject());
    rrepMsg.setDraft(isDraft);
    rrepMsg.setDeleted(Boolean.FALSE);

    rrepMsg.setAuthor(getAuthorString());
    rrepMsg.setApproved(Boolean.FALSE);
    //add some emty space to the msg composite, by huxt
    String replyAllbody = "  ";
    replyAllbody = getForwardBody();

    rrepMsg.setBody(FormattedText.processFormattedText(replyAllbody, alertMsg));
    rrepMsg.setLabel(getSelectedLabel());
    rrepMsg.setInReplyTo(currentMessage);

    //Add attachments
    for (int i = 0; i < allAttachments.size(); i++) {
        prtMsgManager.addAttachToPvtMsg(rrepMsg, ((DecoratedAttachment) allAttachments.get(i)).getAttachment());
    }

    User autheruser = null;
    try {
        autheruser = UserDirectoryService.getUser(currentMessage.getCreatedBy());
    } catch (UserNotDefinedException e) {
        e.printStackTrace();
    }

    List tmpRecipList = currentMessage.getRecipients();

    Map<User, Boolean> returnSet = new HashMap<User, Boolean>();
    StringBuffer sendToStringreplyall = new StringBuffer();

    Iterator iter = tmpRecipList.iterator();
    while (iter.hasNext()) {
        PrivateMessageRecipient tmpPMR = (PrivateMessageRecipient) iter.next();
        User replyrecipientaddtmp = null;
        try {
            replyrecipientaddtmp = UserDirectoryService.getUser(tmpPMR.getUserId());
        } catch (UserNotDefinedException e) {
            // TODO Auto-generated catch block
            LOG.warn("Unable to find user : " + tmpPMR.getUserId(), e);
        }

        if (replyrecipientaddtmp == null) {
            LOG.warn("continuing passed user : " + tmpPMR.getUserId());
            //throw new IllegalStateException("User replyrecipientaddtmp == null!");
        } else {
            if (!(replyrecipientaddtmp.getDisplayName()).equals(getUserName()) && !tmpPMR.getBcc())//&&(!(replyrecipientaddtmp.getDisplayName()).equals(msgauther)))
            {
                returnSet.put(replyrecipientaddtmp, tmpPMR.getBcc());
            }
        }
    }

    if (currentMessage.getRecipientsAsText() != null && !"".equals(currentMessage.getRecipientsAsText())) {
        sendToStringreplyall.append(currentMessage.getRecipientsAsText()).append("; ");
    }
    if (returnSet.isEmpty()) {
        returnSet.put(autheruser, false);
        if (!sendToStringreplyall.toString().contains(msgauther)) {
            //only add it to the reply string if it doesn't exist
            sendToStringreplyall.append(msgauther).append("; ");
        }
    }
    if (returnSet.containsKey(autheruser) && !sendToStringreplyall.toString().contains(msgauther)) {
        sendToStringreplyall.append(msgauther).append("; ");
    }

    //Add the recipientList as String for display in Sent folder
    // Since some users may be hidden, if some of these are recipients
    // filter them out (already checked if no recipients)
    // if only 1 recipient no need to check visibility
    StringBuffer sendToString = new StringBuffer(sendToStringreplyall);
    StringBuffer sendToHiddenString = new StringBuffer();

    if (selectedComposeToList.size() == 1) {
        MembershipItem membershipItem = (MembershipItem) courseMemberMap.get(selectedComposeToList.get(0));
        if (membershipItem != null) {
            sendToString.append(membershipItem.getName()).append("; ");
        }
    } else {
        for (int i = 0; i < selectedComposeToList.size(); i++) {
            MembershipItem membershipItem = (MembershipItem) courseMemberMap.get(selectedComposeToList.get(i));
            if (membershipItem != null) {
                if (!sendToStringreplyall.toString().contains(membershipItem.getName())) {
                    if (membershipItem.isViewable()) {
                        sendToString.append(membershipItem.getName()).append("; ");
                    } else {
                        sendToHiddenString.append(membershipItem.getName()).append("; ");
                    }
                }
            }
        }
    }

    //add bcc recipients place holder:
    if (selectedComposeBccList.size() > 0
            && !sendToString.toString().contains(getResourceBundleString(RECIPIENTS_UNDISCLOSED))) {
        sendToString.append(getResourceBundleString(RECIPIENTS_UNDISCLOSED)).append("; ");
    }

    //create sendToBccString
    StringBuffer sendToBccString = new StringBuffer();
    StringBuffer sendToBccHiddenString = new StringBuffer();
    for (int i = 0; i < selectedComposeBccList.size(); i++) {
        MembershipItem membershipItem = (MembershipItem) courseMemberMap.get(selectedComposeBccList.get(i));
        if (membershipItem != null) {
            if (membershipItem.isViewable()) {
                sendToBccString.append(membershipItem.getName()).append("; ");
            } else {
                sendToBccHiddenString.append(membershipItem.getName()).append("; ");
            }
        }
    }

    //clean sendToString
    if (!"".equals(sendToString.toString()) && sendToString.length() >= 2) {
        sendToString.delete(sendToString.length() - 2, sendToString.length()); //remove last comma and space
    }

    if ("".equals(sendToHiddenString.toString())) {
        rrepMsg.setRecipientsAsText(sendToString.toString());
    } else {
        sendToHiddenString.delete(sendToHiddenString.length() - 2, sendToHiddenString.length()); //remove last comma and space    
        rrepMsg.setRecipientsAsText(sendToString.toString() + " (" + sendToHiddenString.toString() + ")");
    }

    //clean sendToBccString
    if (!"".equals(sendToBccString.toString()) && sendToBccString.length() >= 2) {
        sendToBccString.delete(sendToBccString.length() - 2, sendToBccString.length()); //remove last comma and space
    }

    if ("".equals(sendToBccHiddenString.toString())) {
        rrepMsg.setRecipientsAsTextBcc(sendToBccString.toString());
    } else {
        sendToBccHiddenString.delete(sendToBccHiddenString.length() - 2, sendToBccHiddenString.length()); //remove last comma and space    
        rrepMsg.setRecipientsAsTextBcc(
                sendToBccString.toString() + " (" + sendToBccHiddenString.toString() + ")");
    }

    //Add selected users to reply all list

    Map<User, Boolean> recipients = getRecipients();
    for (Iterator<Entry<User, Boolean>> i = recipients.entrySet().iterator(); i.hasNext();) {
        Entry<User, Boolean> entrySet = (Entry<User, Boolean>) i.next();
        if (!returnSet.containsKey(entrySet.getKey())) {
            returnSet.put(entrySet.getKey(), entrySet.getValue());
        }
    }
    if (!preview) {
        prtMsgManager.sendPrivateMessage(rrepMsg, returnSet, isSendEmail());

        if (!rrepMsg.getDraft()) {
            prtMsgManager.markMessageAsRepliedForUser(getReplyingMessage());
            //update Synoptic tool info
            incrementSynopticToolInfo(returnSet.keySet(), false);
            LearningResourceStoreService lrss = (LearningResourceStoreService) ComponentManager
                    .get("org.sakaiproject.event.api.LearningResourceStoreService");
            Event event = EventTrackingService.newEvent(DiscussionForumService.EVENT_MESSAGES_FORWARD,
                    getEventMessage(rrepMsg), false);
            EventTrackingService.post(event);
            if (null != lrss) {
                try {
                    lrss.registerStatement(getStatementForUserSentPvtMsg(lrss.getEventActor(event),
                            getDetailMsg().getMsg().getTitle(), SAKAI_VERB.responded), "msgcntr");
                } catch (Exception e) {
                    LOG.error(e.getMessage(), e);
                }
            }
        }
        //reset contents
        resetComposeContents();
    }
    return rrepMsg;
}

From source file:dao.DirectoryDaoDb.java

/**
 * Deletes directory/* w ww  . ja v  a 2 s. c  o m*/
 * If the directory contains subdirectories or children or collabrum or urls, then
 * this directory is not deleted.
 * User permissions are checked before the user is allowed to delete directory.
 * If the user is the userid or admin, delete directory.
 * If the user has permission to delete in the permission directory, delete directory.
 * Returns parentId of this directory for controller
 * @param directoryId - the directoryid 
 * @param userId - the user id
 * @param userLogin - user login
 * @return List -> has the parentid used by the controller to throw the viewDirectory
 * @throws BaseDaoException If we have a problem interpreting the data or the data is missing or incorrect
 */
public List deleteDirectory(String directoryId, String userId, String userLogin) throws BaseDaoException {

    if (RegexStrUtil.isNull(directoryId) || RegexStrUtil.isNull(userId) || RegexStrUtil.isNull(userLogin)) {
        throw new BaseDaoException("params are null");
    }

    //logger.info("deleteDirectory" + directoryId);

    if (!WebUtil.isHomeDirDeleteEnabled()) {
        if (WebUtil.isSanEnabled()) {
            if (isHomeDirectory(directoryId, userLogin, userId)) {
                throw new BaseDaoException("Cannot delete, home directory, directoryId " + directoryId
                        + " userLogin = " + userLogin);
            }
        }
    }

    /**
    * allow files, collabrums to be deleted
    */
    if (!WebUtil.isDirTreeDeleteEnabled()) {
        if (isChildASubDir(directoryId)) {
            throw new BaseDaoException(
                    "Cannot delete, subdirs exist, userId = " + userId + " directoryId = " + directoryId);
        }
    }

    /**
     *  check authority to delete: isDiaryAdmin, isAuthor
     *  We donot check for global scope as the author who has added this entry 
     *  is added as diradmin
     */
    if ((!diaryAdmin.isDiaryAdmin(userLogin)) && (!isAuthor(directoryId, userId))) {
        throw new BaseDaoException("User does not have permission to delete this directory, user = " + userId
                + " directoryId " + directoryId);
    }

    /**
     *  Get scalability datasource for directory - not partitioned
     */
    String sourceName = scalabilityManager.getWriteZeroScalability();
    ds = scalabilityManager.getSource(sourceName);
    if (ds == null) {
        throw new BaseDaoException("ds null, deleteDirectory() " + sourceName);
    }

    /**
     *  gets the parentid of the directoryid and the result is returned
     */
    List dResult = null;
    try {
        Object[] params = { (Object) directoryId };
        dResult = directoryParentQuery.execute(params);
    } catch (Exception e) {
        throw new BaseDaoException("directoryparentQuery() exception " + directoryParentQuery.getSql(), e);
    }

    Connection conn = null;
    HashSet dirSet = null;
    try {
        conn = ds.getConnection();
        dirSet = listAuthorQuery.run(conn, directoryId);
    } catch (Exception e) {
        try {
            if (conn != null) {
                conn.close();
            }
        } catch (Exception e1) {
            throw new BaseDaoException("conn.close() exception " + directoryId, e1);
        }
        throw new BaseDaoException("listAuthorQuery, exception " + directoryId, e);
    }

    if (WebUtil.isSanEnabled()) {
        Directory currentDir = viewDirectory(directoryId, userId, userLogin, DbConstants.READ_FROM_SLAVE,
                DbConstants.BLOB_READ_FROM_SLAVE, DbConstants.READ_FROM_SLAVE);

        if (currentDir != null) {
            try {
                getSanUtils();
                //logger.info("commenting deleteAllSanDir for the time being");
                sanUtils.deleteAllSanDir(currentDir.getValue(DbConstants.DIRPATH),
                        currentDir.getValue(DbConstants.DIRNAME), SanConstants.sanPath);
            } catch (SanException e) {
                throw new BaseDaoException("deleteSanDir() deleteDirectory() error, " + directoryId
                        + " error message " + e.getMessage(), e);
            }
        }
    }

    try {
        if (conn == null) {
            conn = ds.getConnection();
        }
        conn.setAutoCommit(false);

        /** delete all children, subdirs */
        if (isChildASubDir(directoryId)) {
            //logger.info("calling deleteNode()");
            deleteNode(directoryId, conn);
        }

        /** 
         * the userId is not required to be checked 
         * as long as the user either the diaryAdmin or is author 
         */
        deleteAllDirectory(directoryId, conn);
        //logger.info("deleteAllDirectory called " + directoryId);

        /*
              directoryDeleteQuery.run(conn, directoryId);
              scopeDeleteQuery.run(conn, directoryId);
              deleteChildQuery.run(conn, directoryId);
              deleteAdminQuery.run(conn, directoryId);
              deleteDirCopyQuery.run(conn, directoryId);
              deleteDirBlockAllQuery.run(conn, directoryId);
              deleteDirAllowUsersAllQuery.run(conn, directoryId);
        */
        //logger.info("completed deleteDirectory queries ");
        /**
         * delete collabrum, delete websites coming soon!
         */
    } catch (Exception e) {
        try {
            conn.rollback();
        } catch (Exception e1) {
            try {
                if (conn != null) {
                    conn.setAutoCommit(true);
                    conn.close();
                }
            } catch (Exception e2) {
                throw new BaseDaoException(
                        "connection close() exception for rollback, delete directory/dirscope/diradmin tables  "
                                + " params (2) " + " directoryId = " + directoryId + " userId = " + userId,
                        e2);
            }
            throw new BaseDaoException("rollback() exception for delete directory/dirscope/diradmin tables  "
                    + " params (2) " + " directoryId = " + directoryId + " userId = " + userId, e1);
        }
    }

    // connection commit
    try {
        conn.commit();
    } catch (Exception e3) {
        throw new BaseDaoException("commit() exception for delete, directory/dirscope/diradmin tables  "
                + " params (2) " + " directoryId = " + directoryId + " userId = " + userId, e3);
    }
    try {
        if (conn != null) {
            conn.setAutoCommit(true);
            conn.close();
        }
    } catch (Exception e4) {
        throw new BaseDaoException(
                "connection close() exception for commit, delete directory/dirscope/diradmin tables  "
                        + " params (2) " + " directoryId = " + directoryId + " userId = " + userId,
                e4);
    }

    /**
     * remove this directory from cache
     */
    Fqn fqn = cacheUtil.fqn(DbConstants.DIRECTORY);
    if (treeCache.exists(fqn, directoryId)) {
        treeCache.remove(fqn, directoryId);
    }

    // check for each parent and remove the parent from cache
    if ((dResult != null) && (dResult.size() > 0)) {
        String parentId = ((Directory) dResult.get(0)).getValue(DbConstants.PARENT_ID);
        if (treeCache.exists(fqn, parentId)) {
            treeCache.remove(fqn, parentId);
        }
    }

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

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

    fqn = cacheUtil.fqn(DbConstants.DIR_CAT);
    StringBuffer sb = new StringBuffer(directoryId);
    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(directoryId);
    sb.append("-");
    sb.append(DbConstants.FILE_CATEGORY);
    if (treeCache.exists(fqn, sb.toString())) {
        treeCache.remove(fqn, sb.toString());
    }

    /*
            fqn = cacheUtil.fqn(DbConstants.DIRECTORY_STREAM_BLOBS);
            if (treeCache.exists(fqn, directoryId)) {
          Object obj = treeCache.get(fqn, directoryId);
          if (obj != null) {
             List entries = (List)obj;
      Fqn streamFqn = cacheUtil.fqn(DbConstants.DIR_STREAM_BLOB);
             //StringBuffer sb = new StringBuffer();
             for (int i = 0; i < entries.size(); i++) {
     String entryId = ((Photo)entries.get(i)).getValue(DbConstants.ENTRYID);
            if (!RegexStrUtil.isNull(entryId)) {
               sb.delete(0, sb.length());        
               sb.append(directoryId);
               sb.append("-");
               sb.append(entryId);
               if (treeCache.exists(streamFqn, sb.toString())) {
      treeCache.remove(streamFqn, sb.toString());
               }
            }
             }
          }
               treeCache.remove(fqn, directoryId);
       }
    */
    if (dirSet != null) {
        Iterator it = dirSet.iterator();
        while (it.hasNext()) {
            Directory directory = (Directory) it.next();
            String adminUser = directory.getValue(DbConstants.LOGIN);
            if (!RegexStrUtil.isNull(adminUser)) {

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

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

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

                String adminId = directory.getValue(DbConstants.LOGIN_ID);
                fqn = cacheUtil.fqn(DbConstants.AUTHOR_BLOCKED_DIRS);
                if (treeCache.exists(fqn, adminId)) {
                    treeCache.remove(fqn, adminId);
                }

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

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

                sb.delete(0, sb.length());
                sb.append(directoryId);
                sb.append("-");
                sb.append(adminId);
                String key = sb.toString();
                fqn = cacheUtil.fqn(DbConstants.DIR_AUTHOR);
                if (treeCache.exists(fqn, key)) {
                    treeCache.remove(fqn, key);
                }
            }
        }
    }
    removeUsersFromDirAuthorsCache(directoryId);
    return dResult;
}

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

private void showCommonDataPart(List<ColBean> lstColBeans) {
    StringBuffer tdPropsBuf;
    ColDisplayData colDisplayData;//from   w ww .  j  a  va2s .  co  m
    String col_displayvalue;
    AbsReportDataPojo rowDataObjTmp;
    boolean isDisplayInPage = rrequest.getShowtype() == Consts.DISPLAY_ON_PAGE;
    int[] displayrowinfo = this.getDisplayRowInfo();
    RowDataBean rowInterceptorObjTmp = null;
    String trstylepropertyTmp = null;
    boolean isReadonlyByRowInterceptor;
    boolean isHorizontalDataset = rbean.getSbean().isHorizontalDataset();
    boolean isShouldDisplayHdsLabelCol = this.isShouldDisplayHdsLabelCol();
    boolean isLazyLoadata = rbean.isLazyLoadReportData(rrequest);
    int lazyloadataCount = rbean.getLazyLoadDataCount(rrequest);
    boolean hasFetchAllDataPrevBatch = false;//????
    int recordidx = -1, startRownum = 0;
    if (isLazyLoadata && !this.cacheDataBean.isLoadAllReportData()) {
        startRownum = (this.cacheDataBean.getFinalPageno() - 1) * this.cacheDataBean.getPagesize();
    }
    for (int i = displayrowinfo[0]; i < displayrowinfo[1]; i++) {
        if (isLazyLoadata && i % lazyloadataCount == 0) {
            if (hasFetchAllDataPrevBatch) {
                this.lstReportData.clear();
            } else {
                this.loadLazyReportData(startRownum + i, startRownum + i + lazyloadataCount);
                hasFetchAllDataPrevBatch = this.lstReportData.size() < lazyloadataCount;
            }
            recordidx = -1;
        }
        recordidx = isLazyLoadata ? (recordidx + 1) : i;
        if (recordidx >= this.lstReportData.size()) {
            String addrow = getDataRowInAddMode(lstColBeans, isLazyLoadata, startRownum, i);
            if (addrow == null)
                break;//??
            dataPartStringBuffer.append(addrow);
            checkAndPrintBufferData(i);
            continue;
        }
        rowDataObjTmp = this.lstReportData.get(recordidx);
        if (isHorizontalDataset && rowDataObjTmp.getHdsDataColBean() != null && this.cacheDataBean
                .getColDisplayModeAfterAuthorize(rowDataObjTmp.getHdsDataColBean(), isDisplayInPage) <= 0) {//?????<col/>??
            continue;
        }
        isReadonlyByRowInterceptor = false;
        trstylepropertyTmp = rowDataObjTmp.getRowValuestyleproperty();
        rowInterceptorObjTmp = null;
        if (this.rbean.getInterceptor() != null) {
            rowInterceptorObjTmp = new RowDataBean(this, trstylepropertyTmp, lstColBeans, rowDataObjTmp, i,
                    this.cacheDataBean.getTotalColCount());
            this.rbean.getInterceptor().beforeDisplayReportDataPerRow(this.rrequest, this.rbean,
                    rowInterceptorObjTmp);
            if (rowInterceptorObjTmp.getInsertDisplayRowHtml() != null)
                dataPartStringBuffer.append(rowInterceptorObjTmp.getInsertDisplayRowHtml());
            if (!rowInterceptorObjTmp.isShouldDisplayThisRow()) {
                this.global_rowindex++;
                continue;
            }
            trstylepropertyTmp = rowInterceptorObjTmp.getRowstyleproperty();
            isReadonlyByRowInterceptor = rowInterceptorObjTmp.isReadonly();
        }
        dataPartStringBuffer.append(showDataRowTrStart(rowInterceptorObjTmp, trstylepropertyTmp, i, false))
                .append(">");
        if (isShouldDisplayHdsLabelCol) {
            dataPartStringBuffer
                    .append("<td " + getTdPropertiesForCol(rowDataObjTmp.getHdsDataColBean(), null, i, false));
            dataPartStringBuffer.append(" class='" + getDataTdClassName() + "' ");
            dataPartStringBuffer
                    .append(rowDataObjTmp.getHdsDataColBean().getLabelstyleproperty(rrequest, false))
                    .append(">");
            dataPartStringBuffer.append(rowDataObjTmp.getHdsDataColBean().getLabel(rrequest));
            dataPartStringBuffer.append("</td>");
        }
        boolean isReadonlyByColInterceptor;
        for (ColBean cbean : lstColBeans) {
            if (Consts.COL_DISPLAYTYPE_HIDDEN.equals(cbean.getDisplaytype(isDisplayInPage))
                    || this.cacheDataBean.getColDisplayModeAfterAuthorize(cbean, isDisplayInPage) <= 0) {
                dataPartStringBuffer.append(showHiddenCol(cbean, rowDataObjTmp, i));
                continue;
            }
            //??
            tdPropsBuf = new StringBuffer();
            Object colDataObj = initDisplayCol(cbean, rowDataObjTmp);
            dataPartStringBuffer.append("<td ").append(getTdPropertiesForCol(cbean, colDataObj, i, false));
            col_displayvalue = getColDisplayValue(cbean, rowDataObjTmp, rowInterceptorObjTmp, tdPropsBuf,
                    colDataObj, i, isReadonlyByRowInterceptor);
            colDisplayData = ColDisplayData.getColDataFromInterceptor(this, cbean, rowDataObjTmp, i,
                    getColValuestyleproperty(cbean, rowDataObjTmp), col_displayvalue);
            isReadonlyByColInterceptor = colDisplayData.getColdataByInterceptor() != null
                    && colDisplayData.getColdataByInterceptor().isReadonly();
            if (!isReadonlyByRowInterceptor && isReadonlyByColInterceptor) {
                tdPropsBuf.delete(0, tdPropsBuf.length());
                col_displayvalue = getColDisplayValue(cbean, rowDataObjTmp, rowInterceptorObjTmp, tdPropsBuf,
                        colDataObj, i, true);
            } else {
                col_displayvalue = colDisplayData.getValue();
            }
            dataPartStringBuffer.append(" class='" + getDataTdClassName() + "' ");
            dataPartStringBuffer.append(tdPropsBuf.toString()).append(" ");
            dataPartStringBuffer.append(colDisplayData.getStyleproperty()).append(">");
            dataPartStringBuffer.append(getColDisplayValueWithWrap(cbean, col_displayvalue, colDataObj,
                    isReadonlyByRowInterceptor || isReadonlyByColInterceptor));
            dataPartStringBuffer.append("</td>");
        }
        dataPartStringBuffer.append("</tr>");
        this.global_rowindex++;
        this.global_sequence++;
        checkAndPrintBufferData(i);
    }
    //        {//???????????
    //            {
    //                this.cacheDataBean.setRecordcount(0);
}