0001: /*
0002: * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
0003: *
0004: * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
0005: *
0006: * The contents of this file are subject to the terms of either the GNU
0007: * General Public License Version 2 only ("GPL") or the Common
0008: * Development and Distribution License("CDDL") (collectively, the
0009: * "License"). You may not use this file except in compliance with the
0010: * License. You can obtain a copy of the License at
0011: * http://www.netbeans.org/cddl-gplv2.html
0012: * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
0013: * specific language governing permissions and limitations under the
0014: * License. When distributing the software, include this License Header
0015: * Notice in each file and include the License file at
0016: * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
0017: * particular file as subject to the "Classpath" exception as provided
0018: * by Sun in the GPL Version 2 section of the License file that
0019: * accompanied this code. If applicable, add the following below the
0020: * License Header, with the fields enclosed by brackets [] replaced by
0021: * your own identifying information:
0022: * "Portions Copyrighted [year] [name of copyright owner]"
0023: *
0024: * Contributor(s):
0025: *
0026: * The Original Software is NetBeans. The Initial Developer of the Original
0027: * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
0028: * Microsystems, Inc. All Rights Reserved.
0029: *
0030: * If you wish your version of this file to be governed by only the CDDL
0031: * or only the GPL Version 2, indicate your decision by adding
0032: * "[Contributor] elects to include this software in this distribution
0033: * under the [CDDL or GPL Version 2] license." If you do not indicate a
0034: * single choice of license, a recipient has the option to distribute
0035: * your version of this file under either the CDDL, the GPL Version 2 or
0036: * to extend the choice of license to its licensees as provided above.
0037: * However, if you add GPL Version 2 code and therefore, elected the GPL
0038: * Version 2 license, then the option applies only if the new code is
0039: * made subject to such option by the copyright holder.
0040: */
0041: package org.netbeans.modules.collab.channel.filesharing.filehandler;
0042:
0043: import com.sun.collablet.CollabException;
0044: import java.awt.event.*;
0045: import java.awt.event.KeyEvent;
0046: import java.awt.event.MouseEvent;
0047: import org.netbeans.modules.collab.channel.filesharing.FilesharingCollablet;
0048: import org.netbeans.modules.collab.channel.filesharing.msgbean.LockRegion;
0049:
0050: import org.openide.*;
0051: import org.openide.cookies.*;
0052: import org.openide.filesystems.*;
0053: import org.openide.loaders.*;
0054: import org.openide.text.*;
0055: import org.openide.util.*;
0056: import org.openide.windows.TopComponent;
0057:
0058: import java.beans.*;
0059:
0060: import java.io.*;
0061:
0062: import java.net.*;
0063:
0064: import java.util.*;
0065:
0066: import javax.swing.*;
0067: import javax.swing.text.*;
0068:
0069: import org.netbeans.modules.collab.channel.filesharing.FilesharingConstants;
0070: import org.netbeans.modules.collab.channel.filesharing.FilesharingContext;
0071: import org.netbeans.modules.collab.channel.filesharing.FilesharingEventNotifierFactory;
0072: import org.netbeans.modules.collab.channel.filesharing.FilesharingEventProcessorFactory;
0073: import org.netbeans.modules.collab.channel.filesharing.context.LockRegionContext;
0074: import org.netbeans.modules.collab.channel.filesharing.context.UnlockRegionContext;
0075: import org.netbeans.modules.collab.channel.filesharing.eventhandler.LockRegionManager;
0076: import org.netbeans.modules.collab.channel.filesharing.event.LockRegionEvent;
0077: import org.netbeans.modules.collab.channel.filesharing.event.UnlockRegionEvent;
0078: import org.netbeans.modules.collab.channel.filesharing.eventlistener.DocumentTabMarker;
0079: import org.netbeans.modules.collab.channel.filesharing.eventlistener.EditorComponentFocusListener;
0080: import org.netbeans.modules.collab.channel.filesharing.eventlistener.FilesharingDocumentListener;
0081: import org.netbeans.modules.collab.channel.filesharing.eventlistener.FilesharingTimerTask;
0082: import org.netbeans.modules.collab.channel.filesharing.eventlistener.SendFileTimerTask;
0083: import org.netbeans.modules.collab.channel.filesharing.eventlistener.SwingThreadTask;
0084: import org.netbeans.modules.collab.channel.filesharing.filesystem.CollabFilesystem;
0085: import org.netbeans.modules.collab.channel.filesharing.mdc.CollabContext;
0086: import org.netbeans.modules.collab.channel.filesharing.mdc.EventNotifier;
0087: import org.netbeans.modules.collab.channel.filesharing.mdc.EventProcessor;
0088: import org.netbeans.modules.collab.channel.filesharing.mdc.eventlistener.CollabDocumentListener;
0089: import org.netbeans.modules.collab.channel.filesharing.mdc.util.Base64;
0090: import org.netbeans.modules.collab.channel.filesharing.mdc.util.StreamCopier;
0091: import org.netbeans.modules.collab.channel.filesharing.msgbean.Content;
0092: import org.netbeans.modules.collab.channel.filesharing.msgbean.FileChanged;
0093: import org.netbeans.modules.collab.channel.filesharing.msgbean.FileChangedData;
0094: import org.netbeans.modules.collab.channel.filesharing.msgbean.FileData;
0095: import org.netbeans.modules.collab.channel.filesharing.msgbean.LineRegion;
0096: import org.netbeans.modules.collab.channel.filesharing.msgbean.LineRegionFunction;
0097: import org.netbeans.modules.collab.channel.filesharing.msgbean.LockRegionData;
0098: import org.netbeans.modules.collab.channel.filesharing.msgbean.RegionChanged;
0099: import org.netbeans.modules.collab.channel.filesharing.msgbean.SendFile;
0100: import org.netbeans.modules.collab.channel.filesharing.msgbean.SendFileData;
0101: import org.netbeans.modules.collab.channel.filesharing.msgbean.TextChange;
0102: import org.netbeans.modules.collab.channel.filesharing.msgbean.TextRegion;
0103: import org.netbeans.modules.collab.channel.filesharing.msgbean.TextRegionChanged;
0104: import org.netbeans.modules.collab.channel.filesharing.msgbean.UnlockRegion;
0105: import org.netbeans.modules.collab.channel.filesharing.msgbean.UnlockRegionData;
0106: import org.netbeans.modules.collab.channel.filesharing.util.FileshareUtil;
0107: import org.netbeans.modules.collab.core.Debug;
0108:
0109: /**
0110: * Support class for all class implements CollabFileHandler
0111: *
0112: * @author Ayub Khan, ayub.khan@sun.com
0113: * @version 1.0
0114: */
0115: public abstract class CollabFileHandlerSupport extends Object implements
0116: FilesharingConstants, KeyListener, MouseListener {
0117: ////////////////////////////////////////////////////////////////////////////
0118: // Instance variables
0119: ////////////////////////////////////////////////////////////////////////////
0120:
0121: /* holds CollabContext */
0122: protected FilesharingContext context = null;
0123:
0124: /* file Name */
0125: protected String fileName = null;
0126:
0127: /* sharedFileGroup */
0128: protected SharedFileGroup sharedFileGroup = null;
0129:
0130: /* fileObject */
0131: protected FileObject fileObject = null;
0132:
0133: /* contentType */
0134: protected String contentType = null;
0135:
0136: /* document listener */
0137: protected CollabDocumentListener documentListener = null;
0138:
0139: /* count to make regionName unique */
0140: protected int regionCount = 0;
0141:
0142: /* store filechange status */
0143: protected boolean fileChanged = false;
0144:
0145: /* current region that changed */
0146: protected CollabRegion currentUpdatedRegion = null;
0147:
0148: /* disable insertUpdate callback */
0149: protected boolean inReceiveSendFile = false;
0150:
0151: /* disable while inPauseState, and enable if received resume*/
0152: protected boolean inPauseState = false;
0153:
0154: /* disable insert/remove if set to true */
0155: protected boolean skipUpdate = true;
0156:
0157: /* skipUpdateAlways */
0158: protected boolean skipUpdateAlways = false;
0159:
0160: /* previousDocLength for adding a doc listener */
0161: protected int previousDocLength = -1;
0162:
0163: /* isValid, if false then this handler is invalid */
0164: protected boolean isValid = true;
0165:
0166: /* getReadyToSendFile */
0167: protected boolean getReadyToSendFile = false;
0168:
0169: /*disableReceiveSendFile*/
0170: protected boolean disableReceiveSendFile = false;
0171:
0172: /* filehandler state */
0173: protected int currentState = FilesharingContext.STATE_UNKNOWN;
0174:
0175: /* sendFile TimerTask */
0176: protected SendFileTimerTask sendFileTimerTask = null;
0177:
0178: /* scheduledSendFileGroupStatus */
0179: protected boolean scheduledSendFileGroupStatus = false;
0180:
0181: /* firstTimeSend */
0182: protected boolean firstTimeSend = true;
0183:
0184: /* lineRegionKey */
0185: protected String lineRegionKey = null;
0186:
0187: /* newLineCount */
0188: protected int newLineCount = 0;
0189:
0190: /* documentLock */
0191: protected String documentLock = "documentLock";
0192:
0193: /* editor cookie */
0194: protected EditorCookie editorCookie = null;
0195:
0196: /* done Reset Document */
0197: protected boolean doneResetDoc = false;
0198:
0199: /* inReceiveMessageUnlock */
0200: protected boolean inReceiveMessageUnlock = false;
0201:
0202: /* disableUnlockTimer */
0203: protected boolean disableUnlockTimer = false;
0204:
0205: /* editorObservableCookie */
0206: protected EditorCookie.Observable editorObservableCookie = null;
0207:
0208: /* cookieListener */
0209: protected CollabEditorCookieListener cookieListener = null;
0210:
0211: /* pauseEditorLock */
0212: protected EditorLock pauseEditorLock = null;
0213:
0214: /* userStyles */
0215: protected HashMap userStyles = new HashMap();
0216: protected byte[] fileContent = null;
0217: protected FileLock fileLock = null;
0218: protected OutputStream fileOutputStream = null;
0219: protected long joinTimeStamp = -1;
0220: protected boolean isSendFileContentOnly = false;
0221: protected HashMap focusListenerMap = new HashMap();
0222: protected boolean undoEditLock = false;
0223: protected RegionQueue queue = null;
0224: private CollabRegionContext rCtx = null;
0225: private EditorLock createRegionEditorLock = null;
0226:
0227: /* Lock Region Manager Map */
0228: private HashMap lrmanagers = new HashMap();
0229:
0230: /**
0231: *
0232: *
0233: */
0234: public CollabFileHandlerSupport() {
0235: super ();
0236:
0237: //init queue
0238: queue = new RegionQueue((CollabFileHandler) this );
0239:
0240: //init region context
0241: rCtx = new CollabRegionContext();
0242: }
0243:
0244: ////////////////////////////////////////////////////////////////////////////
0245: // File handler methods
0246: ////////////////////////////////////////////////////////////////////////////
0247:
0248: /**
0249: * handles send-file message
0250: *
0251: * @param messageOriginator the sender of this message
0252: * @param sendFileData the send-file-data Node inside the message
0253: * @throws CollabException
0254: */
0255: public void handleSendFile(final String messageOriginator,
0256: final SendFileData sendFileData) throws CollabException {
0257: //copy contents from message to files; add files to CollabFileSystem
0258: EditorLock editorLock = null;
0259:
0260: try {
0261: String fullPath = sendFileData.getFileData().getFileName();
0262: String tmpContentType = sendFileData.getFileData()
0263: .getContentType();
0264:
0265: if ((tmpContentType != null)
0266: && !tmpContentType.trim().equals("")) {
0267: setContentType(tmpContentType);
0268: }
0269:
0270: Content sendFileContent = sendFileData.getContent();
0271: byte[] fileContent = decodeBase64(sendFileContent.getData());
0272:
0273: inReceiveSendFile = true;
0274:
0275: //remove all annotations
0276: removeAllLineRegionAnnotation();
0277:
0278: //remove all regions if already exist
0279: rCtx.removeAllRegion();
0280:
0281: FileObject file = getFileObject(); //do not create
0282:
0283: if (file == null) {
0284: firstTimeSend = false;
0285: Debug
0286: .log("CollabFileHandlerSupport",
0287: "CollabFileHandlerSupport, creating FileObject"); //NoI18n
0288:
0289: //create or update if exist
0290: createFileObject(fileContent);
0291:
0292: //find initial guarded sections once
0293: findInitialGuardedSections();
0294: } else {
0295: String content = new String(fileContent);
0296: updateDocument(content);
0297: }
0298: } catch (IllegalArgumentException iargs) {
0299: inReceiveSendFile = false;
0300: throw new CollabException(iargs);
0301: }
0302:
0303: //init listeners
0304: getEditorCookie();
0305:
0306: //set line region user
0307: setLineRegionKey(getContext().getLoginUser()
0308: + "_LINEREGION_USER");
0309:
0310: List newLineRegionList = new ArrayList();
0311: RegionInfo[] lineRegions = findLineRegion(sendFileData);
0312:
0313: Debug.log("CollabFileHandlerSupport",
0314: "CFHS, RCV create LineRegion: ");
0315: for (int i = 0; i < lineRegions.length; i++) {
0316: RegionInfo region = lineRegions[i];
0317: String regionName = region.getID();
0318: int beginOffset = region.getbegin();
0319: int endOffset = region.getend();
0320:
0321: try {
0322: Debug.log("CollabFileHandlerSupport", regionName
0323: + ", begin: "
0324: + beginOffset
0325: + " end: "
0326: + endOffset
0327: + getDocument().getText(beginOffset,
0328: endOffset - beginOffset)); //NoI18n
0329: Debug.log("CollabFileHandlerSupport", " begin index: "
0330: + getDocument().getDefaultRootElement()
0331: .getElementIndex(beginOffset)
0332: + " end index: "
0333: + getDocument().getDefaultRootElement()
0334: .getElementIndex(endOffset)); //NoI18n
0335: } catch (CollabException ex) {
0336: ex.printStackTrace();
0337: } catch (BadLocationException ex) {
0338: ex.printStackTrace();
0339: } //NoI18n
0340:
0341: CollabRegion lineRegion = rCtx.createLineRegion(regionName,
0342: beginOffset, endOffset);
0343:
0344: if (lineRegion == null) {
0345: continue;
0346: }
0347:
0348: rCtx.addLineRegion(regionName, lineRegion);
0349:
0350: //add annotation
0351: lineRegion.removeAnnotation();
0352:
0353: if (regionName.startsWith("RA")) //NoI18n
0354: {
0355: String lineLockUser = regionName.substring(regionName
0356: .indexOf('[') + 1, regionName.indexOf(']'));
0357: Debug.log("CollabFileHandlerSupport",
0358: "CollabFileHandlerSupport, persist annotation "
0359: + //NoI18n
0360: "for user: " + lineLockUser); //NoI18n
0361:
0362: if ((lineLockUser != null)
0363: && !lineLockUser.trim().equals("")) {
0364: int style = -1; //history annotation
0365: String annotationMessage = NbBundle
0366: .getMessage(
0367: CollabFileHandlerSupport.class,
0368: "MSG_CollabFileHandlerSupport_HistoryAnnotation", // NOI18N
0369: getContext().getPrincipal(
0370: lineLockUser)
0371: .getDisplayName());
0372: addAnnotation(lineRegion, style, annotationMessage);
0373: }
0374: }
0375: }
0376:
0377: resetAllLineRegionOffset();
0378:
0379: inReceiveSendFile = false;
0380: }
0381:
0382: /**
0383: * updateDocument
0384: *
0385: */
0386: protected void updateDocument(String content)
0387: throws CollabException {
0388: Debug.log("CollabFileHandlerSupport",
0389: "CollabFileHandlerSupport, updateDocument"); //NoI18n
0390: EditorLock editorLock = null;
0391:
0392: try {
0393: synchronized (getDocumentLock()) {
0394: editorLock = lockEditor();
0395: getDocument().remove(0, getDocument().getLength());
0396: getDocument().insertString(0, content, null);
0397: unlockEditor(editorLock);
0398: }
0399: } catch (javax.swing.text.BadLocationException e) {
0400: //throw new CollabException(e);
0401: Debug.logDebugException("CollabFileHandlerSupport, " + //NoI18n
0402: "cannot update document", e, true);//NoI18n
0403: } finally {
0404: getContext().setSkipSendFile(getName(), false);
0405: unlockEditor(editorLock);
0406: }
0407: }
0408:
0409: /**
0410: * findLineRegion
0411: *
0412: */
0413: private RegionInfo[] findLineRegion(SendFileData sendFileData)
0414: throws CollabException {
0415: RegionInfo[] regions = null;
0416: boolean chooseLineRegionFunction = sendFileData
0417: .isChooseLineRegionFunction();
0418:
0419: if (chooseLineRegionFunction) {
0420: LineRegionFunction lineRegionFuntion = sendFileData
0421: .getLineRegionFunction();
0422: List regionList = new ArrayList();
0423: StyledDocument fileDocument = getDocument();
0424: String[] regionNames = createLineRegionNames(lineRegionFuntion);
0425:
0426: for (int i = 0; i < regionNames.length; i++) {
0427: javax.swing.text.Element currentElement = fileDocument
0428: .getDefaultRootElement().getElement(i);
0429: int beginOffset = currentElement.getStartOffset();
0430: int endOffset = currentElement.getEndOffset() - 1;
0431: RegionInfo regionInfo = new RegionInfo(regionNames[i],
0432: getName(), getFileGroupName(),
0433: RegionInfo.CHAROFFSET_RANGE, beginOffset,
0434: endOffset, 0);
0435: regionList.add(regionInfo);
0436: }
0437:
0438: regions = (RegionInfo[]) regionList
0439: .toArray(new RegionInfo[0]);
0440: } else {
0441: regions = getSendFileRegion(sendFileData);
0442: }
0443:
0444: return regions;
0445: }
0446:
0447: /**
0448: * createLineRegionNames
0449: *
0450: */
0451: private String[] createLineRegionNames(
0452: LineRegionFunction lineRegionFunction) {
0453: String functionName = lineRegionFunction.getFunctionName();
0454: List returnList = new ArrayList();
0455:
0456: if ((functionName != null)
0457: && functionName.equals("simple_linear_function")) {
0458: String[] args = lineRegionFunction.getArguments();
0459:
0460: if ((args != null) && (args.length > 0)) {
0461: String prefix = args[0];
0462: String user = args[1];
0463: int count = Integer.parseInt(args[2]);
0464:
0465: for (int i = 0; i < count; i++) {
0466: String lineRegionName = prefix + "[" + user + "]"
0467: + i; //NoI18n
0468: returnList.add(lineRegionName);
0469: }
0470: }
0471: }
0472:
0473: return (String[]) returnList.toArray(new String[0]);
0474: }
0475:
0476: /**
0477: * findInitialGuardedSections
0478: *
0479: */
0480: protected void findInitialGuardedSections() throws CollabException {
0481: return;
0482: }
0483:
0484: /**
0485: * findInitialGuardedSections
0486: *
0487: */
0488: protected HashMap getInitialGuardedSections()
0489: throws CollabException {
0490: return null;
0491: }
0492:
0493: /**
0494: * handles lock-region message
0495: *
0496: * @param messageOriginator the sender of this message
0497: * @param lockRegionData the lock-region-data Node inside the message
0498: * @throws CollabException
0499: */
0500: public void handleLock(final String messageOriginator,
0501: final LockRegionData lockRegionData) throws CollabException {
0502: SwingUtilities.invokeLater(new Runnable() {
0503: public void run() {
0504: try {
0505: createLock(messageOriginator, lockRegionData);
0506: } catch (Throwable th) {
0507: Debug.log("CollabFileHandlerSupport",
0508: "CollabFileHandlerSupport, " + //NoI18n
0509: "cannot create received Lock "); //NoI18n
0510: Debug.logDebugException(
0511: "CollabFileHandlerSupport, " + //NoI18n
0512: "cannot create received Lock", //NoI18n
0513: th, true);
0514: }
0515: }
0516: });
0517: }
0518:
0519: /**
0520: * handles lock-region message
0521: *
0522: * @param messageOriginator the sender of this message
0523: * @param lockRegionData the lock-region-data Node inside the message
0524: * @throws CollabException
0525: */
0526: private void createLock(final String messageOriginator,
0527: final LockRegionData lockRegionData) throws CollabException {
0528: Debug.log("CollabFileHandlerSupport",
0529: "CollabFileHandlerSupport, receivedMessageLock"); //NoI18n
0530:
0531: //copy contents from message to files; add files to CollabFileSystem
0532: EditorLock editorLock = null;
0533:
0534: try {
0535: String fullPath = lockRegionData.getFileName();
0536: StyledDocument fileDocument = getDocument();
0537:
0538: synchronized (getDocumentLock()) {
0539: editorLock = lockEditor();
0540:
0541: int documentLength = fileDocument.getLength();
0542: RegionInfo region = getLockRegion(lockRegionData);
0543: String regionName = region.getID();
0544: int beginOffset = region.getbegin();
0545: int endOffset = region.getend();
0546: int length = endOffset - beginOffset;
0547:
0548: if (endOffset > documentLength) {
0549: endOffset = documentLength;
0550: }
0551:
0552: CollabLineRegion[] cLineRegions = getCollabLineRegion(lockRegionData);
0553: Debug.log("CollabFileHandlerSupport",
0554: "CollabFileHandlerSupport, # of lineRegions: " + //NoI18n
0555: cLineRegions.length);
0556: if (cLineRegions.length > 0) {
0557: //identify lineregion
0558: List cLineRegionList = new ArrayList();
0559: cLineRegionList.addAll(Arrays.asList(cLineRegions));
0560: rCtx.resetLineRegion(regionName, cLineRegionList,
0561: false); //do not remove old lines
0562:
0563: String firstLineName = cLineRegions[0].getID();
0564: String lastLineName = cLineRegions[cLineRegions.length - 1]
0565: .getID();
0566: Debug.log("CollabFileHandlerSupport",
0567: "CollabFileHandlerSupport, firstLineName: "
0568: + //NoI18n
0569: firstLineName);
0570: Debug.log("CollabFileHandlerSupport",
0571: "CollabFileHandlerSupport, lastLineName: " + //NoI18n
0572: lastLineName);
0573: CollabLineRegion firstLineRegion = (CollabLineRegion) rCtx
0574: .getLineRegion(firstLineName);
0575: CollabLineRegion lastLineRegion = (CollabLineRegion) rCtx
0576: .getLineRegion(lastLineName);
0577:
0578: if (firstLineRegion == null
0579: || lastLineRegion == null)
0580: return;
0581:
0582: beginOffset = firstLineRegion.getBeginOffset();
0583: endOffset = lastLineRegion.getEndOffset();
0584: Debug.log("CollabFileHandlerSupport",
0585: "CollabFileHandlerSupport, beginOffset: " + //NoI18n
0586: beginOffset);
0587: Debug.log("CollabFileHandlerSupport",
0588: "CollabFileHandlerSupport, endOffset: " + //NoI18n
0589: endOffset);
0590:
0591: CollabRegion simpleSection = createSimpleSection(
0592: beginOffset, endOffset, regionName);
0593: /*if(simpleSection==null) { //check with correction: cannot create section
0594: simpleSection = createSimpleSection(beginOffset+1, endOffset, regionName);
0595:
0596: if (simpleSection == null) //check with correction
0597: { //cannot create section
0598: simpleSection = createSimpleSection(beginOffset, endOffset - 1, regionName);
0599:
0600: if (simpleSection == null) //check with correction
0601: { //cannot create section
0602: simpleSection = createSimpleSection(beginOffset+1, endOffset - 1, regionName);
0603:
0604: if (simpleSection == null) //check with correction
0605: { //cannot create section
0606: unlockEditor(editorLock);
0607: return;
0608: }
0609: }
0610: }
0611: }*/
0612: if (simpleSection == null) //check with correction
0613: { //cannot create section
0614: Debug.log("CollabFileHandlerSupport", "CFHS, "
0615: + "create section null for: "
0616: + regionName); //NoI18n
0617: unlockEditor(editorLock);
0618: return;
0619: }
0620:
0621: Debug.log("CollabFileHandlerSupport",
0622: "CFHS, receivedLock " + "for text : ["
0623: + simpleSection.getContent() + "]"); //NoI18n
0624: rCtx.addRegion(messageOriginator, regionName,
0625: simpleSection);
0626:
0627: //Set parent
0628: for (int i = 0; i < cLineRegionList.size(); i++) {
0629: CollabLineRegion liner = (CollabLineRegion) cLineRegionList
0630: .get(i);
0631: if (liner != null) {
0632: Debug.log("CollabFileHandlerSupport",
0633: "CFHS, setAssigned " + "true for: "
0634: + liner.getID()); //NoI18n
0635: liner.setAssigned(simpleSection, true);
0636: }
0637: }
0638:
0639: //add annotation
0640: String annotationMessage = NbBundle
0641: .getMessage(
0642: CollabFileHandlerSupport.class,
0643: "MSG_CollabFileHandlerSupport_EditingAnnotation", // NOI18N
0644: getContext().getPrincipal(
0645: messageOriginator)
0646: .getDisplayName());
0647: int style = getUserStyle(messageOriginator);
0648: addLineRegionAnnotation(
0649: (CollabLineRegion[]) cLineRegionList
0650: .toArray(new CollabLineRegion[0]),
0651: style, annotationMessage);
0652: }
0653: }
0654: } catch (IllegalArgumentException iargs) {
0655: throw new CollabException(iargs);
0656: } finally {
0657: unlockEditor(editorLock);
0658: }
0659: }
0660:
0661: /**
0662: * addLineRegionAnnotation
0663: *
0664: * @param lineRegions
0665: * @param annotationMessage
0666: * @param style
0667: */
0668: private void addLineRegionAnnotation(
0669: CollabLineRegion[] lineRegions, int style,
0670: String annotationMessage) throws CollabException {
0671: for (int i = 0; i < lineRegions.length; i++) {
0672: CollabLineRegion lineRegion = lineRegions[i];
0673:
0674: if (lineRegion != null) {
0675: lineRegion.removeAnnotation();
0676: addAnnotation(lineRegion, style, annotationMessage);
0677: }
0678: }
0679: }
0680:
0681: /**
0682: * addAnnotation
0683: *
0684: * @param region
0685: * @param annotationMessage
0686: * @param style
0687: */
0688: private void addAnnotation(CollabRegion region, int style,
0689: String annotationMessage) throws CollabException {
0690: region.addAnnotation(FileshareUtil
0691: .getDataObject(getFileObject()),
0692: (CollabFileHandler) this , style, annotationMessage);
0693: }
0694:
0695: /**
0696: * handles sendChange message
0697: *
0698: * @param messageOriginator the sender of this message
0699: * @param fileChangedData
0700: * @throws CollabException
0701: * @deprecated
0702: */
0703: public void handleSendChange(String messageOriginator,
0704: FileChangedData fileChangedData) throws CollabException {
0705: }
0706:
0707: /**
0708: * handles unlock-region message
0709: *
0710: * @param messageOriginator the sender of this message
0711: * @param unlockRegionData the unlock-region-data Node inside the message
0712: * @throws CollabException
0713: */
0714: public void handleUnlock(final String messageOriginator,
0715: final UnlockRegionData unlockRegionData)
0716: throws CollabException {
0717: SwingUtilities.invokeLater(new Runnable() {
0718: public void run() {
0719: try {
0720: releaseLock(messageOriginator, unlockRegionData);
0721: } catch (Throwable th) {
0722: Debug.log("CollabFileHandlerSupport",
0723: "CollabFileHandlerSupport, " + //NoI18n
0724: "cannot release Lock "); //NoI18n
0725: Debug.logDebugException(
0726: "CollabFileHandlerSupport, " + //NoI18n
0727: "cannot release Lock", //NoI18n
0728: th, true);
0729: }
0730: }
0731: });
0732: }
0733:
0734: /**
0735: * release Lock
0736: *
0737: * @param messageOriginator the sender of this message
0738: * @param unlockRegionData the unlock-region-data Node inside the message
0739: * @throws CollabException
0740: */
0741: private void releaseLock(final String messageOriginator,
0742: final UnlockRegionData unlockRegionData)
0743: throws CollabException {
0744: Debug.log("CollabFileHandlerSupport",
0745: "CollabFileHandlerSupport, receivedMessageUnlock"); //NoI18n
0746: inReceiveMessageUnlock = true;
0747:
0748: EditorLock editorLock = null;
0749: String regionName = null;
0750:
0751: //copy contents from message to files; add files to CollabFileSystem
0752: try {
0753: String fullPath = unlockRegionData.getFileName();
0754: StyledDocument fileDocument = getDocument();
0755:
0756: int documentLength = fileDocument.getLength();
0757: RegionInfo region = getUnlockRegion(unlockRegionData);
0758:
0759: regionName = region.getID();
0760: Debug.log("CollabFileHandlerSupport",
0761: "CFHS, releaseLock regionName: " + regionName); //NoI18n
0762: int beginOffset = region.getbegin();
0763: int endOffset = region.getend();
0764:
0765: CollabRegion sect = rCtx.getRegion(regionName);
0766:
0767: if (sect == null) {
0768: inReceiveMessageUnlock = false;
0769:
0770: return;
0771: }
0772:
0773: if (unlockRegionData.getContent() != null) {
0774: LineRegion[] lineRegions = unlockRegionData
0775: .getLineRegion();
0776: Debug.log("CollabFileHandlerSupport",
0777: "CollabFileHandlerSupport, # of lineRegions: " //NoI18n
0778: + lineRegions.length);
0779:
0780: List newLineRegionNames = new ArrayList();
0781:
0782: if (lineRegions.length > 0) {
0783: for (int i = 0; i < lineRegions.length; i++) {
0784: LineRegion lineRegion = lineRegions[i];
0785: String lineRegionName = lineRegion
0786: .getRegionName();
0787: newLineRegionNames.add(lineRegionName);
0788: }
0789: }
0790:
0791: Content content = unlockRegionData.getContent();
0792: String text = new String(
0793: decodeBase64(content.getData()));
0794: Debug.log("CollabFileHandlerSupport",
0795: "CFHS, received unlock for "
0796: + //NoI18n
0797: "region: " + regionName
0798: + " with update : [" + text + "]");//NoI18n
0799:
0800: synchronized (getDocumentLock()) {
0801: editorLock = lockEditor();
0802:
0803: boolean originallyModified = isDocumentModified();
0804:
0805: //remove previous annotation before update
0806: CollabRegion cregion = getRegion(regionName);
0807: cregion.removeAnnotation();
0808: beginOffset = sect.getBeginOffset();
0809: Debug.log("CollabFileHandlerSupport",
0810: "CFHS, region before " + "update: ["
0811: + cregion.getContent() + "]"); //NoI18n
0812: boolean status = doUpdateRegion(messageOriginator,
0813: sect, text);
0814: Debug.log("CollabFileHandlerSupport",
0815: "CFHS, region after " + "update: ["
0816: + cregion.getContent() + "]"); //NoI18n
0817: endOffset = sect.getEndOffset();
0818:
0819: if (status) {
0820: List newLineRegionList = rCtx
0821: .doUpdateLineRegion(regionName,
0822: beginOffset, endOffset,
0823: unlockRegionData,
0824: (String[]) newLineRegionNames
0825: .toArray(new String[0]));
0826:
0827: //persist line annotation
0828: String annotationMessage = NbBundle
0829: .getMessage(
0830: CollabFileHandlerSupport.class,
0831: "MSG_CollabFileHandlerSupport_HistoryAnnotation", // NOI18N
0832: getContext().getPrincipal(
0833: messageOriginator)
0834: .getDisplayName());
0835:
0836: int style = -1; //history annotation
0837: addLineRegionAnnotation(
0838: (CollabLineRegion[]) newLineRegionList
0839: .toArray(new CollabLineRegion[0]),
0840: style, annotationMessage);
0841: }
0842:
0843: if (!originallyModified) {
0844: getContext().setSkipSendFile(getName(), true);
0845: saveDocument();
0846: getContext().setSkipSendFile(getName(), false);
0847: }
0848: }
0849: }
0850: } catch (IllegalArgumentException iargs) {
0851: throw new CollabException(iargs);
0852: } finally {
0853: try {
0854: if (regionName != null) {
0855: CollabRegion r = getRegion(regionName);
0856: if (r != null)
0857: r.setValid(false);
0858: removeRegion(messageOriginator, regionName);
0859: }
0860: } catch (Exception e) {
0861: Debug.logDebugException(
0862: "CFHS, exception removing region: "
0863: + regionName, e, true);
0864: }
0865: unlockEditor(editorLock);
0866: inReceiveMessageUnlock = false;
0867: }
0868: }
0869:
0870: /**
0871: * removes all region from the repository
0872: *
0873: * @throws CollabException
0874: */
0875: public void removeAllRegion() throws CollabException {
0876: rCtx.removeAllRegion();
0877: }
0878:
0879: /**
0880: * removes region
0881: *
0882: * @param user
0883: * @param regionName
0884: *
0885: * @throws CollabException
0886: */
0887: public void removeRegion(String user, String regionName)
0888: throws CollabException {
0889: rCtx.removeRegion(user, regionName);
0890: }
0891:
0892: /**
0893: * isDocumentModified
0894: *
0895: */
0896: public boolean isDocumentModified() throws CollabException {
0897: boolean isModified = false;
0898: EditorCookie cookie = getEditorCookie();
0899:
0900: if (cookie != null) {
0901: isModified = cookie.isModified();
0902: }
0903:
0904: Debug.log("CollabFileHandlerSupport", //NoI18n
0905: "CollabFileHandlerSupport, isModified: " + isModified
0906: + " for file " + getName()); //NoI18n
0907:
0908: return isModified;
0909: }
0910:
0911: /**
0912: * saveDocument
0913: *
0914: */
0915: public boolean saveDocument() throws CollabException {
0916: Debug.log("CollabFileHandlerSupport", //NoI18n
0917: "CollabFileHandlerSupport, saving document: " //NoI18n
0918: + getName() + " on update"); //NoI18n
0919:
0920: try {
0921: SwingUtilities.invokeLater(new Runnable() {
0922: public void run() {
0923: try {
0924: editorCookie = getEditorCookie();
0925: } catch (Throwable th) {
0926: Debug
0927: .log("CollabFileHandlerSupport",
0928: "CollabFileHandlerSupport, " + //NoI18n
0929: "wait to getEditorCookie failed"); //NoI18n
0930: Debug
0931: .logDebugException(
0932: "CollabFileHandlerSupport, " + //NoI18n
0933: "wait to getEditorCookie failed", //NoI18n
0934: th, true);
0935: }
0936: }
0937: });
0938:
0939: if (editorCookie != null) {
0940: editorCookie.saveDocument();
0941: }
0942: } catch (IOException iox) {
0943: Debug.log("CollabFileHandlerSupport", //NoI18n
0944: "Exception occured while saving the document: " //NoI18n
0945: + getName() + " on update"); //NoI18n
0946:
0947: return false;
0948: }
0949:
0950: return true;
0951: }
0952:
0953: /**
0954: * getDocumentLock
0955: *
0956: */
0957: protected Object getDocumentLock() {
0958: return documentLock;
0959: }
0960:
0961: /**
0962: * findTopComponent
0963: *
0964: * @return TopComponent
0965: */
0966: public TopComponent findTopComponent() {
0967: String[] paths = getName().split("/");
0968: String tcName = paths[paths.length - 1];
0969: TopComponent.Registry reg = TopComponent.getRegistry();
0970: Set opened = reg.getOpened();
0971: for (Iterator it = opened.iterator(); it.hasNext();) {
0972: TopComponent tc = (TopComponent) it.next();
0973: String displayName = tc.getDisplayName();
0974: if (displayName != null
0975: && displayName.indexOf(tcName) != -1
0976: && displayName.length() > (tcName.length() + 8)) {//*[Shared] len>8
0977: return tc;
0978: }
0979: }
0980: return null;
0981: }
0982:
0983: /**
0984: * lockFileForCreateRegion
0985: *
0986: */
0987: public void lockFileForCreateRegion() {
0988: setCurrentState(FilesharingContext.STATE_LOCK);
0989: SwingUtilities.invokeLater(new Runnable() {
0990: public void run() {
0991: try {
0992: createRegionEditorLock = lockEditor();
0993: } catch (Throwable th) {
0994: Debug.log("CollabFileHandlerSupport",
0995: "CollabFileHandlerSupport, " + //NoI18n
0996: "cannot create received Lock ");//NoI18n
0997: Debug.logDebugException(
0998: "CollabFileHandlerSupport, " + //NoI18n
0999: "cannot create received Lock", th,
1000: true);//NoI18n
1001: }
1002: }
1003: });
1004: }
1005:
1006: /**
1007: * lockEditor
1008: *
1009: */
1010: public final EditorLock lockEditor() throws CollabException {
1011: return doLockEditor();
1012: }
1013:
1014: /**
1015: * lockEditor
1016: *
1017: */
1018: protected EditorLock doLockEditor() throws CollabException {
1019: Debug.log("CollabFileHandlerSupport",
1020: "CollabFileHandlerSupport, locking Editor"); //NoI18n
1021: disableUnlockTimer(true);
1022:
1023: JEditorPane[] editorPanes = getEditorPanes();
1024:
1025: if (editorPanes == null) {
1026: return null;
1027: }
1028:
1029: Debug.log("CollabFileHandlerSupport",
1030: "CollabFileHandlerSupport, # of editorPanes: " + //NoI18n
1031: editorPanes.length);
1032:
1033: EditorLock editorLock = new EditorLock(editorPanes);
1034:
1035: //hack - since editorCookie.getOpenedPanes(); returns null for opened_panes
1036: //Here it successfully returns the panes when user edits the java file
1037: for (int i = 0; i < editorPanes.length; i++) {
1038: JEditorPane editorPane = editorPanes[i];
1039:
1040: if (editorPane != null) {
1041: EditorComponentFocusListener focusListener = null;
1042:
1043: //remove old
1044: focusListener = (EditorComponentFocusListener) focusListenerMap
1045: .get(editorPane);
1046:
1047: if (focusListener != null) {
1048: editorPane.removeFocusListener(focusListener);
1049: }
1050:
1051: //add new
1052: focusListener = new EditorComponentFocusListener(
1053: getName(), getContext().getChannel());
1054: editorPane.addFocusListener(focusListener);
1055: focusListenerMap.put(editorPane, focusListener);
1056: }
1057: }
1058:
1059: editorLock.lock();
1060:
1061: return editorLock;
1062: }
1063:
1064: public void unlockFileForCreateRegion() {
1065: setCurrentState(FilesharingContext.STATE_UNKNOWN);
1066: SwingUtilities.invokeLater(new Runnable() {
1067: public void run() {
1068: try {
1069: unlockEditor(createRegionEditorLock);
1070: } catch (Throwable th) {
1071: Debug.log("CollabFileHandlerSupport",
1072: "CollabFileHandlerSupport, " + //NoI18n
1073: "cannot create received Lock ");//NoI18n
1074: Debug.logDebugException(
1075: "CollabFileHandlerSupport, " + //NoI18n
1076: "cannot create received Lock", th,
1077: true);//NoI18n
1078: }
1079: }
1080: });
1081: }
1082:
1083: /**
1084: * unlockEditor
1085: *
1086: */
1087: public void unlockEditor(EditorLock editorLock) {
1088: Debug.log("CollabFileHandlerSupport",
1089: "CollabFileHandlerSupport, unlocking Editor"); //NoI18n
1090:
1091: //do not enable edit for user readOnly conversation
1092: if (getContext().isReadOnlyConversation()) {
1093: return;
1094: }
1095:
1096: if (editorLock != null) {
1097: editorLock.releaseLock();
1098: /*TopComponent tc=findTopComponent();
1099: if(tc!=null) tc.requestActive();*/
1100: }
1101:
1102: // Hack, to set focus to users current file editorPane
1103: Debug.log("CollabFileHandlerSupport", "CFHS, request Focus"
1104: + "after createLock for user: "
1105: + getContext().getLoginUser());
1106: if (FilesharingCollablet.currentEditorPane != null) {
1107: FilesharingCollablet.currentEditorPane
1108: .requestFocusInWindow();
1109: }
1110:
1111: disableUnlockTimer(false);
1112: }
1113:
1114: /**
1115: * resetAllLock
1116: *
1117: */
1118: protected void resetAllLock() throws CollabException {
1119: Debug.log("CollabFileHandlerSupport",
1120: "CollabFileHandlerSupport, resetAllLock"); //NoI18n
1121:
1122: JEditorPane[] editorPanes = getEditorPanes();
1123:
1124: if (editorPanes == null) {
1125: return;
1126: }
1127:
1128: Debug.log("CollabFileHandlerSupport",
1129: "CollabFileHandlerSupport, # of editorPanes: " + //NoI18n
1130: editorPanes.length);
1131:
1132: if (editorPanes != null) {
1133: for (int i = 0; i < editorPanes.length; i++) {
1134: if (editorPanes[i] != null) {
1135: Debug.log("CollabFileHandlerSupport",
1136: "CollabFileHandlerSupport, editorPane: " + //NoI18n
1137: editorPanes[i].getName());
1138: editorPanes[i].setEnabled(true);
1139: }
1140: }
1141: }
1142:
1143: disableUnlockTimer(false);
1144: }
1145:
1146: /**
1147: * handles pause - Pause edit operation
1148: *
1149: * @param collabBean
1150: * @throws CollabException
1151: */
1152: public void handlePause() throws CollabException {
1153: setCurrentState(FilesharingContext.STATE_PAUSE);
1154: inPauseState = true;
1155: SwingUtilities.invokeLater(new Runnable() {
1156: public void run() {
1157: try {
1158: pauseEditorLock = lockEditor();
1159: } catch (Throwable th) {
1160: Debug.log("CollabFileHandlerSupport",
1161: "CollabFileHandlerSupport, " + //NoI18n
1162: "cannot create received Lock "); //NoI18n
1163: Debug.logDebugException(
1164: "CollabFileHandlerSupport, " + //NoI18n
1165: "cannot create received Lock", //NoI18n
1166: th, true);
1167: }
1168: }
1169: });
1170: }
1171:
1172: /**
1173: * handles resume - Resume edit operation
1174: *
1175: * @param collabBean
1176: * @throws CollabException
1177: */
1178: public void handleResume() throws CollabException {
1179: setCurrentState(FilesharingContext.STATE_RESUME);
1180: inPauseState = false;
1181: setSkipUpdate(false);
1182:
1183: SwingUtilities.invokeLater(new Runnable() {
1184: public void run() {
1185: try {
1186: unlockEditor(pauseEditorLock);
1187: } catch (Throwable th) {
1188: Debug.log("CollabFileHandlerSupport",
1189: "CollabFileHandlerSupport, " + //NoI18n
1190: "cannot create received Lock "); //NoI18n
1191: Debug.logDebugException(
1192: "CollabFileHandlerSupport, " + //NoI18n
1193: "cannot create received Lock", //NoI18n
1194: th, true);
1195: }
1196: }
1197: });
1198: }
1199:
1200: /**
1201: * constructs file-changed-data Node
1202: *
1203: * @param fileChanged the file-changed Node
1204: * @return fileChangedData the file-changed-data Node
1205: * @throws CollabException
1206: * @deprecated
1207: */
1208: public FileChangedData constructFileChangedData(
1209: FileChanged fileChanged) throws CollabException {
1210: return null;
1211: }
1212:
1213: /**
1214: * constructs region Node
1215: *
1216: * @param regionName
1217: * @param regionInfo RegionInfo
1218: * @param pregion Protocol region
1219: */
1220: public void constructRegion(RegionInfo regionInfo, Object pregion)
1221: throws CollabException {
1222: String regionName = regionInfo.getID();
1223: String mode = regionInfo.getMode();
1224: int beginOffset = 0;
1225: int endOffset = 0;
1226: StyledDocument fileDocument = getDocument();
1227:
1228: if (mode.equals(RegionInfo.LINE_RANGE)) {
1229: javax.swing.text.Element beginElement = fileDocument
1230: .getDefaultRootElement().getElement(
1231: regionInfo.getbegin());
1232: beginOffset = beginElement.getStartOffset();
1233:
1234: javax.swing.text.Element endElement = fileDocument
1235: .getDefaultRootElement().getElement(
1236: regionInfo.getend());
1237: endOffset = endElement.getEndOffset();
1238: } else {
1239: beginOffset = regionInfo.getbegin();
1240: endOffset = regionInfo.getend();
1241:
1242: int endCorrection = regionInfo.getCorrection();
1243: endOffset += endCorrection;
1244:
1245: if (endOffset < 0) {
1246: endOffset = 0;
1247: }
1248: }
1249:
1250: if (pregion instanceof TextRegion) {
1251: TextRegion textRegion = (TextRegion) pregion;
1252: int length = endOffset - beginOffset;
1253: textRegion.setRegionName(regionName);
1254: textRegion.setBeginOffset(new java.math.BigInteger(String
1255: .valueOf(beginOffset)));
1256: textRegion.setLength(new java.math.BigInteger(String
1257: .valueOf(length)));
1258: } else if (pregion instanceof LineRegion) {
1259: LineRegion lineRegion = (LineRegion) pregion;
1260: lineRegion.setRegionName(regionName);
1261: }
1262: }
1263:
1264: /**
1265: * getContent
1266: *
1267: * @param regionChanged the region-changed Node
1268: * @param content
1269: */
1270: public Content getContent(RegionChanged regionChanged)
1271: throws CollabException {
1272: TextRegionChanged textRegionChanged = regionChanged
1273: .getTextRegionChanged();
1274: TextChange textChange = textRegionChanged.getTextChange();
1275: Content content = null;
1276:
1277: if (textChange.getContent() != null) {
1278: content = textChange.getContent();
1279: }
1280:
1281: return content;
1282: }
1283:
1284: /**
1285: * getChangeRegion
1286: *
1287: * @param regionChanged the region-changed Node
1288: * @param regionName
1289: */
1290: public RegionInfo getChangeRegion(RegionChanged regionChanged)
1291: throws CollabException {
1292: TextRegionChanged textRegionChanged = regionChanged
1293: .getTextRegionChanged();
1294: TextRegion textRegion = textRegionChanged.getTextRegion();
1295: RegionInfo regionInfo = new RegionInfo(textRegion
1296: .getRegionName(), getName(), getFileGroupName(),
1297: RegionInfo.CHAROFFSET_RANGE, textRegion
1298: .getBeginOffset().intValue(), textRegion
1299: .getLength().intValue(), 0);
1300:
1301: return regionInfo;
1302: }
1303:
1304: /**
1305: * constructs lock-region-data Node
1306: *
1307: * @param regionInfo the RegionInfo bean
1308: * @param lockRegionData the intial lock-region-data Node
1309: * @throws CollabException
1310: * @see RegionInfo
1311: */
1312: public void constructLockRegionData(RegionInfo regionInfo,
1313: LockRegionData lockRegionData) throws CollabException {
1314: Debug.log("CollabFileHandlerSupport",
1315: "CollabFileHandlerSupport, construct LockRegionData"); //NoI18n
1316: setCurrentState(FilesharingContext.STATE_LOCK);
1317: lockRegionData.setFileName(getName());
1318:
1319: Object pregion = setLockRegion(lockRegionData);
1320:
1321: constructRegion(regionInfo, pregion);
1322:
1323: String regionName = regionInfo.getID();
1324: CollabRegion cregion = (CollabRegion) rCtx
1325: .getRegion(regionName);
1326:
1327: int regionBegin = regionInfo.getbegin();
1328: int regionEnd = regionInfo.getend();
1329: regionEnd += regionInfo.getCorrection();
1330:
1331: int length = regionEnd - regionBegin;
1332: Debug
1333: .log("CollabFileHandlerSupport",
1334: "CollabFileHandlerSupport, regionBegin: "
1335: + regionBegin); //NoI18n
1336: Debug.log("CollabFileHandlerSupport",
1337: "CollabFileHandlerSupport, regionEnd: " + regionEnd); //NoI18n
1338:
1339: Vector lineRegions = regionInfo.getLineRegion();
1340: CollabLineRegion[] regions = null;
1341:
1342: if (lineRegions == null) {
1343: synchronized (getDocumentLock()) {
1344: EditorLock editorLock = null;
1345: try {
1346: editorLock = lockEditor();
1347: regions = rCtx.getContainingLineRegion(regionBegin,
1348: length/*-1*/);
1349: unlockEditor(editorLock);
1350: } catch (Exception e) {
1351: e.printStackTrace(Debug.out);
1352: } finally {
1353: unlockEditor(editorLock);
1354: }
1355: }
1356: } else {
1357: regions = (CollabLineRegion[]) lineRegions
1358: .toArray(new CollabLineRegion[0]);
1359: }
1360:
1361: if (regions != null) {
1362: Debug.log("CollabFileHandlerSupport",
1363: "CollabFileHandlerSupport, # of containing LineRegions is: "
1364: + //NoI18n
1365: regions.length);
1366: LineRegion[] pregions = setLockLineRegion(lockRegionData,
1367: regions.length);
1368:
1369: List cLineRegionList = new ArrayList();
1370:
1371: for (int i = 0; i < regions.length; i++) {
1372: CollabLineRegion cLineRegion = regions[i];
1373: LineRegion pLineRegion = pregions[i];
1374: String lineRegionName = cLineRegion.getID();
1375: Debug.log("CollabFileHandlerSupport",
1376: "CollabFileHandlerSupport, construct lock for region: "
1377: + //NoI18n
1378: lineRegionName);
1379:
1380: int beginOffset = cLineRegion.getBeginOffset();
1381: int endOffset = cLineRegion.getEndOffset();
1382:
1383: RegionInfo lineRegionInfo = new RegionInfo(
1384: lineRegionName, getName(), getFileGroupName(),
1385: RegionInfo.CHAROFFSET_RANGE, beginOffset,
1386: endOffset, 0);
1387: constructRegion(lineRegionInfo, pLineRegion);
1388: lockRegionData.setLineRegion(i, pLineRegion);
1389:
1390: cLineRegionList.add(cLineRegion);
1391: }
1392:
1393: rCtx.resetLineRegion(regionName, cLineRegionList, false); //do not remove old lines
1394: }
1395:
1396: CollabRegion textRegion = (CollabRegion) rCtx
1397: .getRegion(regionName);
1398: textRegion.setValid(true);
1399: }
1400:
1401: /**
1402: * set lock-region-data with region
1403: *
1404: * @param lockRegionData the intial lock-region-data Node
1405: * @return region
1406: */
1407: protected Object setLockRegion(LockRegionData lockRegionData) {
1408: TextRegion textRegion = new TextRegion();
1409: lockRegionData.setTextRegion(textRegion);
1410:
1411: return textRegion;
1412: }
1413:
1414: /**
1415: * set lock-region-data with region
1416: *
1417: * @param lockRegionData the intial lock-region-data Node
1418: * @return region
1419: */
1420: protected LineRegion[] setLockLineRegion(
1421: LockRegionData lockRegionData, int totalRegionCount) {
1422: List regionInfoList = new ArrayList();
1423:
1424: for (int i = 0; i < totalRegionCount; i++) {
1425: LineRegion lineRegion = new LineRegion();
1426: regionInfoList.add(lineRegion);
1427: }
1428:
1429: LineRegion[] lineRegions = (LineRegion[]) regionInfoList
1430: .toArray(new LineRegion[0]);
1431: lockRegionData.setLineRegion(lineRegions);
1432:
1433: return lineRegions;
1434: }
1435:
1436: /**
1437: * get region
1438: *
1439: * @param lockRegionData the intial lock-region-data Node
1440: * @return region
1441: */
1442: public RegionInfo getLockRegion(LockRegionData lockRegionData) {
1443: TextRegion textRegion = lockRegionData.getTextRegion();
1444: int regionBegin = textRegion.getBeginOffset().intValue();
1445: int length = textRegion.getLength().intValue();
1446: int regionEnd = regionBegin + length;
1447: CollabLineRegion[] cLineRegionList = getCollabLineRegion(lockRegionData);
1448: Vector cLineRegions = new Vector();
1449: cLineRegions.addAll(Arrays.asList(cLineRegionList));
1450: RegionInfo regionInfo = new RegionInfo(textRegion
1451: .getRegionName(), getName(), getFileGroupName(),
1452: RegionInfo.CHAROFFSET_RANGE, regionBegin, regionEnd, 0,
1453: cLineRegions);
1454: return regionInfo;
1455: }
1456:
1457: /**
1458: * getCollabLineRegion
1459: *
1460: * @param lockRegionData the intial lock-region-data Node
1461: * @return collablineregions
1462: */
1463: public CollabLineRegion[] getCollabLineRegion(
1464: LockRegionData lockRegionData) {
1465: List cLineRegionList = new ArrayList();
1466: LineRegion[] lineRegions = lockRegionData.getLineRegion();
1467: if (lineRegions.length > 0) {
1468: for (int i = 0; i < lineRegions.length; i++) {
1469: LineRegion lineRegion = lineRegions[i];
1470: String lineRegionName = lineRegion.getRegionName();
1471: CollabLineRegion cLineRegion = (CollabLineRegion) rCtx
1472: .getRegion(lineRegionName);
1473:
1474: if (cLineRegion != null)
1475: cLineRegionList.add(cLineRegion);
1476: }
1477: }
1478: return (CollabLineRegion[]) cLineRegionList
1479: .toArray(new CollabLineRegion[0]);
1480: }
1481:
1482: /**
1483: * set unlock-region-data with region
1484: *
1485: * @param unlockRegionData the intial lock-region-data Node
1486: * @throws CollabException
1487: */
1488: protected Object setUnlockRegion(UnlockRegionData unlockRegionData) {
1489: TextRegion textRegion = new TextRegion();
1490: unlockRegionData.setTextRegion(textRegion);
1491:
1492: return textRegion;
1493: }
1494:
1495: /**
1496: * set unlock-region-data with region
1497: *
1498: * @param unlockRegionData
1499: * @return region
1500: */
1501: protected LineRegion[] setUnlockLineRegion(
1502: UnlockRegionData unlockRegionData, int totalRegionCount) {
1503: List regionInfoList = new ArrayList();
1504:
1505: for (int i = 0; i < totalRegionCount; i++) {
1506: LineRegion lineRegion = new LineRegion();
1507: regionInfoList.add(lineRegion);
1508: }
1509:
1510: LineRegion[] lineRegions = (LineRegion[]) regionInfoList
1511: .toArray(new LineRegion[0]);
1512: unlockRegionData.setLineRegion(lineRegions);
1513:
1514: return lineRegions;
1515: }
1516:
1517: /**
1518: * get region
1519: *
1520: * @param unlockRegionData the intial lock-region-data Node
1521: * @return region
1522: */
1523: protected RegionInfo getUnlockRegion(
1524: UnlockRegionData unlockRegionData) {
1525: TextRegion textRegion = unlockRegionData.getTextRegion();
1526: int regionBegin = textRegion.getBeginOffset().intValue();
1527: int length = textRegion.getLength().intValue();
1528: int regionEnd = regionBegin + length;
1529: RegionInfo regionInfo = new RegionInfo(textRegion
1530: .getRegionName(), getName(), getFileGroupName(),
1531: RegionInfo.CHAROFFSET_RANGE, regionBegin, regionEnd, 0);
1532:
1533: return regionInfo;
1534: }
1535:
1536: /**
1537: * constructs unlock-region-data Node
1538: *
1539: * @param regionName the regionName
1540: * @param unlockRegionData the intial unlock-region-data Node
1541: * @throws CollabException
1542: */
1543: public void constructUnlockRegionData(String regionName,
1544: UnlockRegionData unlockRegionData) throws CollabException {
1545: Debug.log("CollabFileHandlerSupport",
1546: "CollabFileHandlerSupport, construct "
1547: + //NoI18n
1548: "UnlockRegionData region: " + regionName
1549: + " for user: " + //NoI18n
1550: getContext().getLoginUser());
1551: setCurrentState(FilesharingContext.STATE_UNLOCK);
1552:
1553: String loginUser = getContext().getLoginUser();
1554: unlockRegionData.setFileName(getName());
1555:
1556: Object pregion = setUnlockRegion(unlockRegionData);
1557:
1558: EditorLock editorLock = null;
1559: try {
1560: CollabRegion cregion = (CollabRegion) rCtx
1561: .getRegion(regionName);
1562: cregion.setValid(false);
1563:
1564: RegionInfo regionInfo = new RegionInfo(regionName,
1565: getName(), getFileGroupName(),
1566: RegionInfo.CHAROFFSET_RANGE, cregion
1567: .getBeginOffset(), cregion.getEndOffset(),
1568: 0);
1569: constructRegion(regionInfo, pregion);
1570:
1571: Content content = new Content();
1572: content.setEncoding(getEncoding());
1573: content.setDigest(getDigest());
1574:
1575: String text = null;
1576: synchronized (getDocumentLock()) {
1577: editorLock = lockEditor();
1578: Debug.log("CollabFileHandlerSupport",
1579: "CFHS, region begin: "
1580: + cregion.getBeginOffset());
1581: Debug.log("CollabFileHandlerSupport",
1582: "CFHS, region end: " + cregion.getEndOffset());
1583:
1584: text = cregion.getContent();
1585:
1586: // String encodedChange = encodeBase64(text.getBytes());
1587: // content.setData(encodedChange);
1588: // unlockRegionData.setContent(content);
1589:
1590: //add new lineregion
1591: int beginOffset = cregion.getBeginOffset();
1592: int endOffset = cregion.getEndOffset();
1593:
1594: List newLineRegionList = null;
1595:
1596: newLineRegionList = rCtx.doUpdateLineRegion(regionName,
1597: beginOffset, endOffset, unlockRegionData, null);
1598:
1599: //construct protocol line regions
1600: LineRegion[] pregions = setUnlockLineRegion(
1601: unlockRegionData, newLineRegionList.size());
1602:
1603: StringBuffer lineTexts = new StringBuffer();
1604: for (int i = 0; i < newLineRegionList.size(); i++) {
1605: CollabLineRegion cLineRegion = (CollabLineRegion) newLineRegionList
1606: .get(i);
1607: LineRegion pLineRegion = pregions[i];
1608: String lineRegionName = cLineRegion.getID();
1609: Debug.log("CollabFileHandlerSupport",
1610: "CollabFileHandlerSupport, New newLineRegionList"
1611: + //NoI18n
1612: lineRegionName);
1613: Debug.log("CollabFileHandlerSupport",
1614: "CFHS, line content"
1615: + cLineRegion.getContent());//NoI18n
1616: lineTexts.append(cLineRegion.getContent());
1617:
1618: int lineBeginOffset = cLineRegion.getBeginOffset();
1619: int lineEndOffset = cLineRegion.getEndOffset();
1620:
1621: Debug.log("CollabFileHandlerSupport",
1622: "CollabFileHandlerSupport, adding region: "
1623: + //NoI18n
1624: lineRegionName);
1625:
1626: RegionInfo lineRegionInfo = new RegionInfo(
1627: lineRegionName, getName(),
1628: getFileGroupName(),
1629: RegionInfo.CHAROFFSET_RANGE,
1630: lineBeginOffset, lineEndOffset, 0);
1631: constructRegion(lineRegionInfo, pLineRegion);
1632: unlockRegionData.setLineRegion(i, pLineRegion);
1633: }
1634:
1635: CollabRegion textRegion = (CollabRegion) rCtx
1636: .getRegion(regionName);
1637: textRegion.removeAnnotation();
1638:
1639: //persist line annotation
1640: String user = getContext().getLoginUser();
1641: String annotationMessage = NbBundle
1642: .getMessage(
1643: CollabFileHandlerSupport.class,
1644: "MSG_CollabFileHandlerSupport_HistoryAnnotation", // NOI18N
1645: getContext().getPrincipal(user)
1646: .getDisplayName());
1647:
1648: int style = -1; //history annotation
1649: addLineRegionAnnotation(
1650: (CollabLineRegion[]) newLineRegionList
1651: .toArray(new CollabLineRegion[0]),
1652: style, annotationMessage);
1653:
1654: //text=lineTexts.toString();
1655: //if(text.endsWith("\n"))
1656: // text=text.substring(0, text.length()-1);
1657: if (!((CollabRegionSupport) textRegion)
1658: .isEndOpenRegion()
1659: && text.endsWith("\n"))
1660: text = text.substring(0, text.length() - 1);
1661:
1662: Debug.log("CollabFileHandlerSupport",
1663: "CFHS, , construct unlock for "
1664: + //NoI18n
1665: "region: " + regionName
1666: + " with content : [" + text + "]"); //NoI18n
1667: String encodedChange = encodeBase64(text.getBytes());
1668: content.setData(encodedChange);
1669: unlockRegionData.setContent(content);
1670: }
1671: } catch (Throwable th) {
1672: Debug.log("CollabFileHandlerSupport", "CFHS, exception: "
1673: + th.getMessage());
1674: throw new CollabException(th);
1675: } finally {
1676: unlockEditor(editorLock);
1677: }
1678: }
1679:
1680: /**
1681: * constructs unlock-region-data Node
1682: *
1683: * @param unlockRegionData the intial unlock-region-data Node
1684: * @throws CollabException
1685: */
1686: public boolean constructUnlockRegionData(UnlockRegion unlockRegion)
1687: throws CollabException {
1688: if (isDisableUnlockTimer()) {
1689: return false;
1690: }
1691:
1692: if (inReceiveMessageUnlock) //return if fileHandler in received unlock
1693: {
1694: return false;
1695: }
1696:
1697: Vector userRegions = (Vector) rCtx.getUserRegion(getContext()
1698: .getLoginUser());
1699:
1700: if ((userRegions == null) || (userRegions.size() == 0)) {
1701: return false;
1702: }
1703:
1704: UnlockRegionData unlockRegionData = new UnlockRegionData();
1705: unlockRegion.addUnlockRegionData(unlockRegionData);
1706: unlockRegionData.setFileName(getName());
1707:
1708: int isReadyToUnlock1 = 0;
1709:
1710: for (int i = 0; i < userRegions.size(); i++) {
1711: final String regionName = (String) userRegions.get(i);
1712: Object tmpRegion = rCtx.getRegion(regionName);
1713:
1714: //skip line regions
1715: if (tmpRegion instanceof CollabLineRegion) {
1716: continue;
1717: }
1718:
1719: if (!(tmpRegion instanceof CollabRegion)) {
1720: continue;
1721: }
1722:
1723: //Hack, to set focus to users current file editorPane
1724: Debug.log("CollabFileHandlerSupport", "CFHS, request Focus"
1725: + "after createLock for user: "
1726: + getContext().getLoginUser());
1727: if (FilesharingCollablet.currentEditorPane != null) {
1728: FilesharingCollablet.currentEditorPane
1729: .requestFocusInWindow();
1730: }
1731:
1732: CollabRegion region = (CollabRegion) tmpRegion;
1733: Debug.log("CollabFileHandlerSupport",
1734: "CollabFileHandlerSupport, region valid:" + //NoI18n
1735: region.isValid());
1736:
1737: if (!region.isValid() || !region.isReadyToUnlock()) {
1738: continue;
1739: }
1740:
1741: region.setValid(false);
1742:
1743: TimerTask cleanupRegionTask = new TimerTask() {
1744: public void run() {
1745: try {
1746: removeRegion(getContext().getLoginUser(),
1747: regionName);
1748: } catch (CollabException ce) {
1749: Debug.log("CollabFileHandlerSupport", //NoI18n
1750: "CollabFileHandlerSupport, cleanup failed for: "
1751: + //NoI18n
1752: regionName);
1753: }
1754: }
1755: };
1756:
1757: getContext().schedule(cleanupRegionTask, 5000);
1758:
1759: try {
1760: constructUnlockRegionData(regionName, unlockRegionData);
1761: isReadyToUnlock1++;
1762: Debug.log("CollabFileHandlerSupport",
1763: "CFHS, after constructUnlockRegionData: "
1764: + isReadyToUnlock1); //NoI18n
1765: break;//process only one unlock region at a time
1766: } catch (Throwable th) {
1767: Debug.log("CollabFileHandlerSupport",
1768: "CFHS, exception: " + th.getMessage()); //NoI18n
1769: continue;
1770: }
1771:
1772: //isReadyToUnlock1++;
1773: }
1774:
1775: Debug.log("CollabFileHandlerSupport",
1776: "CFHS, isReadyToUnlock1: " + isReadyToUnlock1); //NoI18n
1777: if (isReadyToUnlock1 == 0) {
1778: return false;
1779: }
1780:
1781: setCurrentState(FilesharingContext.STATE_UNLOCK);
1782:
1783: return true;
1784: }
1785:
1786: /**
1787: * constructs send-file-data Node
1788: *
1789: * @param sendFile the send-file Node
1790: * @param syncOperation is send-file for sync file during user join
1791: * @return sendFileData the send-file-data Node
1792: * @throws CollabException
1793: */
1794: public SendFileData constructSendFileData(SendFile sendFile)
1795: throws CollabException {
1796: Debug.log("CollabFileHandlerSupport",
1797: "CollabFileHandlerSupport, construct SendFileData");
1798:
1799: if (!isValid()) {
1800: return null;
1801: }
1802:
1803: setCurrentState(FilesharingContext.STATE_SENDFILE);
1804:
1805: SendFileData sendFileData = new SendFileData();
1806: FileData fileData = new FileData();
1807: sendFileData.setFileData(fileData);
1808:
1809: fileData.setFileName(getName());
1810: fileData.setContentType(getContentType());
1811:
1812: //remove all non-lineregions if already exist
1813: rCtx.removeAllRegion(true);
1814:
1815: Content content = new Content();
1816: sendFileData.setContent(content);
1817:
1818: content.setEncoding(getEncoding());
1819: content.setDigest(getDigest());
1820:
1821: byte[] fileContent = null;
1822: Debug.log("CollabFileHandlerSupport",
1823: "CollabFileHandlerSupport, firstTimeSend: "
1824: + firstTimeSend); //NoI18n
1825: Debug.log("CollabFileHandlerSupport",
1826: "CollabFileHandlerSupport, isRetrieveFileContentOnly: "
1827: + isRetrieveFileContentOnly()); //NoI18n
1828:
1829: boolean doSendLineRegion = false;
1830:
1831: if (firstTimeSend || isRetrieveFileContentOnly()) {
1832: if (firstTimeSend) {
1833: doSendLineRegion = false;
1834:
1835: //saveDocument
1836: saveDocument();
1837:
1838: //find initial guarded sections once
1839: findInitialGuardedSections();
1840: } else if (isRetrieveFileContentOnly()) {
1841: doSendLineRegion = true;
1842: }
1843:
1844: firstTimeSend = false;
1845:
1846: //modify content of file if necessary before send
1847: fileContent = doProcessSendFileContent(getFileContentBytes());
1848: } else {
1849: //get current content
1850: fileContent = getContent().getBytes();
1851: doSendLineRegion = true;
1852: }
1853:
1854: String encodedFileContent = encodeBase64(fileContent);
1855: content.setData(encodedFileContent);
1856:
1857: //lock editor if opened
1858: EditorLock editorLock = lockEditor();
1859:
1860: try {
1861: //set line region user
1862: setLineRegionKey(getContext().getLoginUser()
1863: + "_LINEREGION_USER");
1864:
1865: if (!doSendLineRegion) {
1866: Debug
1867: .log("CollabFileHandlerSupport",
1868: "CollabFileHandlerSupport, Sending lineRegionFunction"); //NoI18n
1869:
1870: LineRegionFunction lineReginFunction = new LineRegionFunction();
1871: sendFileData.setLineRegionFunction(lineReginFunction);
1872: lineReginFunction
1873: .setFunctionName("simple_linear_function");
1874:
1875: int totalLineCount = getDocument()
1876: .getDefaultRootElement().getElementCount();
1877: Debug.log("CollabFileHandlerSupport",
1878: "CollabFileHandlerSupport, totalLineCount: "
1879: + totalLineCount); //NoI18n
1880:
1881: String[] args = new String[] { "RI",
1882: getContext().getLoginUser(),
1883: new Integer(totalLineCount).toString() };
1884: lineReginFunction.setArguments(args);
1885: sendFileData.setChooseLineRegionFunction(true);
1886:
1887: RegionInfo[] lineRegions = null;
1888:
1889: try {
1890: lineRegions = findLineRegion(sendFileData);
1891: Debug.log("CollabFileHandlerSupport",
1892: "CollabFileHandlerSupport, lineRegions size: "
1893: + lineRegions.length); //NoI18n
1894: } catch (Throwable th) {
1895: Debug.log("CollabFileHandlerSupport",
1896: "CollabFileHandlerSupport, exception: "
1897: + th.getMessage()); //NoI18n
1898: th.printStackTrace();
1899: }
1900:
1901: Debug.log("CollabFileHandlerSupport",
1902: "CFHS, SND create LineRegion: ");
1903: for (int i = 0; i < lineRegions.length; i++) {
1904: RegionInfo region = lineRegions[i];
1905: String regionName = region.getID();
1906: int beginOffset = region.getbegin();
1907: int endOffset = region.getend();
1908: try {
1909: Debug
1910: .log(
1911: "CollabFileHandlerSupport",
1912: regionName
1913: + ", begin: "
1914: + beginOffset
1915: + " end: "
1916: + endOffset
1917: + getDocument()
1918: .getText(
1919: beginOffset,
1920: endOffset
1921: - beginOffset)); //NoI18n
1922: Debug
1923: .log(
1924: "CollabFileHandlerSupport",
1925: " begin index: "
1926: + getDocument()
1927: .getDefaultRootElement()
1928: .getElementIndex(
1929: beginOffset)
1930: + " end index: "
1931: + getDocument()
1932: .getDefaultRootElement()
1933: .getElementIndex(
1934: endOffset)); //NoI18n
1935: } catch (CollabException ex) {
1936: ex.printStackTrace();
1937: } catch (BadLocationException ex) {
1938: ex.printStackTrace();
1939: } //NoI18n
1940:
1941: CollabRegion lineRegion = rCtx.createLineRegion(
1942: regionName, beginOffset, endOffset);
1943:
1944: if (lineRegion != null) {
1945: rCtx.addLineRegion(regionName, lineRegion);
1946: } else {
1947: continue;
1948: }
1949: }
1950:
1951: //invoke reset after 3000 sec
1952: resetAllLineRegionOffset(3000);
1953: } else {
1954: Debug
1955: .log("CollabFileHandlerSupport",
1956: "CollabFileHandlerSupport, Sending lineRegions"); //NoI18n
1957: printAllRegionInfo();
1958: Debug.log("CollabFileHandlerSupport",
1959: "CollabFileHandlerSupport, regionCount: " + //NoI18n
1960: rCtx.getLineRegionCount());
1961:
1962: int totalLineRegions = rCtx.getLineRegionCount();
1963: LineRegion[] pregions = (LineRegion[]) setSendFileLineRegion(
1964: sendFileData, totalLineRegions);
1965:
1966: for (int i = 0; i < totalLineRegions; i++) {
1967: CollabLineRegion region = (CollabLineRegion) rCtx
1968: .getLineRegion(i);
1969: Debug.log("CollabFileHandlerSupport",
1970: "CollabFileHandlerSupport, region: " + //NoI18n
1971: region.getID());
1972:
1973: RegionInfo regionInfo = new RegionInfo(region
1974: .getID(), getName(), getFileGroupName(),
1975: RegionInfo.CHAROFFSET_RANGE, region
1976: .getBeginOffset(), region
1977: .getEndOffset(), 0);
1978: LineRegion pregion = pregions[i];
1979: constructRegion(regionInfo, pregion);
1980: }
1981:
1982: sendFileData.setChooseLineRegionFunction(false);
1983: }
1984: } catch (CollabException ce) {
1985: unlockEditor(editorLock);
1986: Debug.log("CollabFileHandlerSupport",
1987: "CollabFileHandlerSupport, SendFile failed for file: "
1988: + getName()); //NoI18n
1989:
1990: return null;
1991: }
1992:
1993: unlockEditor(editorLock);
1994:
1995: return sendFileData;
1996: }
1997:
1998: /**
1999: * isRetrieveFileContentOnly
2000: *
2001: */
2002: public boolean isRetrieveFileContentOnly() {
2003: return this .isSendFileContentOnly;
2004: }
2005:
2006: /**
2007: * setRetrieveFileContentOnly
2008: *
2009: */
2010: public void setRetrieveFileContentOnly(boolean flag) {
2011: Debug.log("CollabFileHandlerSupport",
2012: "CollabFileHandlerSupport, setRetrieveFileContentOnly: "
2013: + flag); //NoI18n
2014: this .isSendFileContentOnly = flag;
2015: }
2016:
2017: /**
2018: * set sendfile-data with region
2019: *
2020: * @param sendFileRegionData the intial lock-region-data Node
2021: * @return region
2022: */
2023: protected Object setSendFileLineRegion(SendFileData sendFileData,
2024: int totalRegionCount) {
2025: List regionInfoList = new ArrayList();
2026:
2027: for (int i = 0; i < totalRegionCount; i++) {
2028: LineRegion lineRegion = new LineRegion();
2029: regionInfoList.add(lineRegion);
2030: }
2031:
2032: LineRegion[] lineRegions = (LineRegion[]) regionInfoList
2033: .toArray(new LineRegion[0]);
2034: sendFileData.setLineRegion(lineRegions);
2035:
2036: return lineRegions;
2037: }
2038:
2039: /**
2040: * get region
2041: *
2042: * @param lockRegionData the intial lock-region-data Node
2043: * @return region
2044: */
2045: protected RegionInfo[] getSendFileRegion(SendFileData sendFileData)
2046: throws CollabException {
2047: List regionInfoList = new ArrayList();
2048: LineRegion[] lineRegions = sendFileData.getLineRegion();
2049:
2050: if (lineRegions != null) {
2051: StyledDocument fileDocument = getDocument();
2052: int lineRegionCount = lineRegions.length;
2053:
2054: if (lineRegionCount > fileDocument.getDefaultRootElement()
2055: .getElementCount()) {
2056: lineRegionCount = fileDocument.getDefaultRootElement()
2057: .getElementCount();
2058: }
2059:
2060: for (int i = 0; i < lineRegionCount; i++) {
2061: LineRegion lineRegion = lineRegions[i];
2062:
2063: try {
2064: javax.swing.text.Element currentElement = fileDocument
2065: .getDefaultRootElement().getElement(i);
2066: int regionBegin = currentElement.getStartOffset();
2067: int regionEnd = currentElement.getEndOffset();
2068: RegionInfo regionInfo = new RegionInfo(lineRegion
2069: .getRegionName(), getName(),
2070: getFileGroupName(),
2071: RegionInfo.CHAROFFSET_RANGE, regionBegin,
2072: regionEnd, 0);
2073: regionInfoList.add(regionInfo);
2074: } catch (Throwable th) {
2075: break;
2076: }
2077: }
2078:
2079: return (RegionInfo[]) regionInfoList
2080: .toArray(new RegionInfo[0]);
2081: }
2082:
2083: return null;
2084: }
2085:
2086: /**
2087: * doProcessSendFileContent
2088: *
2089: * @param content
2090: * @return fileContent
2091: * @throws CollabException
2092: */
2093: public byte[] doProcessSendFileContent(byte[] content)
2094: throws CollabException {
2095: String fileContent = new String(content);
2096:
2097: //add 3 additional lines
2098: //fileContent+=CollabFileHandler.EMPTY_CONTENT;//NoI18n
2099: byte[] returnContent = fileContent.getBytes();
2100:
2101: inReceiveSendFile = true;
2102:
2103: //updateFileObject(returnContent);
2104: inReceiveSendFile = false;
2105:
2106: return returnContent;
2107: }
2108:
2109: /**
2110: * create a CollabFileHandler#simpleSection
2111: * @param beginOffset
2112: * @param endOffset
2113: * @param regionName
2114: * @throws CollabException
2115: * @return CollabFileHandler#simpleSection
2116: */
2117: public CollabRegion createSimpleSection(int beginOffset,
2118: int endOffset, String regionName) throws CollabException {
2119: if (rCtx.getRegion().size() == 0) {
2120: NbDocument.unmarkGuarded(getDocument(), 0, getDocument()
2121: .getLength());
2122: }
2123:
2124: //create guarded region
2125: return createRegion(regionName, beginOffset, endOffset, false,
2126: true);
2127: }
2128:
2129: /**
2130: * isRegionOverlap
2131: *
2132: * return true if can region exists or there is a overlap found
2133: *
2134: * @param beginOffset
2135: * @param endOffset
2136: * @throws CollabException
2137: * @return
2138: */
2139: public boolean isRegionOverlap(CollabLineRegion beginLine,
2140: CollabLineRegion endLine) throws CollabException {
2141: if (beginLine == null || endLine == null)
2142: return false;
2143: Debug.log("CollabFileHandlerSupport",
2144: "CFHS::isRegionOverlap:: " + "beginLine: "
2145: + beginLine.getID() + " isAssigned: "
2146: + beginLine.isAssigned());
2147: Debug.log("CollabFileHandlerSupport",
2148: "CFHS::isRegionOverlap:: " + "endLine: "
2149: + endLine.getID() + " isAssigned: "
2150: + endLine.isAssigned());
2151: return (beginLine.isAssigned() || endLine.isAssigned());
2152: }
2153:
2154: /**
2155: * return true if can create region
2156: *
2157: * @param beginOffset
2158: * @param endOffset
2159: * @throws CollabException
2160: * @return
2161: */
2162: public boolean testCreateRegionLineBounds(int beginLine, int endLine)
2163: throws CollabException {
2164: StyledDocument fileDocument = getDocument();
2165: int beginOffset = fileDocument.getDefaultRootElement()
2166: .getElement(beginLine).getStartOffset() - 1;
2167:
2168: if (beginOffset < 0) {
2169: beginOffset = 0;
2170: }
2171:
2172: int endOffset = fileDocument.getDefaultRootElement()
2173: .getElement(endLine).getEndOffset();
2174:
2175: return testCreateRegion(beginOffset, endOffset);
2176: }
2177:
2178: /**
2179: * return true if can create region
2180: *
2181: * @param beginOffset
2182: * @param endOffset
2183: * @throws CollabException
2184: * @return
2185: */
2186: public boolean testCreateRegion(int beginOffset, int endOffset)
2187: throws CollabException {
2188: int length = endOffset - beginOffset;
2189: CollabRegion region = rCtx.getContainingRegion(beginOffset,
2190: length, true);
2191:
2192: if ((region != null) && !(region instanceof CollabLineRegion)) {
2193: return false;
2194: }
2195:
2196: return true;
2197: }
2198:
2199: ////////////////////////////////////////////////////////////////////////////
2200: // Document methods
2201: ////////////////////////////////////////////////////////////////////////////
2202:
2203: /**
2204: * get the file document content of a region
2205: *
2206: * @param regionName the regionName
2207: * @return document Content content
2208: * @throws CollabException
2209: */
2210: public String getContent(String regionName) throws CollabException {
2211: StyledDocument fileDocument = getDocument();
2212: CollabRegion region = (CollabRegion) rCtx.getRegion(regionName);
2213:
2214: return region.getContent();
2215: }
2216:
2217: /**
2218: * get the file document content
2219: *
2220: * @return document Content content
2221: * @throws CollabException
2222: */
2223: public String getContent() throws CollabException {
2224: FileObject fileOject = getFileObject();
2225:
2226: try {
2227: StyledDocument fileDocument = getDocument();
2228:
2229: return fileDocument.getText(0, fileDocument.getLength());
2230: } catch (javax.swing.text.BadLocationException ex) {
2231: //throw new CollabException(ex);
2232: Debug.logDebugException("CollabFileHandlerSupport, " + //NoI18n
2233: "getContent failed", ex, true); //NoI18n
2234: }
2235:
2236: return "";
2237: }
2238:
2239: /**
2240: * getter for contentType
2241: *
2242: * @return contentType
2243: */
2244: public String getContentType() {
2245: return contentType;
2246: }
2247:
2248: /**
2249: * setter for contentType
2250: *
2251: * @param contentType
2252: */
2253: public void setContentType(String contentType) {
2254: this .contentType = contentType;
2255: }
2256:
2257: ////////////////////////////////////////////////////////////////////////////
2258: // Management methods
2259: ////////////////////////////////////////////////////////////////////////////
2260:
2261: /**
2262: * test if the file changed
2263: *
2264: * @return true/false true if file changes
2265: */
2266: public boolean isChanged() throws CollabException {
2267: //logic to register doc listener if not present
2268: if (!fileChanged) {
2269: try {
2270: boolean isDocChanged = isChangedDocument(getDocument());
2271:
2272: if (isDocChanged) {
2273: //register doc listener if doc length changed but there is no indication of change
2274: // -commenting out
2275: //doc listener is now added from TC listener
2276: //registerDocumentListener();
2277: }
2278: } catch (CollabException ce) {
2279: if (ce.getCause() instanceof org.openide.loaders.DataObjectNotFoundException) {
2280: //ignore, this exception
2281: } else if (ce.getCause() instanceof java.io.SyncFailedException) {
2282: //ignore, this exception
2283: } else {
2284: throw ce;
2285: }
2286: }
2287: }
2288:
2289: return fileChanged;
2290: }
2291:
2292: /**
2293: * setter for filechanged
2294: *
2295: * @param status
2296: */
2297: public void updateStatusChanged(boolean status) {
2298: fileChanged = status;
2299: }
2300:
2301: /**
2302: * test if the file changed
2303: *
2304: * @return true/false true if file changes
2305: */
2306: public boolean isChangedDocument(StyledDocument doc) {
2307: if (doc == null) {
2308: return false;
2309: }
2310:
2311: int docLength = doc.getLength();
2312:
2313: if (docLength != previousDocLength) {
2314: previousDocLength = docLength;
2315:
2316: return true;
2317: }
2318:
2319: return false;
2320: }
2321:
2322: /**
2323: * removeAllLineRegionAnnotation
2324: *
2325: * @param lineRegions
2326: */
2327: public void removeAllLineRegionAnnotation() throws CollabException {
2328: int totalLineRegions = rCtx.getLineRegionCount();
2329:
2330: for (int i = 0; i < totalLineRegions; i++) {
2331: CollabLineRegion lineRegion = (CollabLineRegion) rCtx
2332: .getLineRegion(i);
2333: Debug.log("CollabFileHandlerSupport",
2334: "CollabFileHandlerSupport, "
2335: + //NoI18n
2336: "remove annotation for: "
2337: + lineRegion.getID()); //NoI18n
2338:
2339: if (lineRegion != null) {
2340: lineRegion.removeAnnotation();
2341: }
2342: }
2343: }
2344:
2345: /**
2346: * skip insertUpdate
2347: *
2348: * @param offset
2349: * @return true if skip
2350: */
2351: public boolean skipInsertUpdate(int offset) {
2352: Debug.log("CollabFileHandlerSupport",
2353: "CollabFileHandlerSupport, "
2354: + //NoI18n
2355: "skipInsertUpdate for user: "
2356: + getContext().getLoginUser()); //NoI18n
2357: Debug.log("CollabFileHandlerSupport",
2358: "CollabFileHandlerSupport, " + "skipUpdateAlways: "
2359: + skipUpdateAlways); //NoI18n
2360: Debug.log("CollabFileHandlerSupport",
2361: "CollabFileHandlerSupport, " + "skipUpdate: "
2362: + skipUpdate); //NoI18n
2363: Debug.log("CollabFileHandlerSupport",
2364: "CollabFileHandlerSupport, " + "inPauseState: "
2365: + inPauseState); //NoI18n
2366: Debug.log("CollabFileHandlerSupport",
2367: "CollabFileHandlerSupport, " + "inReceiveSendFile: "
2368: + inReceiveSendFile); //NoI18n
2369:
2370: //skip updateText related insert
2371: if (skipUpdateAlways //skip always
2372: || skipUpdate //skip if set to true
2373: || inPauseState //skip if received Pause
2374: || inReceiveSendFile //skip if in inReceiveSendFile
2375: ) {
2376: return true;
2377: }
2378:
2379: return false;
2380: }
2381:
2382: /**
2383: * skip removeUpdate
2384: *
2385: * @param offset
2386: * @param length
2387: * @return true if skip
2388: */
2389: public boolean skipRemoveUpdate(int offset, int length) {
2390: Debug.log("CollabFileHandlerSupport",
2391: "CollabFileHandlerSupport, "
2392: + //NoI18n
2393: "skipRemoveUpdate for user: "
2394: + getContext().getLoginUser()); //NoI18n
2395: Debug.log("CollabFileHandlerSupport",
2396: "CollabFileHandlerSupport, " + "skipUpdateAlways: "
2397: + skipUpdateAlways); //NoI18n
2398: Debug.log("CollabFileHandlerSupport",
2399: "CollabFileHandlerSupport, " + "skipUpdate: "
2400: + skipUpdate); //NoI18n
2401: Debug.log("CollabFileHandlerSupport",
2402: "CollabFileHandlerSupport, " + "inPauseState: "
2403: + inPauseState); //NoI18n
2404: Debug.log("CollabFileHandlerSupport",
2405: "CollabFileHandlerSupport, " + "inReceiveSendFile: "
2406: + inReceiveSendFile); //NoI18n
2407:
2408: //skip updateText related remove
2409: if (skipUpdateAlways //skip always
2410: || skipUpdate //skip if set to true
2411: || inPauseState //skip if received Pause
2412: || inReceiveSendFile //skip if in inReceiveSendFile
2413: ) {
2414: return true;
2415: }
2416:
2417: return false;
2418: }
2419:
2420: /**
2421: * skip Insert or Remove if set to true
2422: *
2423: * @param status if true skip insert/remove
2424: * @throws CollabException
2425: */
2426: public synchronized void setSkipUpdate(boolean skipUpdate) {
2427: Debug.log("CollabFileHandlerSupport", //NoI18n
2428: "CollabFileHandlerSupport, setSkipUpdate: "
2429: + //NoI18n
2430: skipUpdate + " for user: "
2431: + getContext().getLoginUser());
2432: this .skipUpdate = skipUpdate;
2433: }
2434:
2435: /**
2436: * setValid
2437: *
2438: * @param status if false handler is invalid
2439: */
2440: public void setValid(boolean valid) {
2441: this .isValid = valid;
2442: }
2443:
2444: /**
2445: * getValid
2446: *
2447: * @return status if false handler is invalid
2448: */
2449: public boolean isValid() {
2450: return this .isValid;
2451: }
2452:
2453: /**
2454: * setLineRegionKey
2455: *
2456: * @param key
2457: * @throws CollabException
2458: */
2459: public void setLineRegionKey(String key) {
2460: this .lineRegionKey = key;
2461: }
2462:
2463: /**
2464: * getLineRegionKey
2465: *
2466: * @return key
2467: */
2468: public String getLineRegionKey() {
2469: return this .lineRegionKey;
2470: }
2471:
2472: /**
2473: * create a New Region, sends a lock message
2474: *
2475: * @param beginLine
2476: * @param endLine
2477: * @param endOffsetCorrection
2478: * @param includeMarginLines
2479: * @throws CollabException
2480: */
2481: public void createNewRegion(int beginLine, int endLine,
2482: int endOffsetCorrection, boolean includeMarginLines)
2483: throws CollabException {
2484: //Create a new region offset:currentline-1 to curentline +1
2485: String regionName = getContext().createUniqueRegionName(
2486: getName(), regionCount++);
2487:
2488: EditorLock editorLock = null;
2489: try {
2490: StyledDocument fileDocument = fileDocument = getDocument();
2491: synchronized (getDocumentLock()) {
2492: editorLock = lockEditor();
2493:
2494: /* refactored into findUnAssignedLines()
2495: if (includeMarginLines) {
2496: if (beginLine > 0) {
2497: beginLine -= 1;
2498: }
2499:
2500: if (endLine < (fileDocument.getDefaultRootElement().getElementCount() - 2)) {
2501: endLine += 2;
2502: } else if (endLine < (fileDocument.getDefaultRootElement().getElementCount() - 1)) {
2503: endLine += 1;
2504: }
2505:
2506: if (endLine >= fileDocument.getDefaultRootElement().getElementCount()) {
2507: endLine = fileDocument.getDefaultRootElement().getElementCount() - 1;
2508: }
2509:
2510: Debug.log(
2511: "CollabFileHandlerSupport", //NoI18n
2512: "CollabFileHandlerSupport, " + "includeMarginLines beginLine: " + beginLine + " endLine: " + endLine
2513: );
2514: }
2515: //adjust beginLine to avoid delete first line
2516: if(beginLine==1) beginLine=0;
2517:
2518: int beginOffset = fileDocument.getDefaultRootElement().getElement(beginLine).getStartOffset() - 1;
2519:
2520: if (beginOffset < 0) {
2521: beginOffset = 0;
2522: }
2523:
2524: int endOffset = fileDocument.getDefaultRootElement().getElement(endLine).getEndOffset();
2525:
2526: Vector lineRegions = new Vector(10);
2527: boolean foundFirstMatch = false;
2528: CollabLineRegion endLineNeighbour=null;
2529: CollabLineRegion beginLineNeighbour=null;
2530: Debug.log("CollabFileHandlerSupport","CFHS, Check lines are between:" +
2531: " beginOffset: " + beginOffset + " endOffset: " + endOffset); //NoI18n
2532:
2533: for (int i = beginLine; i < rCtx.getLineRegionCount(); i++) {
2534: CollabLineRegion lineRegion = rCtx.getLineRegion(i);
2535:
2536: if (lineRegion == null) {
2537: continue;
2538: }
2539:
2540: int lineBeginOffset = lineRegion.getBeginOffset();
2541: Debug.log("CollabFileHandlerSupport","CFHS, "+ "line ["+i+"]: "+
2542: lineRegion.getID()+" isAssigned(): " + lineRegion.isAssigned()+
2543: " lineBeginOffset: "+lineBeginOffset); //NoI18n
2544: if(!lineRegion.isAssigned() && lineBeginOffset>=beginOffset && lineBeginOffset<endOffset) {
2545: foundFirstMatch=true;
2546: Debug.log("CollabFileHandlerSupport","CFHS, Add line: " + //NoI18n
2547: lineRegion.getID());
2548: lineRegions.add(lineRegion);
2549: } else {
2550: if (foundFirstMatch) { //reached end of match
2551: endLineNeighbour=lineRegion;
2552: break;
2553: }
2554: else
2555: beginLineNeighbour=lineRegion;
2556: }
2557: }*/
2558:
2559: Vector lineRegions = findUnAssignedLines(beginLine,
2560: endLine, endOffsetCorrection,
2561: includeMarginLines);
2562: if (lineRegions.size() == 0) {
2563: Debug
2564: .log(
2565: "CollabFileHandlerSupport",
2566: "CFHS,"
2567: + "Cannot create lock, no line regions match, so try to "
2568: + "create regions from "
2569: + beginLine + " to: "
2570: + endLine);
2571: return;
2572: }
2573: CollabLineRegion beginLineNeighbour = (CollabLineRegion) lineRegions
2574: .firstElement();
2575: lineRegions.removeElement(beginLineNeighbour);
2576: CollabLineRegion endLineNeighbour = (CollabLineRegion) lineRegions
2577: .lastElement();
2578: lineRegions.removeElement(endLineNeighbour);
2579:
2580: /*refactored to findNewRegionBeginOffset() and findNewRegionEndOffset()
2581: //Calculate offset based on unassigned lineregions only
2582: if(lineRegions==null || lineRegions.size()==0) return;
2583: CollabLineRegion beginLineRegion=(CollabLineRegion)lineRegions.get(0);
2584: if(beginLineRegion==null) return;
2585: //beginOffset = fileDocument.getDefaultRootElement().
2586: // getElement(beginLineRegion.getLineIndex()).getStartOffset()-1;
2587: beginOffset=beginLineRegion.getBeginOffset();
2588: if(beginOffset!=0 && beginOffset+1==beginLineRegion.getBeginOffset())//correct beginoffset
2589: beginOffset = beginLineRegion.getBeginOffset();
2590: if(beginOffset<0) beginOffset=0;
2591: CollabLineRegion endLineRegion=
2592: (CollabLineRegion)lineRegions.get(lineRegions.size()-1);
2593: if(endLineRegion==null) return;
2594: //endOffset = fileDocument.getDefaultRootElement().
2595: // getElement(endLineRegion.getLineIndex()).getEndOffset();
2596: if(endOffset<endLineRegion.getEndOffset())
2597: endOffset = endLineRegion.getEndOffset();
2598:
2599: //adjust endoffset for new inserted lines or delete first line
2600: if(endLineNeighbour!=null && (endOffset+1<endLineNeighbour.getBeginOffset() ||
2601: endOffset>=endLineNeighbour.getBeginOffset())) {
2602: Debug.log("CollabFileHandlerSupport","CFHS, elR: " +
2603: endLineRegion.getID()+" end: "+ endOffset);//NoI18n
2604: Debug.log("CollabFileHandlerSupport","CFHS, elN: "+endLineNeighbour.getID()+
2605: " begin: "+endLineNeighbour.getBeginOffset());//NoI18n
2606: endOffset=endLineNeighbour.getBeginOffset()-1;
2607: if(endOffset<0) endOffset=0;
2608: Debug.log("CollabFileHandlerSupport","CFHS, adjusted endOffset: "+
2609: endOffset);//NoI18n
2610: }
2611:
2612: int docLength=fileDocument.getLength();
2613: if(endOffset>docLength) endOffset=docLength;*/
2614:
2615: Debug
2616: .log(
2617: "CollabFileHandlerSupport",
2618: "CFHS, "
2619: + "create new region beginLineNeighbour end: "
2620: + (beginLineNeighbour != null ? beginLineNeighbour
2621: .getEndOffset()
2622: : -1)
2623: + " endLineNeighbour begin: "
2624: + (endLineNeighbour != null ? endLineNeighbour
2625: .getBeginOffset()
2626: : -1));//NoI18n
2627: Debug.log("CollabFileHandlerSupport",
2628: "CFHS, lines size: " + lineRegions.size()); //NoI18n
2629:
2630: int beginOffset = findNewRegionBeginOffset(lineRegions,
2631: beginLineNeighbour);
2632: if (beginOffset == -1)
2633: return;
2634:
2635: int endOffset = findNewRegionEndOffset(lineRegions,
2636: endLineNeighbour);
2637: if (endOffset == -1)
2638: return;
2639:
2640: //Create new region
2641: Debug.log("CollabFileHandlerSupport", "CFHS, "
2642: + "create new region beginOffset: "
2643: + beginOffset + " endOffset: " + endOffset);//NoI18n
2644: //Debug.log("CollabFileHandlerSupport","CFHS, lines: " + lineRegions); //NoI18n
2645: if (endOffset == 0)
2646: return;
2647: CollabRegion textRegion = createRegion(regionName,
2648: beginOffset, endOffset, false);
2649: if (textRegion == null)
2650: return;
2651:
2652: textRegion.setValid(false);
2653: rCtx.addRegion(getContext().getLoginUser(), regionName,
2654: textRegion);
2655:
2656: //Set parent
2657: for (int i = 0; i < lineRegions.size(); i++) {
2658: CollabLineRegion liner = (CollabLineRegion) lineRegions
2659: .get(i);
2660: if (liner != null) {
2661: Debug.log("CollabFileHandlerSupport",
2662: "CFHS, setAssigned " + "true for: "
2663: + liner.getID()); //NoI18n
2664: liner.setAssigned(textRegion, true);
2665: }
2666: }
2667:
2668: //add annotation
2669: String user = getContext().getLoginUser();
2670: String annotationMessage = NbBundle
2671: .getMessage(
2672: CollabFileHandlerSupport.class,
2673: "MSG_CollabFileHandlerSupport_EditingAnnotation", // NOI18N
2674: getContext().getPrincipal(user)
2675: .getDisplayName());
2676: int style = getUserStyle(user);
2677: List tmpList = new ArrayList();
2678: tmpList.addAll(lineRegions);
2679: addLineRegionAnnotation((CollabLineRegion[]) tmpList
2680: .toArray(new CollabLineRegion[0]), style,
2681: annotationMessage);
2682:
2683: if (textRegion.getContent().endsWith("\n"))
2684: ((CollabRegionSupport) textRegion)
2685: .setEndOpenRegion(true);
2686: Debug.log("CollabFileHandlerSupport",
2687: "CollabFileHandlerSupport, createLock text : ["
2688: + //NoI18n
2689: textRegion.getContent() + "]"); //NoI18n
2690:
2691: RegionInfo regionInfo = new RegionInfo(textRegion
2692: .getID(), getName(), getFileGroupName(),
2693: RegionInfo.CHAROFFSET_RANGE, textRegion
2694: .getBeginOffset(), textRegion
2695: .getEndOffset(), endOffsetCorrection,
2696: lineRegions);
2697:
2698: LockRegionEvent lockRegionEvent = new LockRegionEvent(
2699: new LockRegionContext(LockRegionEvent
2700: .getEventID(), getFileHandler(),
2701: regionInfo));
2702: getContext().getChannelEventNotifier().notify(
2703: lockRegionEvent);
2704:
2705: textRegion.updateStatusChanged(true);
2706: currentUpdatedRegion = ((CollabRegion) textRegion);
2707: }
2708: } catch (CollabException ce) {
2709: ce.printStackTrace(Debug.out);
2710: } finally {
2711: unlockEditor(editorLock);
2712:
2713: //Hack - Now save the editorpane that had the users focus
2714: registerInputListener();
2715: /*
2716: SwingUtilities.invokeLater( new Runnable() {
2717: public void run() {
2718: try {
2719: TopComponent tc=findTopComponent();
2720: if(tc!=null) tc.requestActive();
2721: } catch(Throwable th) {
2722: Debug.logDebugException("CFHS, " +//NoI18n
2723: "cannot request Active after createnewregion", //NoI18n
2724: th, true);
2725: }
2726: }
2727: });
2728: */
2729: }
2730: }
2731:
2732: private Vector findUnAssignedLines(int beginLine, int endLine,
2733: int endOffsetCorrection, boolean includeMarginLines)
2734: throws CollabException {
2735: CollabLineRegion beginLineNeighbour = null;
2736: CollabLineRegion endLineNeighbour = null;
2737: StyledDocument fileDocument = getDocument();
2738: if (includeMarginLines) {
2739: if (beginLine > 0) {
2740: beginLine -= 1;
2741: }
2742:
2743: if (endLine < (fileDocument.getDefaultRootElement()
2744: .getElementCount() - 2)) {
2745: endLine += 2;
2746: } else if (endLine < (fileDocument.getDefaultRootElement()
2747: .getElementCount() - 1)) {
2748: endLine += 1;
2749: }
2750:
2751: if (endLine >= fileDocument.getDefaultRootElement()
2752: .getElementCount()) {
2753: endLine = fileDocument.getDefaultRootElement()
2754: .getElementCount() - 1;
2755: }
2756:
2757: Debug.log("CollabFileHandlerSupport", //NoI18n
2758: "CollabFileHandlerSupport, "
2759: + "includeMarginLines beginLine: "
2760: + beginLine + " endLine: " + endLine);
2761: }
2762: //adjust beginLine to avoid delete first line
2763: if (beginLine == 1)
2764: beginLine = 0;
2765:
2766: int beginOffset = fileDocument.getDefaultRootElement()
2767: .getElement(beginLine).getStartOffset() - 1;
2768:
2769: if (beginOffset < 0) {
2770: beginOffset = 0;
2771: }
2772:
2773: int endOffset = fileDocument.getDefaultRootElement()
2774: .getElement(endLine).getEndOffset();
2775:
2776: Vector lineRegions = new Vector(10);
2777: boolean foundFirstMatch = false;
2778: Debug.log("CollabFileHandlerSupport",
2779: "CFHS, Check lines are between:" + " beginOffset: "
2780: + beginOffset + " endOffset: " + endOffset); //NoI18n
2781:
2782: if (beginLine > 0)
2783: beginLineNeighbour = rCtx.getLineRegion(beginLine - 1);
2784:
2785: for (int i = beginLine; i < rCtx.getLineRegionCount(); i++) {
2786: CollabLineRegion lineRegion = rCtx.getLineRegion(i);
2787:
2788: if (lineRegion == null) {
2789: continue;
2790: }
2791:
2792: int lineBeginOffset = lineRegion.getBeginOffset();
2793: Debug.log("CollabFileHandlerSupport", "CFHS, " + "line ["
2794: + i + "]: " + lineRegion.getID()
2795: + " isAssigned(): " + lineRegion.isAssigned()
2796: + " lineBeginOffset: " + lineBeginOffset); //NoI18n
2797: if (!lineRegion.isAssigned()
2798: && lineBeginOffset >= beginOffset
2799: && lineBeginOffset < endOffset) {
2800: foundFirstMatch = true;
2801: Debug.log("CollabFileHandlerSupport",
2802: "CFHS, Add line: " + //NoI18n
2803: lineRegion.getID());
2804: lineRegions.add(lineRegion);
2805: } else {
2806: if (foundFirstMatch) { //reached end of match
2807: endLineNeighbour = lineRegion;
2808: break;
2809: } else
2810: beginLineNeighbour = lineRegion;
2811: }
2812: }
2813: //add the neighbouring begin and end lines
2814: lineRegions.insertElementAt(beginLineNeighbour, 0);
2815: lineRegions.add(endLineNeighbour);
2816:
2817: return lineRegions;
2818: }
2819:
2820: private int findNewRegionBeginOffset(final Vector lineRegions,
2821: final CollabLineRegion beginLineNeighbour) {
2822: int beginOffset = 0;
2823:
2824: if (lineRegions == null || lineRegions.size() == 0)
2825: return -1;
2826:
2827: if (beginLineNeighbour != null) {
2828: Debug.log("CollabFileHandlerSupport", "CFHS, blN: "
2829: + beginLineNeighbour.getID() + " end: "
2830: + beginLineNeighbour.getEndOffset());//NoI18n
2831: beginOffset = beginLineNeighbour.getEndOffset();
2832: }
2833: /*CollabLineRegion beginLineRegion=(CollabLineRegion)lineRegions.get(0);
2834: if(beginLineRegion==null) return -1;
2835: beginOffset=beginLineRegion.getBeginOffset();
2836: if(beginOffset!=0 && beginOffset+1==beginLineRegion.getBeginOffset())//correct beginoffset
2837: beginOffset = beginLineRegion.getBeginOffset();
2838:
2839: if(beginOffset<0) beginOffset=0;*/
2840:
2841: if (beginOffset < 0)
2842: beginOffset = 0;
2843:
2844: return beginOffset;
2845: }
2846:
2847: private int findNewRegionEndOffset(final Vector lineRegions,
2848: final CollabLineRegion endLineNeighbour)
2849: throws CollabException {
2850: int docLength = getDocument().getLength();
2851: int endOffset = docLength;
2852:
2853: if (lineRegions == null || lineRegions.size() == 0)
2854: return -1;
2855:
2856: if (endLineNeighbour != null) {
2857: Debug.log("CollabFileHandlerSupport", "CFHS, elN: "
2858: + endLineNeighbour.getID() + " begin: "
2859: + endLineNeighbour.getBeginOffset());//NoI18n
2860: endOffset = endLineNeighbour.getBeginOffset() - 1;
2861: }
2862: /*CollabLineRegion endLineRegion=
2863: (CollabLineRegion)lineRegions.get(lineRegions.size()-1);
2864: if(endLineRegion==null) return -1;
2865: if(endOffset<endLineRegion.getEndOffset())
2866: endOffset = endLineRegion.getEndOffset();
2867:
2868: //adjust endoffset for new inserted lines or delete first line
2869: if(endLineNeighbour!=null && (endOffset+1<endLineNeighbour.getBeginOffset() ||
2870: endOffset>=endLineNeighbour.getBeginOffset())) {
2871: Debug.log("CollabFileHandlerSupport","CFHS, elR: " +
2872: endLineRegion.getID()+" end: "+ endOffset);//NoI18n
2873: Debug.log("CollabFileHandlerSupport","CFHS, elN: "+endLineNeighbour.getID()+
2874: " begin: "+endLineNeighbour.getBeginOffset());//NoI18n
2875: endOffset=endLineNeighbour.getBeginOffset()-1;
2876: if(endOffset<0) endOffset=0;
2877: Debug.log("CollabFileHandlerSupport","CFHS, adjusted endOffset: "+
2878: endOffset);//NoI18n
2879: }*/
2880:
2881: if (endOffset > docLength)
2882: endOffset = docLength;
2883:
2884: return endOffset;
2885: }
2886:
2887: /**
2888: * creates a CollabRegion, a super-class for all regions
2889: *
2890: * @param regionName the regionName
2891: * @param beginOffset the beginOffset
2892: * @param endOffset the endOffset
2893: * @throws CollabException
2894: * @return
2895: */
2896: public CollabRegion createRegion(String regionName,
2897: int beginOffset, int endOffset) throws CollabException {
2898: return createRegion(regionName, beginOffset, endOffset, true,
2899: false);
2900: }
2901:
2902: /**
2903: * creates a CollabRegion, a super-class for all regions
2904: *
2905: * @param regionName the regionName
2906: * @param beginOffset the beginOffset
2907: * @param endOffset the endOffset
2908: * @param testOverlap
2909: * @throws CollabException
2910: * @return
2911: */
2912: public CollabRegion createRegion(String regionName,
2913: int beginOffset, int endOffset, boolean testOverlap)
2914: throws CollabException {
2915: return createRegion(regionName, beginOffset, endOffset,
2916: testOverlap, false);
2917: }
2918:
2919: /**
2920: * creates a CollabRegion, a super-class for all regions
2921: *
2922: * @param testOverlap
2923: * @param regionName the regionName
2924: * @param beginOffset the beginOffset
2925: * @param endOffset the endOffset
2926: * @param testOverlap
2927: * @param guarded
2928: * @throws CollabException
2929: * @return
2930: */
2931: public abstract CollabRegion createRegion(String regionName,
2932: int beginOffset, int endOffset, boolean testOverlap,
2933: boolean guarded) throws CollabException;
2934:
2935: /**
2936: * test if the region exist in the repository
2937: *
2938: * @param user
2939: * @param offset
2940: * @param length
2941: * @param length of adjacency of change to this region
2942: * @return true if region exist
2943: */
2944: public boolean isUserRegionExist(String user, int offset,
2945: int length, int adjacency) throws CollabException {
2946: return rCtx.isUserRegionExist(user, offset, length, adjacency);
2947: }
2948:
2949: /**
2950: * test if the region exist in the repository
2951: *
2952: * @param user
2953: * @param offset
2954: * @param length
2955: * @param length of adjacency of change to this region
2956: * @return true if region exist
2957: */
2958: public CollabRegion getContainingUserRegion(String user,
2959: int offset, int length, int adjacency)
2960: throws CollabException {
2961: return rCtx.getContainingUserRegion(user, offset, length,
2962: adjacency);
2963: }
2964:
2965: /**
2966: * test if the region exist in the repository
2967: *
2968: * @param offset
2969: * @param length
2970: * @param length of adjacency of change to this region
2971: * @return true if region exist
2972: */
2973: public boolean regionExist(int offset, int length, int adjacency)
2974: throws CollabException {
2975: return rCtx.regionExist(offset, length, adjacency);
2976: }
2977:
2978: /**
2979: * unlock all user regions(ready for removal)
2980: *
2981: */
2982: public void unlockAllUserRegions() {
2983: rCtx.unlockAllUserRegions();
2984: }
2985:
2986: /**
2987: * get a region from the repository
2988: *
2989: * @param regionName the regionName
2990: * @return region CollabRegion
2991: */
2992: public CollabRegion getRegion(String regionName) {
2993: return rCtx.getRegion(regionName);
2994: }
2995:
2996: /**
2997: * return a region that contains the offset
2998: *
2999: * @param user
3000: * @param beginOffset
3001: * @param length
3002: * @param applyCorrection
3003: * @return
3004: */
3005: protected CollabRegion getContainingRegion(int offset, int length,
3006: boolean applyCorrection) {
3007: return rCtx
3008: .getContainingRegion(offset, length, applyCorrection);
3009: }
3010:
3011: /**
3012: * get a region from the repository
3013: *
3014: * @param regionName the regionName
3015: * @return CollabLineRegion
3016: */
3017: public CollabLineRegion getLineRegion(String regionName) {
3018: return rCtx.getLineRegion(regionName);
3019: }
3020:
3021: /**
3022: * get a region from the repository
3023: *
3024: * @param regionIndex
3025: * @return CollabLineRegion
3026: */
3027: public CollabLineRegion getLineRegion(int regionIndex) {
3028: return rCtx.getLineRegion(regionIndex);
3029: }
3030:
3031: /**
3032: * doUpdateRegion
3033: *
3034: * @param messageOriginator the sender of this message
3035: * @param sect
3036: * @param text
3037: * @throws CollabException
3038: */
3039: public boolean doUpdateRegion(String messageOriginator,
3040: CollabRegion sect, String text) throws CollabException {
3041: return rCtx.doUpdateRegion(messageOriginator, sect, text);
3042: }
3043:
3044: /**
3045: * remove a guarded section
3046: *
3047: * @param sect
3048: * @throws CollabException
3049: */
3050: public void removeSection(CollabRegion region)
3051: throws CollabException {
3052: if (region.isGuarded()) {
3053: ((CollabRegionSupport.SimpleSection) region.getGuard())
3054: .removeSection();
3055:
3056: if (rCtx.getRegion().size() == 1) {
3057: NbDocument.unmarkGuarded(getDocument(), 0,
3058: getDocument().getLength());
3059: }
3060: }
3061: }
3062:
3063: /**
3064: * update file status
3065: *
3066: * @param offset
3067: * @param length
3068: * @param insert
3069: * @throws CollabException
3070: */
3071: public void updateStatusFileChanged(int offset, int length,
3072: boolean insert) throws CollabException {
3073: fileChanged = true;
3074: }
3075:
3076: /**
3077: * for debug
3078: *
3079: */
3080: public void printAllRegionInfo() {
3081: CollabRegion[] objArr = (CollabRegion[]) rCtx.getRegion()
3082: .values().toArray(new CollabRegion[0]);
3083:
3084: for (int i = 0; i < objArr.length; i++) {
3085: CollabRegion sect = objArr[i];
3086: printRegionInfo(sect, "");
3087: }
3088: }
3089:
3090: /**
3091: * for debug
3092: *
3093: */
3094: public void printRegionInfo(CollabRegion sect, String message) {
3095: int beginOffset = 0;
3096: int endOffset = 0;
3097: String regionName = null;
3098: regionName = sect.getID();
3099: beginOffset = sect.getBeginOffset();
3100: endOffset = sect.getEndOffset();
3101: printRegionInfo(regionName, beginOffset, endOffset, message);
3102: }
3103:
3104: /**
3105: * for debug
3106: *
3107: */
3108: public void printRegionInfo(String regionName, int beginOffset,
3109: int endOffset, String message) {
3110: Debug.log("CollabFileHandlerSupport_RegionInfo", "\n\n"
3111: + message + "\n========================\n"); //NoI18n
3112: Debug.log("CollabFileHandlerSupport_RegionInfo", "regionName: "
3113: + regionName); //NoI18n
3114: Debug.log("CollabFileHandlerSupport_RegionInfo", "begin: "
3115: + beginOffset); //NoI18n
3116: Debug.log("CollabFileHandlerSupport_RegionInfo", "end: "
3117: + endOffset); //NoI18n
3118: Debug.log("CollabFileHandlerSupport_RegionInfo",
3119: "\n========================\n"); //NoI18n
3120: }
3121:
3122: /**
3123: *
3124: * @return folder
3125: */
3126: public FileObject createFolder(String fullpath)
3127: throws CollabException {
3128: FileObject folder = FileUtil
3129: .toFileObject(((CollabFilesystem) getContext()
3130: .getCollabFilesystem()).getCollabRoot()); //getContext().getCollabFilesystem().getRoot();
3131:
3132: try {
3133: int index = fullpath.lastIndexOf(FILE_SEPERATOR);
3134:
3135: if (index != -1) {
3136: String path = fullpath.substring(0, index);
3137: StringTokenizer st = new StringTokenizer(path,
3138: FILE_SEPERATOR);
3139:
3140: while (st.hasMoreTokens()) {
3141: String token = st.nextToken();
3142: FileObject tmpFolder = folder.getFileObject(token);
3143:
3144: if (tmpFolder == null) {
3145: tmpFolder = folder.createFolder(token);
3146: }
3147:
3148: folder = tmpFolder;
3149: }
3150: }
3151: } catch (IOException e) {
3152: throw new CollabException(e);
3153: }
3154:
3155: return folder;
3156: }
3157:
3158: /**
3159: * getter for fileName
3160: *
3161: * @return fileName name of file being handled
3162: */
3163: public String getName() {
3164: return fileName;
3165: }
3166:
3167: /**
3168: * getter for fileSize
3169: *
3170: * @return fileSize size of file being handled
3171: */
3172: public long getFileSize() {
3173: return this .fileObject.getSize();
3174: }
3175:
3176: /**
3177: * getter for groupName where this file belongs
3178: *
3179: * @return fileGroupName name of fileGroup
3180: */
3181: public SharedFileGroup getSharedFileGroup() {
3182: return sharedFileGroup;
3183: }
3184:
3185: /**
3186: * getter for groupName where this file belongs
3187: *
3188: * @return fileGroupName name of fileGroup
3189: */
3190: public String getFileGroupName() {
3191: return getSharedFileGroup().getName();
3192: }
3193:
3194: /**
3195: * setter for fileName
3196: *
3197: * @param fileName name of file being handled
3198: */
3199: public void setFileName(String fileName) {
3200: this .fileName = fileName;
3201: }
3202:
3203: /**
3204: * setter for sharedFileGroup where this file belongs
3205: *
3206: * @param fileGroupName name of fileGroup
3207: */
3208: public void setFileGroup(SharedFileGroup sharedFileGroup) {
3209: this .sharedFileGroup = sharedFileGroup;
3210: }
3211:
3212: /**
3213: * isSendFirstTime
3214: *
3215: * @return isSendFirstTime
3216: */
3217: public boolean isSendFirstTime() {
3218: return this .firstTimeSend;
3219: }
3220:
3221: /**
3222: * getter for filehandler
3223: *
3224: * @return filehandler
3225: */
3226: public abstract CollabFileHandler getFileHandler();
3227:
3228: /**
3229: * getter for file content encoding
3230: *
3231: * @return encoding
3232: */
3233: public String getEncoding() {
3234: return CollabFileHandler.ENCODING;
3235: }
3236:
3237: /**
3238: * getter for file content digest
3239: *
3240: * @return digest
3241: */
3242: public String getDigest() {
3243: return CollabFileHandler.DIGEST;
3244: }
3245:
3246: /**
3247: * setter for CollabContext
3248: *
3249: * @param context
3250: */
3251: public void setContext(CollabContext context) {
3252: this .context = (FilesharingContext) context;
3253: }
3254:
3255: /**
3256: * getter for channel
3257: *
3258: * @return channel
3259: */
3260: public FilesharingContext getContext() {
3261: return this .context;
3262: }
3263:
3264: /**
3265: * setSkipUpdateAlways
3266: *
3267: * @param skipUpdateAlways
3268: */
3269: public void setSkipUpdateAlways(boolean skipUpdateAlways) {
3270: Debug.log("CollabFileHandlerSupport", //NoI18n
3271: "CollabFileHandlerSupport, skipUpdateAlways to: " + //NoI18n
3272: skipUpdateAlways);
3273: this .skipUpdateAlways = skipUpdateAlways;
3274: }
3275:
3276: /**
3277: *
3278: * @return
3279: */
3280: public int getCurrentState() {
3281: return this .currentState;
3282: }
3283:
3284: /**
3285: * setCurrentState
3286: *
3287: * @param currentState
3288: */
3289: public void setCurrentState(int currentState) {
3290: Debug.log("CollabFileHandlerSupport", //NoI18n
3291: "CollabFileHandlerSupport, setCurrentState to: " + //NoI18n
3292: currentState);
3293: setCurrentState(currentState, -1);
3294: }
3295:
3296: /**
3297: * setCurrentState
3298: *
3299: * @param currentState
3300: * @param delay
3301: */
3302: public void setCurrentState(final int currentState, long delay) {
3303: setCurrentState(currentState, delay, true);
3304: }
3305:
3306: /**
3307: * setCurrentState
3308: *
3309: * @param currentState
3310: * @param delay
3311: * @param saveUnconditionally
3312: */
3313: public void setCurrentState(final int currentState, long delay,
3314: final boolean saveUnconditionally) {
3315: setCurrentState(currentState, delay, saveUnconditionally, false);
3316: }
3317:
3318: /**
3319: * setCurrentState
3320: *
3321: * @param currentState
3322: * @param delay
3323: * @param saveUnconditionally
3324: * @param changeSkipUpdate
3325: */
3326: public void setCurrentState(final int currentState, long delay,
3327: final boolean saveUnconditionally,
3328: final boolean changeSkipUpdate) {
3329: Debug.log("CollabFileHandlerSupport", //NoI18n
3330: "CollabFileHandlerSupport, setCurrentState to: " + //NoI18n
3331: currentState + " for: " + delay + " millis");
3332: this .currentState = currentState;
3333:
3334: if (delay == -1) {
3335: return;
3336: }
3337:
3338: if (changeSkipUpdate) {
3339: setSkipUpdate(true);
3340: }
3341:
3342: TimerTask resetStateTask = new TimerTask() {
3343: public void run() {
3344: int currentState = CollabFileHandlerSupport.this
3345: .getCurrentState();
3346: Debug.log("CollabFileHandlerSupport", //NoI18n
3347: "CollabFileHandlerSupport, reset setCurrentState from: "
3348: + //NoI18n
3349: currentState);
3350:
3351: try {
3352: if (saveUnconditionally) {
3353: getContext().setSkipSendFile(getName(), true);
3354: saveDocument();
3355:
3356: //sleep for 200 millis after save
3357: try {
3358: Thread.sleep(200);
3359: } catch (java.lang.Throwable th) {
3360: //ignore
3361: }
3362:
3363: getContext().setSkipSendFile(getName(), false);
3364: }
3365: } catch (CollabException ce) {
3366: Debug.log("CollabFileHandlerSupport", //NoI18n
3367: "CollabFileHandlerSupport, cannot saveDocument"
3368: + //NoI18n
3369: getName());
3370: }
3371:
3372: if (changeSkipUpdate) {
3373: setSkipUpdate(false);
3374: }
3375:
3376: CollabFileHandlerSupport.this
3377: .setCurrentState(FilesharingContext.STATE_UNKNOWN);
3378: }
3379: };
3380:
3381: getContext().schedule(resetStateTask, delay);
3382: }
3383:
3384: /**
3385: *
3386: * @return sendFileTimerTask
3387: */
3388: public SendFileTimerTask getSendFileTimerTask() {
3389: return this .sendFileTimerTask;
3390: }
3391:
3392: /**
3393: *
3394: * @param sendFileTimerTask
3395: */
3396: public void setSendFileTimerTask(SendFileTimerTask sendFileTimerTask) {
3397: this .sendFileTimerTask = sendFileTimerTask;
3398: }
3399:
3400: /**
3401: *
3402: * @return true if already scheduled
3403: */
3404: public boolean isScheduledSendFileGroup() {
3405: return this .scheduledSendFileGroupStatus;
3406: }
3407:
3408: /**
3409: *
3410: * @param status
3411: */
3412: public void setScheduledSendFileGroup(boolean status) {
3413: this .scheduledSendFileGroupStatus = status;
3414: }
3415:
3416: /**
3417: * setter for fileObject
3418: *
3419: * @param fileObject fileObject of file being handled
3420: */
3421: public void setFileObject(FileObject file) {
3422: this .fileObject = file;
3423: }
3424:
3425: /**
3426: * getter for fileObject
3427: *
3428: * @return fileObject fileObject of file being handled
3429: */
3430: public FileObject getFileObject() {
3431: return fileObject;
3432: }
3433:
3434: /**
3435: * create a fileObject with the given fileContent
3436: *
3437: * @param fileContent
3438: * @throws CollabException
3439: * @return fileObject
3440: */
3441: public FileObject createFileObject(String fileContent)
3442: throws CollabException {
3443: return createFileObject(fileContent.getBytes());
3444: }
3445:
3446: /**
3447: * create a fileObject with the given fileContent
3448: *
3449: * @param fileContent
3450: * @throws CollabException
3451: * @return fileObject
3452: */
3453: public FileObject createFileObject(byte[] fileContent)
3454: throws CollabException {
3455: getContext().setSkipSendFile(getName(), true);
3456:
3457: FileSystem filesystem = getContext().getCollabFilesystem();
3458: this .fileContent = fileContent;
3459:
3460: if (fileObject == null) {
3461: fileObject = filesystem.findResource(getName());
3462:
3463: if (fileObject == null) {
3464: try {
3465: final FileSystem fs = getContext()
3466: .getCollabFilesystem();
3467: final String fs_path = ((CollabFilesystem) fs)
3468: .getCollabRoot().getPath();
3469: fs.runAtomicAction(new FileSystem.AtomicAction() {
3470: public void run() throws IOException {
3471: FileObject folder = null;
3472:
3473: try {
3474: folder = createFolder(getName());
3475: } catch (CollabException ex) {
3476: String r_folder = getName().substring(
3477: 0,
3478: getName().lastIndexOf(
3479: FILE_SEPERATOR));
3480: Debug.log("CollabFileHandlerSupport",
3481: "CollabFileHandlerSupport, r_folder: "
3482: + r_folder);
3483:
3484: URL url = new URL("file:///" + fs_path
3485: + File.separator + r_folder);
3486: Debug.log("CollabFileHandlerSupport",
3487: "CollabFileHandlerSupport, url: "
3488: + url);
3489: new File(fs_path + File.separator
3490: + r_folder).mkdirs();
3491: fs.refresh(false);
3492: folder = URLMapper.findFileObject(url);
3493: }
3494:
3495: if (folder == null) {
3496: throw new IOException(
3497: "Create folder failed for path: "
3498: + getName());
3499: }
3500:
3501: int index = getName().lastIndexOf(
3502: FILE_SEPERATOR);
3503:
3504: if (index != -1) {
3505: fileObject = createFile(folder,
3506: getName().substring(index + 1));
3507: } else {
3508: fileObject = createFile(folder,
3509: getName());
3510: }
3511:
3512: try {
3513: updateFileObject(CollabFileHandlerSupport.this .fileContent);
3514: } catch (CollabException ex) {
3515: ErrorManager.getDefault().notify(ex);
3516: }
3517: }
3518: });
3519: } catch (FileStateInvalidException ex) {
3520: ErrorManager.getDefault().notify(ex);
3521: } catch (IOException ex) {
3522: ErrorManager.getDefault().notify(ex);
3523: } catch (Exception ex) {
3524: ErrorManager.getDefault().notify(ex);
3525: } finally {
3526: getContext().setSkipSendFile(getName(), false);
3527: }
3528: } else {
3529: updateFileObject(fileContent);
3530: }
3531: }
3532:
3533: getContext().setSkipSendFile(getName(), false);
3534:
3535: return fileObject;
3536: }
3537:
3538: protected FileObject createFile(FileObject folder, String fileName) {
3539: Debug.log("CollabFileHandlerSupport",
3540: "CollabFileHandlerSupport, " + //NoI18n
3541: "createFile: " + fileName); //NoI18n
3542:
3543: return createFile(folder, fileName, null);
3544: }
3545:
3546: protected FileObject createFile(FileObject folder, String fileName,
3547: String ext) {
3548: Debug.log("CollabFileHandlerSupport",
3549: "CollabFileHandlerSupport, " + //NoI18n
3550: "createFile: " + fileName + " ext: " + ext); //NoI18n
3551:
3552: try {
3553: if ((ext != null) && (ext.trim().length() > 0)) {
3554: return folder.createData(fileName, ext);
3555: } else {
3556: return folder.createData(fileName);
3557: }
3558: } catch (IOException ex) {
3559: ErrorManager.getDefault().notify(ex);
3560: }
3561:
3562: return null;
3563: }
3564:
3565: /**
3566: * update given fileObject
3567: *
3568: * @param fileContent
3569: * @throws CollabException
3570: */
3571: public void updateFileObject(String fileContent)
3572: throws CollabException {
3573: updateFileObject(fileContent.getBytes());
3574: }
3575:
3576: /**
3577: * update given fileObject
3578: *
3579: * @param fileContent
3580: * @throws CollabException
3581: */
3582: public void updateFileObject(byte[] fileContent)
3583: throws CollabException {
3584: this .fileContent = fileContent;
3585:
3586: try {
3587: FileSystem fs = getContext().getCollabFilesystem();
3588: fs.runAtomicAction(new FileSystem.AtomicAction() {
3589: public void run() throws IOException {
3590: ByteArrayInputStream inputStream = new ByteArrayInputStream(
3591: CollabFileHandlerSupport.this .fileContent);
3592:
3593: try {
3594: fileLock = fileObject.lock();
3595: } catch (FileAlreadyLockedException ale) {
3596: //ignore
3597: }
3598:
3599: fileOutputStream = fileObject
3600: .getOutputStream(fileLock);
3601: StreamCopier.copyStream(inputStream,
3602: fileOutputStream);
3603: }
3604: });
3605: } catch (FileStateInvalidException ex) {
3606: ErrorManager.getDefault().notify(ex);
3607: } catch (IOException ex) {
3608: ErrorManager.getDefault().notify(ex);
3609: } catch (Exception ex) {
3610: ErrorManager.getDefault().notify(ex);
3611: } finally {
3612: if (fileLock != null) {
3613: fileLock.releaseLock();
3614: }
3615:
3616: try {
3617: if (fileOutputStream != null) {
3618: fileOutputStream.close();
3619: }
3620: } catch (IOException e) {
3621: throw new CollabException(e);
3622: }
3623: }
3624:
3625: getFileObject().refresh(false);
3626: }
3627:
3628: /**
3629: * return document object for this file
3630: *
3631: * @throws CollabException
3632: * @return document
3633: */
3634: public StyledDocument getDocument() throws CollabException {
3635: try {
3636: StyledDocument document = getEditorCookie().openDocument();
3637:
3638: return document;
3639: } catch (org.openide.loaders.DataObjectNotFoundException notFound) {
3640: throw new CollabException(notFound);
3641: } catch (java.io.IOException io) {
3642: throw new CollabException(io);
3643: }
3644: }
3645:
3646: /**
3647: * return editor cookie for this filehandler
3648: *
3649: * @throws CollabException
3650: * @return document
3651: */
3652: public EditorCookie getEditorCookie() throws CollabException {
3653: Debug.log("CollabFileHandlerSupport",
3654: "CollabFileHandlerSupport, " + //NoI18n
3655: "geteditorCookie for file: " + getName()); //NoI18n
3656:
3657: try {
3658: if (editorCookie == null) {
3659: FileObject file = getFileObject();
3660:
3661: if (file == null)
3662: return null;
3663:
3664: // Get the DataObject
3665: DataObject dataObject = DataObject.find(file);
3666:
3667: if (dataObject == null) {
3668: throw new IllegalArgumentException(
3669: "No DataObject found for file \""
3670: + getName() + "\"");
3671: }
3672:
3673: // Get the editor cookie for the file
3674: editorCookie = (EditorCookie) dataObject
3675: .getCookie(EditorCookie.class);
3676:
3677: //add reset Document Reference Listener
3678: addResetDocumentRefListener(editorCookie,
3679: getEditorObservableCookie());
3680: }
3681:
3682: return editorCookie;
3683: } catch (org.openide.loaders.DataObjectNotFoundException notFound) {
3684: throw new CollabException(notFound);
3685: } catch (java.io.IOException io) {
3686: throw new CollabException(io);
3687: }
3688: }
3689:
3690: /**
3691: * getEditorObservableCookie
3692: *
3693: * @throws CollabException
3694: * @return document
3695: */
3696: public EditorCookie.Observable getEditorObservableCookie()
3697: throws CollabException {
3698: Debug.log("CollabFileHandlerSupport",
3699: "CollabFileHandlerSupport, " + //NoI18n
3700: "getEditorObservableCookie for file: " + //NoI18n
3701: getName());
3702:
3703: try {
3704: if (editorObservableCookie == null) {
3705: FileObject file = getFileObject();
3706:
3707: // Get the FileObject
3708: if (file == null) {
3709: return null;
3710: }
3711:
3712: // Get the DataObject
3713: DataObject dataObject = DataObject.find(file);
3714:
3715: if (dataObject == null) {
3716: throw new IllegalArgumentException(
3717: "No DataObject found for file \""
3718: + getName() + "\"");
3719: }
3720:
3721: //add PropertyChangeListener
3722: editorObservableCookie = (EditorCookie.Observable) dataObject
3723: .getCookie(EditorCookie.Observable.class);
3724: }
3725:
3726: return editorObservableCookie;
3727: } catch (org.openide.loaders.DataObjectNotFoundException notFound) {
3728: throw new CollabException(notFound);
3729: } catch (java.io.IOException io) {
3730: throw new CollabException(io);
3731: }
3732: }
3733:
3734: /**
3735: * addResetDocumentRefListener
3736: *
3737: * @throws CollabException
3738: * @return document
3739: */
3740: public void addResetDocumentRefListener(EditorCookie editorCookie,
3741: EditorCookie.Observable editorObservableCookie)
3742: throws CollabException {
3743: Debug.log("CollabFileHandlerSupport",
3744: "CollabFileHandlerSupport, "
3745: + "addResetDocumentRefListener for file: "
3746: + getName());
3747:
3748: //remove PropertyChangeListener
3749: if ((editorObservableCookie != null)
3750: && (cookieListener != null)) {
3751: editorObservableCookie
3752: .removePropertyChangeListener(cookieListener);
3753: }
3754:
3755: //add PropertyChangeListener
3756: cookieListener = new CollabEditorCookieListener(editorCookie);
3757:
3758: if (editorObservableCookie != null) {
3759: Debug.log("CollabFileHandlerSupport",
3760: "CollabFileHandlerSupport, adding cookieListener"); //NoI18n
3761: editorObservableCookie
3762: .addPropertyChangeListener(cookieListener);
3763: } else {
3764: Debug
3765: .log("CollabFileHandlerSupport",
3766: "CollabFileHandlerSupport, scheduling cookieListener"); //NoI18n
3767: getContext().cancelTimerTask(COOKIE_LISTENER_TIMER_TASK,
3768: getName());
3769: getContext().addTimerTask(COOKIE_LISTENER_TIMER_TASK,
3770: getName(), cookieListener);
3771: getContext().scheduleAtFixedRate(
3772: new SwingThreadTask(cookieListener),
3773: FilesharingTimerTask.INTER_DELAY,
3774: FilesharingTimerTask.PERIOD);
3775: }
3776: }
3777:
3778: /**
3779: * createEventNotifer
3780: *
3781: * @return EventNotifier
3782: * @throws CollabException
3783: */
3784: public EventNotifier createEventNotifer() throws CollabException {
3785: //create a notifer first
3786: EventProcessor eventProcessor = FilesharingEventProcessorFactory
3787: .getDefault()
3788: .createEventProcessor(
3789: getContext().getProcessorConfig(), getContext());
3790: EventNotifier eventNotifier = FilesharingEventNotifierFactory
3791: .getDefault().createEventNotifier(
3792: getContext().getNotifierConfig(),
3793: eventProcessor);
3794:
3795: return eventNotifier;
3796: }
3797:
3798: /**
3799: * add DocumentListener
3800: *
3801: * @return DocumentListener
3802: * @throws CollabException
3803: */
3804: public abstract CollabDocumentListener addDocumentListener()
3805: throws CollabException;
3806:
3807: /**
3808: * register DocumentListener
3809: *
3810: * @throws CollabException
3811: */
3812: public void registerDocumentListener() throws CollabException {
3813: if (documentListener != null) {
3814: //add listener for this document
3815: getDocument().removeDocumentListener(documentListener);
3816: documentListener = null;
3817: }
3818:
3819: try {
3820: //add listener for this document
3821: documentListener = addDocumentListener();
3822: } catch (Throwable th) {
3823: Debug.log("CollabFileHandlerSupport",
3824: "CollabFileHandlerSupport, " + //NoI18n
3825: "cannot add documentlistener "); //NoI18n
3826: Debug.logDebugException("CollabFileHandlerSupport, " + //NoI18n
3827: "cannot add documentlistener", //NoI18n
3828: th, true);
3829: }
3830:
3831: if (documentListener != null) {
3832: //save this listener
3833: getContext().addCollabDocumentListener(getName(),
3834: documentListener);
3835: }
3836: //Hack - Now save the editorpane that had the users focus
3837: registerInputListener();
3838: }
3839:
3840: /**
3841: * getFileContentBytes
3842: *
3843: * @return byte[]
3844: * @throws CollabException
3845: */
3846: public byte[] getFileContentBytes() throws CollabException {
3847: byte[] content = null;
3848:
3849: try {
3850: InputStream inputStream = getFileObject().getInputStream();
3851: ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
3852: StreamCopier.copyStream(inputStream, outputStream);
3853: content = outputStream.toByteArray();
3854: } catch (IOException iox) {
3855: throw new CollabException(iox);
3856: }
3857:
3858: return content;
3859: }
3860:
3861: /**
3862: * clear
3863: *
3864: * @throws CollabException
3865: */
3866: public void clear() throws CollabException {
3867: //remove PropertyChangeListener
3868: if ((editorObservableCookie != null)
3869: && (cookieListener != null)) {
3870: editorObservableCookie
3871: .removePropertyChangeListener(cookieListener);
3872: }
3873:
3874: getContext().cancelTimerTask(COOKIE_LISTENER_TIMER_TASK,
3875: getName());
3876:
3877: //clear annotations
3878: for (int i = 0; i < rCtx.getLineRegionCount(); i++) {
3879: CollabLineRegion lineRegion = rCtx.getLineRegion(i);
3880: if (lineRegion != null)
3881: lineRegion.removeAnnotation();
3882: }
3883:
3884: this .removeAllRegion();
3885: }
3886:
3887: /**
3888: * encode
3889: *
3890: * @param text
3891: * @return Base64 and UTF-8 encoded string
3892: */
3893: public String encode(String text) throws CollabException {
3894: String encodedText = null;
3895:
3896: try {
3897: encodedText = encodeBase64(text.getBytes("UTF-8"));
3898: } catch (java.io.UnsupportedEncodingException uee) {
3899: throw new CollabException(uee);
3900: }
3901:
3902: return encodedText;
3903: }
3904:
3905: /**
3906: * encode Base64
3907: *
3908: * @param content (byte[])
3909: * @return Base64 encoded string
3910: */
3911: public String encodeBase64(byte[] content) throws CollabException {
3912: return Base64.encode(content);
3913: }
3914:
3915: /**
3916: * decode
3917: *
3918: * @param text
3919: * @return Base64 and UTF-8 decoded string
3920: */
3921: public String decode(String text) throws CollabException {
3922: String decodedText = null;
3923:
3924: try {
3925: byte[] fileContents = decodeBase64(text);
3926: decodedText = new String(fileContents, "UTF-8");
3927: } catch (java.io.UnsupportedEncodingException uee) {
3928: throw new CollabException(uee);
3929: }
3930:
3931: return decodedText;
3932: }
3933:
3934: /**
3935: * decode Base64
3936: *
3937: * @param text
3938: * @return Base64 decoded string
3939: */
3940: public byte[] decodeBase64(String text) throws CollabException {
3941: return Base64.decode(text);
3942: }
3943:
3944: /**
3945: * documentViewChanged
3946: *
3947: */
3948: private void documentViewChanged() {
3949: EditorLock editorLock = null;
3950:
3951: try {
3952: editorLock = lockEditor();
3953: } catch (CollabException ce) {
3954: //ignore
3955: }
3956:
3957: resetDocumentRef();
3958: unlockEditor(editorLock);
3959: }
3960:
3961: /**
3962: * resetDocumentRef
3963: *
3964: */
3965: private boolean resetDocumentRef() {
3966: Debug.log("CollabFileHandlerSupport",
3967: "CollabFileHandlerSupport, resetDocumentRef"); //NoI18n
3968: Debug.log("CollabFileHandlerSupport",
3969: "CollabFileHandlerSupport, user: " + //NoI18n
3970: getContext().getLoginUser());
3971:
3972: try {
3973: //register doc listener if doc length changed but there is no indication of change
3974: Debug.log("CollabFileHandlerSupport",
3975: "CollabFileHandlerSupport, register Listeners"); //NoI18n
3976:
3977: //-commenting out
3978: //doc listener is now added from TC listener
3979: //registerDocumentListener();
3980: resetAllLineRegionOffset();
3981: } catch (CollabException ce) {
3982: return false;
3983: }
3984:
3985: return true;
3986: }
3987:
3988: /**
3989: * resetAllLineRegionOffset
3990: *
3991: */
3992: private void resetAllLineRegionOffset() throws CollabException {
3993: Debug.log("CollabFileHandlerSupport", //NoI18n
3994: "CollabFileHandlerSupport, resetAllLineRegionOffset"); //NoI18n
3995:
3996: StyledDocument fileDocument = getDocument();
3997: Element rootElement = fileDocument.getDefaultRootElement();
3998: int totalElementCount = fileDocument.getDefaultRootElement()
3999: .getElementCount();
4000:
4001: for (int i = 0; i < rCtx.getLineRegionCount(); i++) {
4002: CollabLineRegion lineRegion = rCtx.getLineRegion(i);
4003:
4004: if (lineRegion != null) {
4005: Debug.log("CollabFileHandlerSupport_LineRegion",
4006: "CollabFileHandlerSupport, reset region: " + //NoI18n
4007: lineRegion.getID());
4008:
4009: if (i < totalElementCount) {
4010: javax.swing.text.Element currentElement = rootElement
4011: .getElement(i);
4012: int beginOffset = currentElement.getStartOffset();
4013: int endOffset = currentElement.getEndOffset();
4014: Debug.log("CollabFileHandlerSupport_LineRegion",
4015: "CollabFileHandlerSupport, beginOffset: " + //NoI18n
4016: beginOffset);
4017: Debug.log("CollabFileHandlerSupport_LineRegion",
4018: "CollabFileHandlerSupport, endOffset: " + //NoI18n
4019: endOffset);
4020:
4021: try {
4022: lineRegion.setBeginOffset(beginOffset);
4023: lineRegion.setEndOffset(endOffset);
4024: } catch (java.lang.IllegalArgumentException ia) {
4025: Debug.logDebugException(
4026: "CollabFileHandlerSupport, " + //NoI18n
4027: "resetallbeginoffset failed",
4028: ia, true);//NoI18n
4029: }
4030: }
4031:
4032: lineRegion.setDocument(fileDocument);
4033: }
4034: }
4035: }
4036:
4037: /**
4038: * resetAllLineRegionOffset
4039: *
4040: * @param delay
4041: */
4042: public void resetAllLineRegionOffset(long delay) {
4043: Debug.log("CollabFileHandlerSupport", //NoI18n
4044: "CollabFileHandlerSupport, resetAllLineRegionOffset " + //NoI18n
4045: " after delay: " + delay + " millis"); //NoI18n
4046:
4047: TimerTask resetOffsetTask = new TimerTask() {
4048: public void run() {
4049: try {
4050: resetAllLineRegionOffset();
4051: } catch (CollabException ce) {
4052: Debug.log("CollabFileHandlerSupport", //NoI18n
4053: "CollabFileHandlerSupport, cannot resetAllLineRegionOffset"
4054: + //NoI18n
4055: getName());
4056: }
4057: }
4058: };
4059:
4060: getContext().schedule(resetOffsetTask, delay);
4061: }
4062:
4063: /**
4064: * getLineRegions
4065: *
4066: * @param regionName
4067: * @return lineRegions
4068: */
4069: public List getLineRegions(String regionName) {
4070: return rCtx.getLineRegions(regionName);
4071: }
4072:
4073: public String createUniqueLockID(String userID, String regionID) {
4074: return rCtx.createUniqueLockID(userID, regionID);
4075: }
4076:
4077: public LockRegionManager createLockRegionManager(String userID,
4078: LockRegion lockRegion) {
4079: return rCtx.createLockRegionManager(userID, lockRegion);
4080: }
4081:
4082: public LockRegionManager createLockRegionManager(String userID,
4083: RegionInfo regionInfo) {
4084: return rCtx.createLockRegionManager(userID, regionInfo);
4085: }
4086:
4087: public void removeLockRegionManager(String lockID) {
4088: rCtx.removeLockManager(lockID);
4089: }
4090:
4091: /**
4092: * disableUnlockTimer
4093: *
4094: * @param status
4095: */
4096: protected void disableUnlockTimer(boolean status) {
4097: this .disableUnlockTimer = status;
4098: }
4099:
4100: /**
4101: * isDisableUnlockTimer
4102: *
4103: * @return disableUnlockTimer
4104: */
4105: private boolean isDisableUnlockTimer() {
4106: return this .disableUnlockTimer;
4107: }
4108:
4109: /**
4110: * getUserStyle
4111: *
4112: * @return
4113: */
4114: public int getUserStyle(String user) {
4115: Integer style = (Integer) userStyles.get(user);
4116:
4117: if (style == null) {
4118: style = getContext().getUserStyle(user);
4119: userStyles.put(user, style);
4120: }
4121:
4122: return style.intValue();
4123: }
4124:
4125: /**
4126: * getJoinTimeStamp
4127: *
4128: * @return
4129: */
4130: public long getJoinTimeStamp() {
4131: Debug.log("CollabFileHandlerSupport",
4132: "CollabFileHandlerSupport, joinTimeStamp before"
4133: + joinTimeStamp);
4134:
4135: if (joinTimeStamp == -1) {
4136: joinTimeStamp = getContext().getJoinTimeStamp();
4137: }
4138:
4139: Debug.log("CollabFileHandlerSupport",
4140: "CollabFileHandlerSupport, joinTimeStamp after"
4141: + joinTimeStamp);
4142:
4143: return joinTimeStamp;
4144: }
4145:
4146: /**
4147: * getQueue
4148: *
4149: * @return queue
4150: */
4151: public RegionQueue getQueue() {
4152: return this .queue;
4153: }
4154:
4155: //Key Events
4156: /** Handle the key typed event from the text field. */
4157: public void keyTyped(KeyEvent e) {
4158: setCurrentEditorPane(findCurrentEditorPane());
4159: if (Debug.isEnabled())
4160: displayInfo(e, "KEY TYPED: ");
4161: }
4162:
4163: /** Handle the key pressed event from the text field. */
4164: public void keyPressed(KeyEvent e) {
4165: setCurrentEditorPane(findCurrentEditorPane());
4166: if (Debug.isEnabled())
4167: displayInfo(e, "KEY PRESSED: ");
4168: }
4169:
4170: /** Handle the key released event from the text field. */
4171: public void keyReleased(KeyEvent e) {
4172: }
4173:
4174: protected void displayInfo(KeyEvent e, String s) {
4175: String keyString = null;
4176: String modString = null;
4177: String actionString = null;
4178: String locationString = null;
4179: //You should only rely on the key char if the event
4180: //is a key typed event.
4181: int id = e.getID();
4182: if (id == KeyEvent.KEY_TYPED) {
4183: char c = e.getKeyChar();
4184: keyString = "key character = '" + c + "'";
4185: } else {
4186: int keyCode = e.getKeyCode();
4187: keyString = "key code = " + keyCode + " ("
4188: + KeyEvent.getKeyText(keyCode) + ")";
4189: }
4190:
4191: int modifiers = e.getModifiersEx();
4192: modString = "modifiers = " + modifiers;
4193: String tmpString = KeyEvent.getModifiersExText(modifiers);
4194: if (tmpString.length() > 0) {
4195: modString += " (" + tmpString + ")";
4196: } else {
4197: modString += " (no modifiers)";
4198: }
4199:
4200: actionString = "action key? ";
4201: if (e.isActionKey()) {
4202: actionString += "YES";
4203: } else {
4204: actionString += "NO";
4205: }
4206:
4207: locationString = "key location: ";
4208: int location = e.getKeyLocation();
4209: if (location == KeyEvent.KEY_LOCATION_STANDARD) {
4210: locationString += "standard";
4211: } else if (location == KeyEvent.KEY_LOCATION_LEFT) {
4212: locationString += "left";
4213: } else if (location == KeyEvent.KEY_LOCATION_RIGHT) {
4214: locationString += "right";
4215: } else if (location == KeyEvent.KEY_LOCATION_NUMPAD) {
4216: locationString += "numpad";
4217: } else { // (location == KeyEvent.KEY_LOCATION_UNKNOWN)
4218: locationString += "unknown";
4219: }
4220:
4221: Debug.log("CollabFileHandlerSupport", "CFHS, " + "keyString: "
4222: + keyString + "actionString: " + actionString
4223: + "locationString: " + locationString);
4224: }
4225:
4226: //Mouse events
4227: public void mousePressed(MouseEvent e) {
4228: setCurrentEditorPane(findCurrentEditorPane());
4229: if (Debug.isEnabled())
4230: saySomething("Mouse pressed; # of clicks: "
4231: + e.getClickCount(), e);
4232: }
4233:
4234: public void mouseClicked(MouseEvent e) {
4235: setCurrentEditorPane(findCurrentEditorPane());
4236: if (Debug.isEnabled())
4237: saySomething("Mouse clicked (# of clicks: "
4238: + e.getClickCount() + ")", e);
4239: }
4240:
4241: public void mouseReleased(MouseEvent e) {
4242: }
4243:
4244: public void mouseEntered(MouseEvent e) {
4245: }
4246:
4247: public void mouseExited(MouseEvent e) {
4248: }
4249:
4250: void saySomething(String eventDescription, MouseEvent e) {
4251: Debug.log("CollabFileHandlerSupport", "CFHS, "
4252: + eventDescription + " detected on "
4253: + e.getComponent().getClass().getName());
4254: }
4255:
4256: private void registerInputListener() throws CollabException {
4257: JEditorPane[] editorPanes = getEditorPanes();
4258: ;
4259: if (editorPanes == null)
4260: return;
4261: Debug.log("CollabFileHandlerSupport",
4262: "CFHS, save editor pane for focus: "
4263: + "# of editorPanes: " + editorPanes.length);
4264: for (int i = 0; i < editorPanes.length; i++) {
4265: JEditorPane editorPane = editorPanes[i];
4266: if (editorPane != null) {
4267: //Now remove and add key and mouse listeners for this editorpane
4268: Debug.log("CollabFileHandlerSupport",
4269: "CFHS, isFocusOwner: "
4270: + editorPane.isFocusOwner()
4271: + " for user: "
4272: + getContext().getLoginUser());
4273: editorPane.removeMouseListener(this );
4274: editorPane.removeKeyListener(this );
4275: editorPane.addMouseListener(this );
4276: editorPane.addKeyListener(this );
4277: }
4278: }
4279: //get the last editor pane and set as the current editorpane
4280: JEditorPane editorPane = findCurrentEditorPane(editorPanes);
4281: if (editorPane != null) {
4282: Debug.log("CollabFileHandlerSupport",
4283: "CFHS, isFocusOwner: " + editorPane.isFocusOwner()
4284: + " for user: "
4285: + getContext().getLoginUser());
4286: setCurrentEditorPane(editorPane);
4287: }
4288: }
4289:
4290: private JEditorPane findCurrentEditorPane() {
4291: try {
4292: return findCurrentEditorPane(getEditorPanes());
4293: } catch (CollabException ce) {
4294: return null;
4295: }
4296: }
4297:
4298: private JEditorPane findCurrentEditorPane(JEditorPane[] editorPanes) {
4299: if (editorPanes != null && editorPanes.length > 0)
4300: return editorPanes[editorPanes.length - 1];
4301: else
4302: return null;
4303: }
4304:
4305: private JEditorPane[] getEditorPanes() throws CollabException {
4306: final EditorCookie ec = getEditorCookie();
4307: if (ec != null)
4308: return (JEditorPane[]) Mutex.EVENT
4309: .readAccess(new Mutex.Action() {
4310: public Object run() {
4311: return ec.getOpenedPanes();
4312: }
4313: });
4314: return null;
4315: }
4316:
4317: private void setCurrentEditorPane(JEditorPane editorPane) {
4318: FilesharingCollablet.currentEditorPane = editorPane;
4319: }
4320:
4321: /**
4322: * toString
4323: *
4324: * @return fileName
4325: */
4326: public String toString() {
4327: return getName();
4328: }
4329:
4330: ////////////////////////////////////////////////////////////////////////////
4331: // Inner class
4332: ////////////////////////////////////////////////////////////////////////////
4333: class CollabEditorCookieListener extends TimerTask implements
4334: PropertyChangeListener {
4335: ////////////////////////////////////////////////////////////////////////////
4336: // Instance variables
4337: ////////////////////////////////////////////////////////////////////////////
4338:
4339: /* holds cookie */
4340: private EditorCookie cookie = null;
4341:
4342: /* done Reset Document */
4343: private boolean doneResetDoc = false;
4344:
4345: /**
4346: * constructor
4347: *
4348: */
4349: public CollabEditorCookieListener(EditorCookie cookie)
4350: throws CollabException {
4351: super ();
4352: this .cookie = cookie;
4353: }
4354:
4355: ////////////////////////////////////////////////////////////////////////////
4356: // methods
4357: ////////////////////////////////////////////////////////////////////////////
4358:
4359: /**
4360: *
4361: *
4362: */
4363: public void run() {
4364: if ((cookie != null) && !cookie.isModified()) {
4365: if (!doneResetDoc) {
4366: Debug
4367: .log("CollabFileHandlerSupport",
4368: "CollabFileHandlerSupport, \n\nCollabEditorCookieListener::run");
4369: Debug
4370: .log("CollabFileHandlerSupport",
4371: "CollabFileHandlerSupport, calling documentViewChange: ");
4372:
4373: boolean isValid = false;
4374:
4375: if (isValid()) {
4376: CollabFileHandlerSupport.this
4377: .documentViewChanged();
4378: }
4379:
4380: doneResetDoc = true;
4381: }
4382: } else {
4383: doneResetDoc = false;
4384: }
4385: }
4386:
4387: /**
4388: * propertyChange
4389: *
4390: * @param event
4391: */
4392: public void propertyChange(PropertyChangeEvent event) {
4393: if (EditorCookie.Observable.PROP_OPENED_PANES.equals(event
4394: .getPropertyName())) {
4395: if (isValid()) {
4396: Debug.log("CollabFileHandlerSupport",
4397: "CollabFileHandlerSupport, propertyChange: "
4398: + event.getPropertyName()); //NoI18n
4399: CollabFileHandlerSupport.this .documentViewChanged();
4400: }
4401: }
4402: }
4403: }
4404:
4405: class CollabRegionContext extends Object {
4406: ////////////////////////////////////////////////////////////////////////////
4407: // Instance variables
4408: ////////////////////////////////////////////////////////////////////////////
4409:
4410: /* repository to manage regions */
4411: protected HashMap regions = new HashMap();
4412:
4413: /* mapping of user to regions */
4414: protected HashMap collabUserRegionMap = new HashMap();
4415:
4416: /* mapping of collabregion to lineregion */
4417: protected HashMap collabRegionLineRegionMap = new HashMap();
4418:
4419: /**
4420: * constructor
4421: *
4422: */
4423: public CollabRegionContext() {
4424: super ();
4425: }
4426:
4427: ////////////////////////////////////////////////////////////////////////////
4428: // methods
4429: ////////////////////////////////////////////////////////////////////////////
4430:
4431: /**
4432: * adds a new region into repository
4433: *
4434: * @param user the user who created the region
4435: * @param regionName the regionName
4436: * @param region CollabRegion
4437: */
4438: public synchronized void addRegion(String user,
4439: String regionName, CollabRegion region) {
4440: if (!getRegion().containsKey(regionName)) {
4441: addRegion(regionName, region);
4442:
4443: if (!getUserRegion().containsKey(user)) {
4444: Vector tmpList = new Vector();
4445: tmpList.add(regionName);
4446: getUserRegion().put(user, tmpList);
4447: } else {
4448: Vector regionNames = ((Vector) getUserRegion().get(
4449: user));
4450: if (!regionNames.contains(regionName))
4451: regionNames.add(regionName);
4452: }
4453: } else {
4454: throw new IllegalArgumentException("region: "
4455: + regionName + " already exist");
4456: }
4457: }
4458:
4459: /**
4460: * adds a new region into repository
4461: *
4462: * @param regionName the regionName
4463: * @param region CollabRegion
4464: */
4465: public void addRegion(String regionName, CollabRegion region) {
4466: printRegionInfo(region,
4467: "Adding new region, region info for user: "
4468: + getContext().getLoginUser());
4469:
4470: if (!getRegion().containsKey(regionName)) {
4471: getRegion().put(regionName, region);
4472: } else {
4473: throw new IllegalArgumentException("region: "
4474: + regionName + " already exist");
4475: }
4476: }
4477:
4478: /**
4479: * adds a new lineregion into repository
4480: *
4481: * @param regionName the regionName
4482: * @param region CollabRegion
4483: */
4484: public synchronized void addLineRegion(String regionName,
4485: CollabRegion region) {
4486: addRegion(getLineRegionKey(), regionName, region);
4487: }
4488:
4489: /**
4490: * removes all region from the repository
4491: *
4492: * @throws CollabException
4493: */
4494: public synchronized void removeAllRegion()
4495: throws CollabException {
4496: removeAllRegion(false);
4497: }
4498:
4499: /**
4500: * removes all region from the repository
4501: *
4502: * @throws CollabException
4503: */
4504: public synchronized void removeAllRegion(
4505: boolean retainLineRegions) throws CollabException {
4506: String[] users = (String[]) getUserRegion().keySet()
4507: .toArray(new String[0]);
4508: for (int j = 0; j < users.length; j++) {
4509: String user = users[j];
4510:
4511: if (retainLineRegions && (user != null)
4512: && user.equals(getLineRegionKey())) {
4513: continue;
4514: }
4515:
4516: Vector regionNames = (Vector) getUserRegion(user);
4517:
4518: if (regionNames != null) {
4519: for (int i = 0; i < regionNames.size(); i++) {
4520: removeRegion((String) regionNames.get(i));
4521: }
4522:
4523: regionNames.clear();
4524: }
4525: }
4526:
4527: if (!retainLineRegions) {
4528: getUserRegion().clear();
4529: getRegion().clear();
4530: }
4531: }
4532:
4533: /**
4534: * removes a region from the repository
4535: *
4536: * @param user the user who created the region
4537: * @param regionName the regionName
4538: * @throws CollabException
4539: */
4540: public synchronized boolean removeRegion(String user,
4541: String regionName) throws CollabException {
4542: if (getUserRegion().containsKey(user)) {
4543: Vector regionNames = (Vector) getUserRegion().get(user);
4544:
4545: if (regionNames != null) {
4546: regionNames.remove(regionName);
4547:
4548: if (regionNames.isEmpty()) {
4549: getUserRegion().remove(user);
4550: }
4551: }
4552: } else {
4553: return false;
4554: }
4555:
4556: return removeRegion(regionName);
4557: }
4558:
4559: /**
4560: * remove a region
4561: *
4562: * @param regionName
4563: * @throws CollabException
4564: */
4565: public boolean removeRegion(String regionName)
4566: throws CollabException {
4567: if (getRegion().containsKey(regionName)) {
4568: CollabRegion sect = (CollabRegion) getRegion().get(
4569: regionName);
4570: printRegionInfo(sect,
4571: "Removing region, region info for user: "
4572: + getContext().getLoginUser());
4573: removeSection(sect);
4574: getRegion().remove(regionName);
4575:
4576: if (getRegion().containsKey(regionName)) {
4577: return false;
4578: }
4579: } else {
4580: return false;
4581: }
4582:
4583: return true;
4584: }
4585:
4586: /**
4587: * removes a line region from the repository
4588: *
4589: * @param regionName the regionName
4590: * @throws CollabException
4591: */
4592: public synchronized boolean removeLineRegion(String regionName)
4593: throws CollabException {
4594: return removeRegion(getLineRegionKey(), regionName);
4595: }
4596:
4597: /**
4598: * replaceLineRegions
4599: *
4600: * @param regionList the list of user regions
4601: */
4602: private void replaceLineRegions(Object regionList) {
4603: String user = getLineRegionKey();
4604: synchronized (collabUserRegionMap) {
4605: if (collabUserRegionMap.containsKey(user)) {
4606: collabUserRegionMap.remove(user);
4607: }
4608: collabUserRegionMap.put(user, regionList);
4609: }
4610: }
4611:
4612: /**
4613: * get userRegionMap
4614: *
4615: * @param user the user who created the region
4616: * @return regionList the list of user regions
4617: */
4618: public HashMap getUserRegion() {
4619: return collabUserRegionMap;
4620: }
4621:
4622: /**
4623: * get all region belonging to user from the repository
4624: *
4625: * @param user the user who created the region
4626: * @return regionList the list of user regions
4627: */
4628: public Object getUserRegion(String user) {
4629: Debug.log("CollabFileHandlerSupport_getLineRegion",
4630: "CollabFileHandlerSupport, In getUserRegion: "
4631: + collabUserRegionMap); //NoI18n
4632:
4633: return collabUserRegionMap.get(user);
4634: }
4635:
4636: /**
4637: * get a region from the repository
4638: *
4639: * @param regionName the regionName
4640: * @return region CollabRegion
4641: */
4642: public CollabRegion getRegion(String regionName) {
4643: if (!getRegion().containsKey(regionName)) {
4644: return null;
4645: }
4646:
4647: return (CollabRegion) getRegion().get(regionName);
4648: }
4649:
4650: /**
4651: * get a region from the repository
4652: *
4653: * @param regionName the regionName
4654: * @return CollabLineRegion
4655: */
4656: public CollabLineRegion getLineRegion(String regionName) {
4657: CollabLineRegion lineRegion = (CollabLineRegion) getRegion(regionName);
4658:
4659: return lineRegion;
4660: }
4661:
4662: /**
4663: * get a region from the repository
4664: *
4665: * @param regionIndex
4666: * @return CollabLineRegion
4667: */
4668: public CollabLineRegion getLineRegion(int regionIndex) {
4669: Debug.log("CollabFileHandlerSupport_getLineRegion",
4670: "CollabFileHandlerSupport, In getLineRegion"); //NoI18n
4671:
4672: Vector userRegions = (Vector) getUserRegion(getLineRegionKey());
4673:
4674: if ((userRegions == null) || (userRegions.size() == 0)
4675: || (regionIndex >= userRegions.size())) {
4676: Debug
4677: .log("CollabFileHandlerSupport_getLineRegion",
4678: "CollabFileHandlerSupport, getLineRegion userRegions null: "); //NoI18n
4679:
4680: return null;
4681: }
4682:
4683: String regionName = (String) userRegions.get(regionIndex);
4684: Debug.log("CollabFileHandlerSupport_getLineRegion",
4685: "CollabFileHandlerSupport, getLineRegion regionName: "
4686: + //NoI18n
4687: regionName);
4688:
4689: CollabLineRegion lineRegion = (CollabLineRegion) getRegion(regionName);
4690:
4691: return lineRegion;
4692: }
4693:
4694: /**
4695: * get a region from the repository
4696: *
4697: * @param regionIndex
4698: * @return Vector containing CollabLineRegion's
4699: */
4700: public Vector getLineRegion() {
4701: return (Vector) getUserRegion(getLineRegionKey());
4702: }
4703:
4704: /**
4705: * get lineregion count
4706: *
4707: * @return count of CollabLineRegion's
4708: */
4709: public int getLineRegionCount() {
4710: if (getLineRegion() != null) {
4711: return getLineRegion().size();
4712: } else {
4713: return 0;
4714: }
4715: }
4716:
4717: /**
4718: * get region map
4719: *
4720: * @return region map
4721: */
4722: public HashMap getRegion() {
4723: printUserRegions();
4724: return this .regions;
4725: }
4726:
4727: /**
4728: * get region map
4729: *
4730: * @return region map
4731: */
4732: public void printUserRegions() {
4733: if (Debug.isEnabled()) {
4734: synchronized (this .regions) {
4735: String[] users = (String[]) getUserRegion()
4736: .keySet().toArray(new String[0]);
4737: for (int j = 0; j < users.length; j++) {
4738: //String user = (String) it.next();
4739: String user = users[j];
4740: if (user != null
4741: && user.equals(getLineRegionKey()))
4742: continue;
4743: Debug.log(
4744: "CollabFileHandlerSupport_LineRegion",
4745: "CFHS, regions user: " + user);//NoI18n
4746:
4747: Vector userRegions = (Vector) getUserRegion(user);
4748: if (userRegions == null
4749: || userRegions.size() == 0)
4750: continue;
4751:
4752: for (int i = 0; i < userRegions.size(); i++) {
4753: String regionName = (String) userRegions
4754: .get(i);
4755: Debug
4756: .log(
4757: "CollabFileHandlerSupport_LineRegion",
4758: "CFHS, regions: " + //NoI18n
4759: regionName);
4760: }
4761: }
4762: }
4763: }
4764: }
4765:
4766: /**
4767: * test if the region exist in the repository
4768: *
4769: * @param regionName the regionName
4770: * @return true/false true if region exist
4771: */
4772: public boolean regionExist(String regionName) {
4773: return getRegion().containsKey(regionName);
4774: }
4775:
4776: /**
4777: * getLineRegions
4778: *
4779: * @param regionName
4780: * @return lineRegions
4781: */
4782: public List getLineRegions(String regionName) {
4783: return (List) collabRegionLineRegionMap.get(regionName);
4784: }
4785:
4786: /**
4787: * resetLineRegion
4788: *
4789: * @param regionName
4790: * @param newLines for this region
4791: * @param if old lineregions need to be removed for this file completely
4792: * @return newLines
4793: */
4794: public void resetLineRegion(String regionName, List newLines,
4795: boolean removeOldLines) {
4796: synchronized (collabRegionLineRegionMap) {
4797: if (removeOldLines) {
4798: List oldLines = getLineRegions(regionName);
4799: if (oldLines != null) {
4800: for (int i = 0; i < oldLines.size(); i++) {
4801: CollabLineRegion liner = (CollabLineRegion) oldLines
4802: .get(i);
4803: Debug.log("CollabFileHandlerSupport",
4804: "CFHS, removing " + "old line: "
4805: + liner.getID()); //NoI18n
4806: try {
4807: removeLineRegion(liner.getID());
4808: } catch (Exception e) {
4809: Debug.logDebugException(
4810: "exception removing "
4811: + "old line region", e,
4812: true);
4813: }
4814: }
4815: }
4816: }
4817: collabRegionLineRegionMap.remove(regionName);
4818: collabRegionLineRegionMap.put(regionName, newLines);
4819: }
4820: }
4821:
4822: /**
4823: * return a region that contains the offset, no correction needed
4824: *
4825: * @param beginOffset
4826: * @param length
4827: * @return
4828: */
4829: public CollabLineRegion[] getContainingLineRegion(
4830: int beginOffset, int length) throws CollabException {
4831: int endOffset = beginOffset + length;
4832: List lineRegionList = new ArrayList();
4833: Vector userRegions = (Vector) getLineRegion();
4834:
4835: if ((userRegions == null) || (userRegions.size() == 0)) {
4836: return null;
4837: }
4838:
4839: Debug.log("CollabFileHandlerSupport",
4840: "CollabFileHandlerSupport, total # of regions: " + //NoI18n
4841: userRegions.size());
4842: Debug.log("CollabFileHandlerSupport",
4843: "CollabFileHandlerSupport, beginOffset: "
4844: + beginOffset); //NoI18n
4845: Debug
4846: .log("CollabFileHandlerSupport",
4847: "CollabFileHandlerSupport, endOffset: "
4848: + endOffset); //NoI18n
4849:
4850: StyledDocument fileDocument = getDocument();
4851: int beginLine = fileDocument.getDefaultRootElement()
4852: .getElementIndex(beginOffset);
4853: Debug
4854: .log("CollabFileHandlerSupport",
4855: "CollabFileHandlerSupport, beginLine: "
4856: + beginLine); //NoI18n
4857:
4858: int endLine = fileDocument.getDefaultRootElement()
4859: .getElementIndex(endOffset - 1);
4860: Debug.log("CollabFileHandlerSupport",
4861: "CollabFileHandlerSupport, endLine: " + endLine); //NoI18n
4862:
4863: for (int lineIndex = beginLine; lineIndex <= endLine; lineIndex++) {
4864: if (lineIndex == userRegions.size()) {
4865: break;
4866: }
4867:
4868: String regionName = (String) userRegions.get(lineIndex);
4869: Debug.log("CollabFileHandlerSupport",
4870: "CollabFileHandlerSupport, regionName>: "
4871: + regionName); //NoI18n
4872:
4873: CollabLineRegion lineRegion = (CollabLineRegion) getRegion(regionName);
4874: Debug.log("CollabFileHandlerSupport",
4875: "CollabFileHandlerSupport, regionName>>: " + //NoI18n
4876: lineRegion.getID());
4877: Debug.log("CollabFileHandlerSupport",
4878: "CollabFileHandlerSupport, check begin: " + //NoI18n
4879: lineRegion.getBeginOffset());
4880: Debug.log("CollabFileHandlerSupport",
4881: "CollabFileHandlerSupport, end: " + //NoI18n
4882: lineRegion.getEndOffset());
4883: lineRegionList.add(lineRegion);
4884: }
4885:
4886: return (CollabLineRegion[]) lineRegionList
4887: .toArray(new CollabLineRegion[0]);
4888: }
4889:
4890: /**
4891: * return a region that contains the offset, no correction needed
4892: *
4893: * @param beginOffset
4894: * @param length
4895: * @return
4896: */
4897: public Object getContainingRegion(int offset, int length) {
4898: return getContainingRegion(offset, length, false);
4899: }
4900:
4901: /**
4902: * return a region that contains the offset
4903: *
4904: * @param user
4905: * @param beginOffset
4906: * @param length
4907: * @param applyCorrection
4908: * @return
4909: */
4910: protected CollabRegion getContainingRegion(int offset,
4911: int length, boolean applyCorrection) {
4912: Debug.log("CollabFileHandlerSupport",
4913: "CollabFileHandlerSupport, getContainingRegion"); //NoI18n
4914:
4915: int beginOffset = offset;
4916: int endOffset = offset + length;
4917:
4918: String[] users = (String[]) getUserRegion().keySet()
4919: .toArray(new String[0]);
4920: for (int j = 0; j < users.length; j++) {
4921: String user = users[j];
4922: if ((user != null) && user.equals(getLineRegionKey())) {
4923: continue;
4924: }
4925:
4926: Vector userRegions = (Vector) getUserRegion(user);
4927:
4928: if ((userRegions == null) || (userRegions.size() == 0)) {
4929: return null;
4930: }
4931:
4932: for (int i = 0; i < userRegions.size(); i++) {
4933: String regionName = (String) userRegions.get(i);
4934: CollabRegion sect = getRegion(regionName);
4935:
4936: if (sect == null) {
4937: return null;
4938: }
4939:
4940: CollabRegion match = getContainingRegion(sect,
4941: beginOffset, endOffset, applyCorrection);
4942:
4943: if (match != null) {
4944: return match;
4945: }
4946: }
4947: }
4948:
4949: return null;
4950: }
4951:
4952: /**
4953: * returns region if region contains the beginOffset & endOffset
4954: *
4955: * @param sect
4956: * @param beginOffset
4957: * @param endOffset
4958: * @param applyCorrection
4959: * @return region
4960: */
4961: protected CollabRegion getContainingRegion(CollabRegion sect,
4962: int beginOffset, int endOffset, boolean applyCorrection) {
4963: Debug.log("CollabFileHandlerSupport",
4964: "CollabFileHandlerSupport, check containingRegion"); //NoI18n
4965: Debug.log("CollabFileHandlerSupport",
4966: "CollabFileHandlerSupport, beginOffset: "
4967: + beginOffset); //NoI18n
4968: Debug
4969: .log("CollabFileHandlerSupport",
4970: "CollabFileHandlerSupport, endOffset: "
4971: + endOffset); //NoI18n
4972:
4973: if (sect.isGuarded()) {
4974: CollabRegionSupport.SimpleSection simpleSection = (CollabRegionSupport.SimpleSection) sect
4975: .getGuard();
4976:
4977: int posBegin = simpleSection.getBegin();
4978: int posEnd = simpleSection.getPositionAfter() - 1;
4979: Debug.log("CollabFileHandlerSupport",
4980: "CollabFileHandlerSupport, section: " + //NoI18n
4981: simpleSection.getName());
4982: Debug.log("CollabFileHandlerSupport",
4983: "CollabFileHandlerSupport, posBegin: "
4984: + posBegin); //NoI18n
4985: Debug.log("CollabFileHandlerSupport",
4986: "CollabFileHandlerSupport, posEnd: " + posEnd); //NoI18n
4987:
4988: if (((beginOffset >= posBegin) && (beginOffset <= posEnd))
4989: || ((endOffset >= posBegin) && (endOffset <= posEnd))) {
4990: return sect;
4991: }
4992: } else if (sect instanceof CollabRegion
4993: && !(sect instanceof CollabLineRegion)) {
4994: CollabRegion region = ((CollabRegion) sect);
4995: int posBegin = region.getBeginOffset();
4996: int posEnd = region.getEndOffset();
4997: Debug.log("CollabFileHandlerSupport",
4998: "CollabFileHandlerSupport, CollabRegion: " + //NoI18n
4999: region.getID());
5000: Debug.log("CollabFileHandlerSupport",
5001: "CollabFileHandlerSupport, posBegin: "
5002: + posBegin); //NoI18n
5003: Debug.log("CollabFileHandlerSupport",
5004: "CollabFileHandlerSupport, posEnd: " + posEnd); //NoI18n
5005:
5006: //correction
5007: if (applyCorrection) {
5008: posEnd -= 1;
5009: }
5010:
5011: if ((beginOffset >= posBegin && beginOffset <= posEnd)
5012: || ((endOffset >= posBegin) && (endOffset <= posEnd))) {
5013: return region;
5014: }
5015: }
5016:
5017: return null;
5018: }
5019:
5020: /**
5021: * returns adjacent region, meeting the adjacency length criteria
5022: *
5023: * @param offset
5024: * @param length
5025: * @param adjanceLength
5026: * @return
5027: */
5028: protected CollabRegion getContainingRegion(int offset,
5029: int length, int adjanceLength) {
5030: CollabRegion[] objArr = (CollabRegion[]) getRegion()
5031: .values().toArray(new CollabRegion[0]);
5032:
5033: for (int i = 0; i < objArr.length; i++) {
5034: CollabRegion sect = objArr[i];
5035:
5036: if (!(sect instanceof CollabLineRegion)) {
5037: CollabRegion region = ((CollabRegion) sect);
5038: int posBegin = region.getBeginOffset();
5039: int posEnd = region.getEndOffset();
5040:
5041: if ((offset >= posBegin) && (offset <= posEnd)) {
5042: return region;
5043: }
5044: }
5045: }
5046:
5047: return null;
5048: }
5049:
5050: /**
5051: * creates a CollabRegion, a super-class for all regions
5052: *
5053: * @param regionName the regionName
5054: * @param beginOffset the beginOffset
5055: * @param endOffset the endOffset
5056: * @throws CollabException
5057: * @return
5058: */
5059: public CollabRegion createLineRegion(String regionName,
5060: int beginOffset, int endOffset) throws CollabException {
5061: return new CollabLineRegion(getDocument(), regionName,
5062: beginOffset, endOffset);
5063: }
5064:
5065: /**
5066: * unlock all user regions(ready for removal)
5067: *
5068: */
5069: public void unlockAllUserRegions() {
5070: Vector userRegions = (Vector) getUserRegion(getContext()
5071: .getLoginUser());
5072:
5073: if ((userRegions == null) || (userRegions.size() == 0)) {
5074: return;
5075: }
5076:
5077: for (int i = 0; i < userRegions.size(); i++) {
5078: String regionName = (String) userRegions.get(i);
5079: CollabRegion region = (CollabRegion) getRegion(regionName);
5080: region.setReadyToUnlock();
5081:
5082: UnlockRegionEvent unlockRegionEvent = new UnlockRegionEvent(
5083: new UnlockRegionContext(UnlockRegionEvent
5084: .getEventID(), getFileHandler(),
5085: getFileGroupName()));
5086: getContext().getChannelEventNotifier().notify(
5087: unlockRegionEvent);
5088: }
5089: }
5090:
5091: /**
5092: * doUpdateRegion
5093: *
5094: * @param messageOriginator the sender of this message
5095: * @param sect
5096: * @param text
5097: * @throws CollabException
5098: */
5099: public boolean doUpdateRegion(String messageOriginator,
5100: CollabRegion sect, String text) throws CollabException {
5101: Debug.log("CollabFileHandlerSupport",
5102: "CFHS::sect.isGuarded(): " + sect.isGuarded());
5103: if (!sect.isGuarded()) {
5104: return false;
5105: }
5106:
5107: boolean updateRegionTextStatus = false;
5108:
5109: synchronized (getDocument()) {
5110: setSkipUpdate(true);
5111:
5112: if (currentUpdatedRegion != null) {
5113: //reset region change before update
5114: currentUpdatedRegion = null;
5115: }
5116:
5117: CollabRegionSupport.SimpleSection simpleSection = (CollabRegionSupport.SimpleSection) sect
5118: .getGuard();
5119:
5120: if (simpleSection != null) {
5121: int regionBegin = simpleSection.getBegin();
5122: int diff = text.length()
5123: - simpleSection.getText().length();
5124: if (documentListener != null) {
5125: ((FilesharingDocumentListener) documentListener)
5126: .setSkipUpdate(true);
5127: }
5128:
5129: if (Debug.isEnabled())
5130: Debug.log("CollabFileHandlerSupport", "CFHS, "
5131: + "doUpdateRegion set text: [" + text
5132: + "]");
5133: if (Debug.isEnabled())
5134: Debug.log("CollabFileHandlerSupport", "CFHS, "
5135: + "simpleSection before update: ["
5136: + simpleSection.getText() + "]");
5137:
5138: simpleSection.setText(text);
5139:
5140: if (Debug.isEnabled())
5141: Debug.log("CollabFileHandlerSupport", "CFHS, "
5142: + "simpleSection after update: ["
5143: + simpleSection.getText() + "]");
5144:
5145: if (documentListener != null) {
5146: ((FilesharingDocumentListener) documentListener)
5147: .setSkipUpdate(false);
5148: }
5149: }
5150:
5151: if (currentUpdatedRegion != null) {
5152: currentUpdatedRegion.updateStatusChanged(true);
5153: }
5154:
5155: setCurrentState(FilesharingContext.STATE_UNKNOWN);
5156: setSkipUpdate(false);
5157: }
5158:
5159: return true;
5160: }
5161:
5162: /**
5163: * doUpdateLineRegion
5164: *
5165: * @param regionName the regionName
5166: * @param beginOffset
5167: * @param endOffset
5168: * @param unlockRegionData the intial unlock-region-data Node
5169: * @throws CollabException
5170: */
5171: public List doUpdateLineRegion(String regionName,
5172: int beginOffset, int endOffset,
5173: UnlockRegionData unlockRegionData,
5174: String[] newLineRegionNames) throws CollabException {
5175: List lineRegions = getLineRegions(regionName);
5176: List newLineRegionList = new ArrayList();
5177: StyledDocument fileDocument = getDocument();
5178:
5179: if ((lineRegions != null) && (lineRegions.size() > 0)) {
5180: Vector currentLineRegions = getLineRegion();
5181: Debug.log("CollabFileHandlerSupport",
5182: "CFHS, currentLineRegions ["
5183: + currentLineRegions.size()
5184: + "]: before update: "
5185: + currentLineRegions);//NoI18n
5186:
5187: int beginLine = fileDocument.getDefaultRootElement()
5188: .getElementIndex(beginOffset);
5189: //int endLine = fileDocument.getDefaultRootElement().getElementIndex(endOffset - 1);
5190: int endLine = fileDocument.getDefaultRootElement()
5191: .getElementIndex(endOffset);
5192: Debug.log("CollabFileHandlerSupport",
5193: "CFHS, beginLine: " + beginLine); //NoI18n
5194: Debug.log("CollabFileHandlerSupport", "CFHS, endLine: "
5195: + endLine); //NoI18n
5196:
5197: //save line region that was the begin
5198: CollabLineRegion firstLineRegion = (CollabLineRegion) lineRegions
5199: .get(0);
5200: Debug.log("CollabFileHandlerSupport",
5201: "CFHS, first line regionName: " + //NoI18n
5202: firstLineRegion.getID());
5203:
5204: int saveIndex = currentLineRegions
5205: .indexOf(firstLineRegion.getID());
5206: Debug.log("CollabFileHandlerSupport",
5207: "CFHS, first line saveIndex: " + //NoI18n
5208: saveIndex);
5209:
5210: if ((newLineRegionNames != null)
5211: && (newLineRegionNames.length > 0)) {
5212: endLine = beginLine
5213: + (newLineRegionNames.length - 1);
5214: }
5215:
5216: if (beginLine < 0)
5217: beginLine = 0;
5218: int docLineCount = fileDocument.getDefaultRootElement()
5219: .getElementCount();
5220: if (endLine >= docLineCount)
5221: endLine = docLineCount - 1;
5222:
5223: //remove old line regions
5224: for (int i = 0; i < lineRegions.size(); i++) {
5225: CollabLineRegion lineRegion = (CollabLineRegion) lineRegions
5226: .get(i);
5227:
5228: if (lineRegion != null) {
5229: lineRegion.removeAnnotation();
5230: }
5231: }
5232:
5233: int count = 0;
5234: String user = getContext().getLoginUser();
5235:
5236: for (int lineIndex = beginLine; lineIndex <= endLine; lineIndex++) {
5237: javax.swing.text.Element currentElement = fileDocument
5238: .getDefaultRootElement().getElement(
5239: lineIndex);
5240: String newLineRegionName = null;
5241:
5242: if ((newLineRegionNames == null)
5243: || (newLineRegionNames.length == 0)) {
5244: newLineRegionName = "RA[" + user + "]_"
5245: + getJoinTimeStamp() + "_"
5246: + newLineCount++; //NoI18n
5247: } else {
5248: if (count == newLineRegionNames.length) {
5249: break;
5250: }
5251:
5252: newLineRegionName = newLineRegionNames[count++];
5253: }
5254:
5255: Debug.log("CollabFileHandlerSupport",
5256: "CFHS, newLineRegionName: " + //NoI18n
5257: newLineRegionName);
5258:
5259: int newLineBeginOffset = currentElement
5260: .getStartOffset();
5261: int newLineEndOffset = currentElement
5262: .getEndOffset();
5263:
5264: CollabRegion newLineRegion = createLineRegion(
5265: newLineRegionName, newLineBeginOffset,
5266: newLineEndOffset);
5267:
5268: if (newLineRegion != null) {
5269: newLineRegionList.add(newLineRegion);
5270: Debug.log("CollabFileHandlerSupport",
5271: "CFHS, currentLineRegions size: " + //NoI18n
5272: currentLineRegions.size());
5273:
5274: Debug.log("CollabFileHandlerSupport",
5275: "CollabFileHandlerSupport, insert element "
5276: + //NoI18n
5277: newLineRegionName + " at: "
5278: + saveIndex); //NoI18n
5279: currentLineRegions.insertElementAt(
5280: newLineRegionName, saveIndex++);
5281: addRegion(newLineRegionName, newLineRegion);
5282: }
5283: }
5284:
5285: Debug.log("CollabFileHandlerSupport",
5286: "CFHS, new list: " + getLineRegion()); //NoI18n
5287: resetLineRegion(regionName, newLineRegionList, true);//remove old lines also
5288: replaceLineRegions(currentLineRegions);
5289: Debug.log("CollabFileHandlerSupport",
5290: "CFHS, currentLineRegions ["
5291: + currentLineRegions.size()
5292: + "]: before update: "
5293: + currentLineRegions);//NoI18n
5294: }
5295:
5296: return newLineRegionList;
5297: }
5298:
5299: /**
5300: * test if the region exist in the repository
5301: *
5302: * @param user
5303: * @param offset
5304: * @param length
5305: * @param length of adjacency of change to this region
5306: * @return true/false true if region exist
5307: */
5308: public boolean isUserRegionExist(String user, int offset,
5309: int length, int adjacency) throws CollabException {
5310: /*boolean foundUserRegion=false;
5311: CollabRegion region=getContainingRegion(offset, length, adjacency);
5312: if(region!=null && region.isValid() && region instanceof CollabRegion &&
5313: !(region instanceof CollabLineRegion)) {
5314: Vector userRegions = (Vector)getUserRegion(user);
5315: if(userRegions!=null) {
5316: for(int i=0;i<userRegions.size();i++) {
5317: String regionName = (String)userRegions.get(i);
5318: if(regionName!=null && regionName.equals(region.getID()))
5319: foundUserRegion=true;
5320: }
5321: }
5322:
5323: currentUpdatedRegion=region;
5324: if(!skipUpdate) {
5325: //update status changed
5326: region.updateStatusChanged(true);
5327: }
5328: return foundUserRegion;
5329: }
5330: return foundUserRegion;*/
5331: CollabRegion findUserRegion = getContainingUserRegion(user,
5332: offset, length, adjacency);
5333: if (findUserRegion != null)
5334: return true;
5335:
5336: return false;
5337: }
5338:
5339: /**
5340: * get user region in the repository
5341: *
5342: * @param user
5343: * @param offset
5344: * @param length
5345: * @param length of adjacency of change to this region
5346: * @return true/false true if region exist
5347: */
5348: public CollabRegion getContainingUserRegion(String user,
5349: int offset, int length, int adjacency)
5350: throws CollabException {
5351: CollabRegion findUserRegion = null;
5352: CollabRegion region = getContainingRegion(offset, length,
5353: adjacency);
5354: if (region != null && region.isValid()
5355: && region instanceof CollabRegion
5356: && !(region instanceof CollabLineRegion)) {
5357: Vector userRegions = (Vector) getUserRegion(user);
5358: if (userRegions != null) {
5359: for (int i = 0; i < userRegions.size(); i++) {
5360: String regionName = (String) userRegions.get(i);
5361: if (regionName != null
5362: && regionName.equals(region.getID()))
5363: findUserRegion = region;
5364: }
5365: }
5366:
5367: currentUpdatedRegion = region;
5368: if (!skipUpdate) {
5369: //update status changed
5370: region.updateStatusChanged(true);
5371: }
5372: return findUserRegion;
5373: }
5374: return findUserRegion;
5375: }
5376:
5377: /**
5378: * test if the region exist in the repository
5379: *
5380: * @param offset
5381: * @param length
5382: * @param length of adjacency of change to this region
5383: * @return true/false true if region exist
5384: */
5385: public boolean regionExist(int offset, int length, int adjacency)
5386: throws CollabException {
5387: CollabRegion region = getContainingRegion(offset, length,
5388: adjacency);
5389:
5390: if ((region != null) && region.isValid()
5391: && region instanceof CollabRegion
5392: && !(region instanceof CollabLineRegion)) {
5393: CollabRegion cRegion = (CollabRegion) region;
5394: currentUpdatedRegion = cRegion;
5395:
5396: if (!skipUpdate) {
5397: //update status changed
5398: cRegion.updateStatusChanged(true);
5399: }
5400:
5401: return true;
5402: }
5403:
5404: return false;
5405: }
5406:
5407: public String createUniqueLockID(String userID, String regionID) {
5408: return userID + getName() + regionID;
5409: }
5410:
5411: public LockRegionManager createLockRegionManager(String userID,
5412: LockRegion lockRegion) {
5413: LockRegionManager lrm = null;
5414: LockRegionData[] lockRegionData = lockRegion
5415: .getLockRegionData();
5416: if (lockRegionData != null && lockRegionData.length > 0) {
5417: RegionInfo regionInfo = getLockRegion(lockRegionData[0]);
5418: lrm = createLockRegionManager(userID, regionInfo);
5419: }
5420: return lrm;
5421: }
5422:
5423: public LockRegionManager createLockRegionManager(String userID,
5424: RegionInfo regionInfo) {
5425: LockRegionManager lrm = null;
5426: String lockID = createUniqueLockID(userID, regionInfo
5427: .getID());
5428: synchronized (lrmanagers) {
5429: if (lrmanagers.containsKey(lockID)) {
5430: lrm = (LockRegionManager) lrmanagers.get(lockID);
5431: } else {
5432: lrm = new LockRegionManager(lockID, getContext(),
5433: userID, regionInfo);
5434: lrmanagers.put(lockID, lrm);
5435: }
5436: }
5437: return lrm;
5438: }
5439:
5440: public void removeLockManager(String lockID) {
5441: synchronized (lrmanagers) {
5442: if (lrmanagers.containsKey(lockID)) {
5443: lrmanagers.remove(lockID);
5444: }
5445: }
5446: }
5447: }
5448: }
|