rem
stringlengths 0
477k
| add
stringlengths 0
313k
| context
stringlengths 6
599k
|
---|---|---|
documentJLabel.setText(getString("DocumentLabel.Empty")); | documentNameJLabel.setText(getString("DocumentNameLabel.Empty")); | private void reloadDocument() { documentJLabel.setText(getString("DocumentLabel.Empty")); if(null != input) { final Document document = getDocument(); final Object[] arguments = new Object[] {document.getName()}; documentJLabel.setText(getString("DocumentLabel", arguments)); } } |
documentJLabel.setText(getString("DocumentLabel", arguments)); | documentNameJLabel.setText(getString("DocumentNameLabel", arguments)); | private void reloadDocument() { documentJLabel.setText(getString("DocumentLabel.Empty")); if(null != input) { final Document document = getDocument(); final Object[] arguments = new Object[] {document.getName()}; documentJLabel.setText(getString("DocumentLabel", arguments)); } } |
else { final DocumentVersion version = extractDocumentVersion(); if(version == WorkingVersion.getWorkingVersion()) { getSessionModel().send(contacts, documentId); } else { getSessionModel().send( contacts, documentId, version.getVersionId()); } } | else { getSessionModel().send(contacts, documentId); } | private void sendJButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_sendJButtonActionPerformed if(isInputValid()) { final Long documentId = extractDocumentId(); final List<User> contacts = proxy(extractTeam()); contacts.addAll(proxy(extractContacts())); final Boolean doIncludeKey = extractDoIncludeKey(); toggleVisualFeedback(Boolean.TRUE); try { if(doIncludeKey) { // create a version and send it // update the server key holder final User user = contacts.get(0); // TODO Refactor the user object. final JabberId jabberId = JabberIdBuilder.parseUsername(user.getSimpleUsername()); getSessionModel().sendKeyResponse(documentId, jabberId, KeyResponse.ACCEPT); } else { final DocumentVersion version = extractDocumentVersion(); if(version == WorkingVersion.getWorkingVersion()) { // create a version and send it getSessionModel().send(contacts, documentId); } else { // send a specific version getSessionModel().send( contacts, documentId, version.getVersionId()); } } // NOTE Interesting ArtifactModel.getModel().applyFlagSeen(documentId); } catch(final ParityException px) { throw new RuntimeException(px); } finally { toggleVisualFeedback(Boolean.FALSE); getController().fireDocumentUpdated(documentId); disposeWindow(); } } }//GEN-LAST:event_sendJButtonActionPerformed |
return new ValueParserSub(this, key); | return getString(key); | public Object get(String key) { return new ValueParserSub(this, key); } |
public void addTeamMember(final UUID uniqueId, final JabberId jabberId) throws SmackException { | public void addTeamMember(final UUID uniqueId, final JabberId jabberId) { | public void addTeamMember(final UUID uniqueId, final JabberId jabberId) throws SmackException { xmppArtifact.addTeamMember(uniqueId, jabberId); } |
final JabberId invitedBy) throws SmackException { | final JabberId invitedBy) { | public void declineInvitation(final EMail invitedAs, final JabberId invitedBy) throws SmackException { xmppContact.decline(invitedAs, invitedBy); } |
final Credentials credentials) throws SmackException { | final Credentials credentials) { | public void login(final Environment environment, final Credentials credentials) throws SmackException { login(1, environment, credentials); } |
public void publish(ContainerVersion container, Map<DocumentVersion, InputStream> documents, List<JabberId> publishTo, JabberId publishedBy, Calendar publishedOn) throws SmackException { | public void publish(ContainerVersion container, Map<DocumentVersion, InputStream> documents, List<JabberId> publishTo, JabberId publishedBy, Calendar publishedOn) { | public void publish(ContainerVersion container, Map<DocumentVersion, InputStream> documents, List<JabberId> publishTo, JabberId publishedBy, Calendar publishedOn) throws SmackException { try { xmppContainer.publish(container, documents, publishTo, publishedBy, publishedOn); } catch (final IOException iox) { throw XMPPErrorTranslator.translate(iox); } } |
throw XMPPErrorTranslator.translate(iox); | throw translateError(iox); | public void publish(ContainerVersion container, Map<DocumentVersion, InputStream> documents, List<JabberId> publishTo, JabberId publishedBy, Calendar publishedOn) throws SmackException { try { xmppContainer.publish(container, documents, publishTo, publishedBy, publishedOn); } catch (final IOException iox) { throw XMPPErrorTranslator.translate(iox); } } |
public User readCurrentUser() throws SmackException { | public User readCurrentUser() { | public User readCurrentUser() throws SmackException { assertLoggedIn("[LMODEL] [XMPP] [READ CURRENT USER] [NO SESSION]"); final String qualifiedJabberId = xmppConnection.getUser(); final JabberId jabberId = JabberIdBuilder.parseQualifiedJabberId(qualifiedJabberId); return xmppUser.read(jabberId); } |
public Profile readProfile() throws SmackException { | public Profile readProfile() { | public Profile readProfile() throws SmackException { assertLoggedIn("[LMODEL] [XMPP] [READ PROFILE] [USER NOT ONLINE]"); return xmppProfile.read(getJabberId()); } |
final List<JabberId> sendTo, final JabberId sentBy, final Calendar sentOn) throws SmackException { | final List<JabberId> sendTo, final JabberId sentBy, final Calendar sentOn) { | public void send(final ContainerVersion container, final Map<DocumentVersion, InputStream> documents, final List<JabberId> sendTo, final JabberId sentBy, final Calendar sentOn) throws SmackException { try { xmppContainer.send(container, documents, sendTo, sentBy, sentOn); } catch (final IOException iox) { throw XMPPErrorTranslator.translate(iox); } } |
throw XMPPErrorTranslator.translate(iox); | throw translateError(iox); | public void send(final ContainerVersion container, final Map<DocumentVersion, InputStream> documents, final List<JabberId> sendTo, final JabberId sentBy, final Calendar sentOn) throws SmackException { try { xmppContainer.send(container, documents, sendTo, sentBy, sentOn); } catch (final IOException iox) { throw XMPPErrorTranslator.translate(iox); } } |
public void sendLogFileArchive(final File logFileArchive, final User user) throws SmackException { | public void sendLogFileArchive(final File logFileArchive, final User user) { | public void sendLogFileArchive(final File logFileArchive, final User user) throws SmackException { logger.logApiId(); logger.logVariable("logFileArchive", logFileArchive); logger.logVariable("user", user); } |
XMPPErrorTranslator.translateUnchecked(this, "UPDATE PROFILE CREDENTIALS", t); | throw translateError(t); | public void updateProfileCredentials(final JabberId userId, final Credentials credentials) { try { Assert.assertTrue("CAN ONLY UPDATE PROFILE CREDENTIALS", userId.equals(getJabberId())); final AccountManager accountManager = new AccountManager(xmppConnection); accountManager.changePassword(credentials.getPassword()); } catch (final Throwable t) { XMPPErrorTranslator.translateUnchecked(this, "UPDATE PROFILE CREDENTIALS", t); } } |
return Class.forName(this.fieldType); | return ReflectionUtils.forName(this.fieldType); | private Class loadFieldTypeClass() { if (this.fieldType == null) { return null; } if ("byte".equals(this.fieldType)) { return byte.class; } else if ("short".equals(this.fieldType)) { return short.class; } else if ("int".equals(this.fieldType)) { return int.class; } else if ("long".equals(this.fieldType)) { return long.class; } else if ("float".equals(this.fieldType)) { return float.class; } else if ("double".equals(this.fieldType)) { return double.class; } else if ("char".equals(this.fieldType)) { return char.class; } else if ("boolean".equals(this.fieldType)) { return boolean.class; } else { try { return Class.forName(this.fieldType); } catch (ClassNotFoundException cnfe) { ; // nothing to do; it will be dynamically determined } } return null; } |
catch (ClassNotFoundException cnfe) { | catch (JcrMappingException jme) { | private Class loadFieldTypeClass() { if (this.fieldType == null) { return null; } if ("byte".equals(this.fieldType)) { return byte.class; } else if ("short".equals(this.fieldType)) { return short.class; } else if ("int".equals(this.fieldType)) { return int.class; } else if ("long".equals(this.fieldType)) { return long.class; } else if ("float".equals(this.fieldType)) { return float.class; } else if ("double".equals(this.fieldType)) { return double.class; } else if ("char".equals(this.fieldType)) { return char.class; } else if ("boolean".equals(this.fieldType)) { return boolean.class; } else { try { return Class.forName(this.fieldType); } catch (ClassNotFoundException cnfe) { ; // nothing to do; it will be dynamically determined } } return null; } |
System.out.println("notationDecl(" + name + ", " + publicId + ", " + systemId + ");"); | public void notationDecl(String name, String publicId, String systemId) throws SAXException { System.out.println("notationDecl(" + name + ", " + publicId + ", " + systemId + ");"); } |
|
XMLNode newNode = new XMLNode(namespaceURI, sName, qName, attributes, currentNode); currentNode.addChild(newNode); currentNode = newNode; | startElementInternal(namespaceURI, sName, qName, attributes); | public void startElement(String namespaceURI, String sName, String qName, Attributes attrs) throws SAXException { //System.out.println("SE"); Attribute[] attributes = new Attribute[attrs.getLength()]; for(int i = 0; i < attributes.length; ++i) { attributes[i] = new Attribute(attrs.getLocalName(i), attrs.getQName(i), attrs.getType(i), attrs.getURI(i), attrs.getValue(i)); } XMLNode newNode = new XMLNode(namespaceURI, sName, qName, attributes, currentNode); currentNode.addChild(newNode); currentNode = newNode; } |
return va1.getDependencies().size() - va2.getDependencies().size(); | return va1.getDependencyList().size() - va2.getDependencyList().size(); | public int compare(Object o1, Object o2) { ValidatorAction va1 = (ValidatorAction)o1; ValidatorAction va2 = (ValidatorAction)o2; String vad1 = va1.getDepends(); String vad2 = va2.getDepends(); if ((vad1 == null || vad1.length() == 0) && (vad2 == null || vad2.length() == 0)) { return 0; } else if ((vad1 != null && vad1.length() > 0) && (vad2 == null || vad2.length() == 0)) { return 1; } else if ((vad1 == null || vad1.length() == 0) && (vad2 != null && vad2.length() > 0)) { return -1; } else { return va1.getDependencies().size() - va2.getDependencies().size(); } } |
for (Iterator x = field.getDependencies().iterator(); x.hasNext();) | for (Iterator x = field.getDependencyList().iterator(); x.hasNext();) | protected List createActionList(ValidatorResources resources, Form form) { List actionMethods = new ArrayList(); // Get List of actions for this Form for (Iterator i = form.getFields().iterator(); i.hasNext();) { Field field = (Field)i.next(); for (Iterator x = field.getDependencies().iterator(); x.hasNext();) { Object o = x.next(); if (o != null && !actionMethods.contains(o)) { actionMethods.add(o); } } } List actions = new ArrayList(); // Create list of ValidatorActions based on actionMethods for (Iterator i = actionMethods.iterator(); i.hasNext();) { String depends = (String) i.next(); ValidatorAction va = resources.getValidatorAction(depends); // throw nicer NPE for easier debugging if (va == null) { throw new NullPointerException( "Depends string \"" + depends + "\" was not found in validator-rules.xml."); } String javascript = va.getJavascript(); if (javascript != null && javascript.length() > 0) { actions.add(va); } else { i.remove(); } } //TODO? make an instance of this class a static member Comparator comp = new ValidatorActionComparator(); Collections.sort(actions, comp); return actions; } |
ModuleConfig mconfig = RequestUtils.getModuleConfig(request, app); | ModuleConfig mconfig = ModuleUtils.getInstance().getModuleConfig(request, app); | public void init(Object obj) { if (!(obj instanceof ViewContext)) { throw new IllegalArgumentException( "Tool can only be initialized with a ViewContext"); } this.context = (ViewContext)obj; this.request = context.getRequest(); this.session = request.getSession(false); this.app = context.getServletContext(); Boolean b = (Boolean)context.getAttribute(ViewContext.XHTML); if (b != null) { this.xhtml = b.booleanValue(); } /* Is there a mapping associated with this request? */ ActionConfig config = (ActionConfig)request.getAttribute(Globals.MAPPING_KEY); if (config != null) { /* Is there a form bean associated with this mapping? */ this.formName = config.getAttribute(); } ModuleConfig mconfig = RequestUtils.getModuleConfig(request, app); this.resources = (ValidatorResources)app.getAttribute(ValidatorPlugIn. VALIDATOR_KEY + mconfig.getPrefix()); } |
final void setParameter(final String name, final byte[] value) { | public final void setParameter(final String name, final byte[] value) { | final void setParameter(final String name, final byte[] value) { parameters.add(new Parameter(name, byte[].class, value)); } |
throw Assert.createUnreachable("[UNKNOWN CONNECTION]"); | throw Assert.createUnreachable("Unknown connection."); | private void setIcon() { switch(systemApplication.getConnection()) { case OFFLINE: systemTrayIcon.setIcon(Icons.Tray.TRAY_ICON_OFFLINE); break; case ONLINE: systemTrayIcon.setIcon(Icons.Tray.TRAY_ICON_ONLINE); default: throw Assert.createUnreachable("[UNKNOWN CONNECTION]"); } } |
SAXParser saxParser = SAXParserFactory.newInstance().newSAXParser(); try { saxParser.parse(is, handler); } catch(SAXException se) { se.printStackTrace(); System.err.println("Could not read the partition list... exiting."); System.exit(1); | if(useSaxParser) { SAXParser saxParser = SAXParserFactory.newInstance().newSAXParser(); try { if(verbose) printSAXParserInfo(saxParser.getXMLReader(), System.out, ""); saxParser.parse(is, handler); } catch(SAXException se) { se.printStackTrace(); System.err.println("Could not read the partition list... exiting."); System.exit(1); } } else { try { Ass encodingParser = Ass.create(new InputStreamReader(is, "US-ASCII"), new NullXMLContentHandler()); String encoding = encodingParser.xmlDecl(); if(verbose) System.out.println("XML Encoding: " + encoding); if(encoding == null) encoding = "US-ASCII"; is = new ByteArrayInputStream(buffer); Reader usedReader = new BufferedReader(new InputStreamReader(is, encoding)); Ass assParser = Ass.create(usedReader, new NodeBuilderContentHandler(handler)); assParser.xmlDocument(); } catch(ParseException pe) { println("Could not read the partition list... exiting."); System.exit(1); } | public static void notmain(String[] args) throws Exception { if(debug) verbose = true; parseArgs(args); printlnVerbose("Processing: " + dmgFile); RandomAccessFile dmgRaf = new RandomAccessFile(dmgFile, "r"); RandomAccessFile isoRaf = null; boolean testOnly = false; if(isoFile != null) { isoRaf = new RandomAccessFile(isoFile, "rw"); isoRaf.setLength(0); printlnVerbose("Extracting to: " + isoFile); } else { testOnly = true; printlnVerbose("Simulating extraction..."); } dmgRaf.seek(dmgRaf.length()-PLIST_ADDRESS_1); long plistBegin1 = dmgRaf.readLong(); long plistEnd = dmgRaf.readLong(); dmgRaf.seek(dmgRaf.length()-PLIST_ADDRESS_2); long plistBegin2 = dmgRaf.readLong(); long plistSize = dmgRaf.readLong(); if(debug) { println("Read addresses:", " " + plistBegin1, " " + plistBegin2); } if(plistBegin1 != plistBegin2) { println("ERROR: Addresses not equal! Assumption false.", plistBegin1 + " != " + plistBegin2); System.exit(0); } if(false && plistSize != (plistEnd-plistBegin1)) { // This assumption is proven false. plistEnd is not interpreted correctly println("NOTE: plistSize field does not match plistEnd marker. Assumption false.", "plistSize=" + plistSize + " plistBegin1=" + plistBegin1 + " plistEnd=" + plistEnd + " plistEnd-plistBegin1=" + (plistEnd-plistBegin1)); } printlnVerbose("Jumping to address..."); dmgRaf.seek(plistBegin1); byte[] buffer = new byte[(int)plistSize]; dmgRaf.read(buffer); InputStream is = new ByteArrayInputStream(buffer); NodeBuilder handler = new NodeBuilder(); SAXParser saxParser = SAXParserFactory.newInstance().newSAXParser(); try {// System.out.println("validation: " + saxParser.getProperty("validation"));// System.out.println("external-general-entities: " + saxParser.getProperty("external-general-entities"));// System.out.println("external-parameter-entities: " + saxParser.getProperty("external-parameter-entities"));// System.out.println("is-standalone: " + saxParser.getProperty("is-standalone"));// System.out.println("lexical-handler: " + saxParser.getProperty("lexical-handler"));// System.out.println("parameter-entities: " + saxParser.getProperty("parameter-entities"));// System.out.println("namespaces: " + saxParser.getProperty("namespaces"));// System.out.println("namespace-prefixes: " + saxParser.getProperty("namespace-prefixes"));// System.out.println(": " + saxParser.getProperty(""));// System.out.println(": " + saxParser.getProperty(""));// System.out.println(": " + saxParser.getProperty(""));// System.out.println(": " + saxParser.getProperty(""));// System.out.println("" + saxParser.getProperty(""));// System.out.println("" + saxParser.getProperty(""));// System.out.println("" + saxParser.getProperty(""));// System.out.println("" + saxParser.getProperty(""));// System.out.println("" + saxParser.getProperty(""));// System.out.println("" + saxParser.getProperty(""));// System.out.println("" + saxParser.getProperty(""));// System.out.println("" + saxParser.getProperty("")); //System.out.println("isValidating: " + saxParser.isValidating()); saxParser.parse(is, handler); } catch(SAXException se) { se.printStackTrace(); System.err.println("Could not read the partition list... exiting."); System.exit(1); } XMLNode[] rootNodes = handler.getRoots(); if(rootNodes.length != 1) { println("Could not parse DMG-file!"); System.exit(0); } /* Ok, now we have a tree built from the XML-document. Let's walk to the right place. */ /* cd plist cd dict cdkey resource-fork (type:dict) cdkey blkx (type:array) */ XMLNode current; XMLElement[] children; boolean keyFound; current = rootNodes[0]; //We are at plist... probably (there should be only one root node) current = current.cd("dict"); current = current.cdkey("resource-fork"); current = current.cdkey("blkx"); printlnVerbose("Found " + current.getChildren().length + " partitions:"); byte[] inBuffer = new byte[0x40000]; byte[] outBuffer = new byte[0x40000]; byte[] zeroblock = new byte[4096]; /* I think java always zeroes its arrays on creation... but let's play safe. */ for(int y = 0; y < zeroblock.length; ++y) zeroblock[y] = 0; LinkedList<DMGBlock> blocks = new LinkedList<DMGBlock>(); long elementNumber = 0; //long lastOffs = 0; long lastOutOffset = 0; long lastInOffset = 0; long totalSize = 0; int errorsReported = 0; int warningsReported = 0; reportProgress(0); for(XMLElement xe : current.getChildren()) { if(progmon != null && progmon.isCanceled()) System.exit(0); if(xe instanceof XMLNode) { XMLNode xn = (XMLNode)xe; byte[] data = Base64.decode(xn.getKeyValue("Data")); long partitionSize = calculatePartitionSize(data); totalSize += partitionSize; printlnVerbose(" " + xn.getKeyValue("Name")); printlnVerbose(" ID: " + xn.getKeyValue("ID")); printlnVerbose(" Attributes: " + xn.getKeyValue("Attributes")); printlnVerbose(" Partition map data length: " + data.length + " bytes"); printlnVerbose(" Partition size: " + partitionSize + " bytes"); if(debug) { File dumpFile = new File("data(" + xn.getKeyValue("ID") + ").bin"); println(" Dumping partition map to file: " + dumpFile); FileOutputStream dump = new FileOutputStream(dumpFile); dump.write(data); dump.close(); } int offset = 0xCC; int blockType = 0; /* Offset of the input data for the current block in the input file */ long inOffset = 0; /* Size of the input data for the current block */ long inSize = 0; /* Offset of the output data for the current block in the output file */ long outOffset = 0; /* Size of the output data (possibly larger than inSize because of decompression, zero expansion...) */ long outSize = 0; long lastByteReadInBlock = -1; boolean addInOffset = false; //, lastInOffs = 0; int blockCount = 0; while(blockType != BT_END) { if(progmon != null && progmon.isCanceled()) System.exit(0); DataInputStream dis = new DataInputStream(new ByteArrayInputStream(data)); int bytesSkipped = 0; while(bytesSkipped < offset) bytesSkipped += dis.skipBytes(offset-bytesSkipped); blockType = dis.readInt(); int skipped = dis.readInt(); //Skip 4 bytes forward outOffset = dis.readLong()*0x200;//(dis.readInt() & 0xffffffffL)*0x200; //unsigned int -> long //dis.readInt(); //Skip 4 bytes forward outSize = dis.readLong()*0x200;//(dis.readInt() & 0xffffffffL)*0x200; //unsigned int -> long inOffset = dis.readLong();// & 0xffffffffL; //unsigned int -> long //dis.readInt(); //Skip 4 bytes forward inSize = dis.readLong();//dis.readInt() & 0xffffffffL; //unsigned int -> long String blockTypeString = blockTypeToString(blockType); if(debug) println(" " + elementNumber + ":" + blockCount + ". " + blockTypeString + " processing..."); if(lastByteReadInBlock == -1) lastByteReadInBlock = inOffset; lastByteReadInBlock += inSize; /* The lines below are a "hack" that I had to do to make dmgx work with certain dmg-files. I don't understand the issue at all, which is why this hack is here, but sometimes inOffset == 0 means that it is 0 relative to the previous partition's last inOffset. And sometimes it doesn't (meaning the actual position 0 in the dmg file). */ if(addInOffset) { if(debug) println("------->NOTE: addInOffset mode: inOffset tranformation " + inOffset + "->" + (inOffset+lastInOffset)); inOffset += lastInOffset; } else if(inOffset == 0 && blockCount == 0) { if(debug) println("------->NOTE: Detected inOffset == 0, setting to " + lastInOffset); addInOffset = true; inOffset = lastInOffset; } outOffset += lastOutOffset; DMGBlock currentBlock = new DMGBlock(blockType, skipped, outOffset, outSize, inOffset, inSize); blocks.add(currentBlock); if(debug) { println(" outOffset=" + outOffset + " outSize=" + outSize + " inOffset=" + inOffset, " inSize=" + inSize + " lastOutOffset=" + lastOutOffset + " lastInOffset=" + lastInOffset /*+ " lastInOffs=" + lastInOffs + " lastOffs=" + lastOffs*/); } if(blockType == BT_ADC) { println("!------>ERROR: BT_ADC not supported."); ++errorsReported; if(!testOnly) System.exit(0); } else if(blockType == BT_ZLIB) {// if(debug)// println(" " + elementNumber + ":" + blockCount + ". BT_ZLIB processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) println("!------>WARNING: BT_ZLIB FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); try { DMGBlockHandlers.processZlibBlock(currentBlock, dmgRaf, isoRaf, testOnly, dummyMonitor); } catch(DataFormatException dfe) { println("!------>ERROR: BT_ZLIB Could not decode..."); ++errorsReported; if(!debug) { println("!------> outOffset=" + outOffset + " outSize=" + outSize + " inOffset=" + inOffset + " inSize=" + inSize + " lastOutOffset=" + lastOutOffset + " lastInOffset=" + lastInOffset); } dfe.printStackTrace(); if(!testOnly) System.exit(0); else { println("!------> Testing mode, so continuing..."); //System.exit(0); break; } } } else if(blockType == BT_BZIP2) { println("!------>ERROR: BT_BZIP2 not currently supported."); ++errorsReported; if(!testOnly) System.exit(0); } else if(blockType == BT_COPY) {// if(debug)// println(" " + elementNumber + ":" + blockCount + ". BT_COPY processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) { println("!------>WARNING: BT_COPY FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); ++warningsReported; } dmgRaf.seek(/*lastOffs+*/inOffset); int bytesRead = dmgRaf.read(inBuffer, 0, Math.min((int)inSize, inBuffer.length)); long totalBytesRead = bytesRead; while(bytesRead != -1) { reportFilePointerProgress(dmgRaf); if(!testOnly) isoRaf.write(inBuffer, 0, bytesRead); if(totalBytesRead >= inSize) break; bytesRead = dmgRaf.read(inBuffer, 0, Math.min((int)(inSize-totalBytesRead), inBuffer.length)); if(bytesRead > 0) totalBytesRead += bytesRead; } //lastInOffs = inOffset+inSize; } else if(blockType == BT_ZERO) {// if(debug)// println(" " + elementNumber + ":" + blockCount + ". BT_ZERO processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) { println("!------>WARNING: BT_ZERO FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); ++warningsReported; } reportFilePointerProgress(dmgRaf); long numberOfZeroBlocks = outSize/zeroblock.length; int numberOfRemainingBytes = (int)(outSize%zeroblock.length); for(int j = 0; j < numberOfZeroBlocks; ++j) { if(!testOnly) isoRaf.write(zeroblock); } if(!testOnly) isoRaf.write(zeroblock, 0, numberOfRemainingBytes); //lastInOffs = inOffset+inSize; } else if(blockType == BT_ZERO2) {// if(debug)// println(" " + elementNumber + ":" + blockCount + ". BT_ZERO2 processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) { println("!------>WARNING: BT_ZERO2 FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); ++warningsReported; } reportFilePointerProgress(dmgRaf); long numberOfZeroBlocks = outSize/zeroblock.length; int numberOfRemainingBytes = (int)(outSize%zeroblock.length); for(int j = 0; j < numberOfZeroBlocks; ++j) { if(!testOnly) isoRaf.write(zeroblock); } if(!testOnly) isoRaf.write(zeroblock, 0, numberOfRemainingBytes); //lastInOffs = inOffset+inSize; } else if(blockType == BT_UNKNOWN) { /* I have no idea what this blocktype is... but it's common, and usually doesn't appear more than 2-3 times in a dmg. As long as its input and output sizes are 0, there's no reason to complain... is there? */// if(debug)// println(" " + elementNumber + ":" + blockCount + ". BT_UNKNOWN processing..."); if(!(inSize == 0 && outSize == 0)) { println("!------>WARNING: Blocktype BT_UNKNOWN had non-zero sizes...", "!------> inSize=" + inSize + ", outSize=" + outSize); ++warningsReported; //println(" The author of the program would be pleased if you contacted him about this."); // ...or would I? } } else if(blockType == BT_END) {// if(debug)// println(" " + elementNumber + ":" + blockCount + ". BT_END processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) { println("!------>WARNING: BT_END FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); ++warningsReported; } //lastOffs += lastInOffs; lastOutOffset = outOffset; lastInOffset += lastByteReadInBlock; } else { println("!------>WARNING: previously unseen blocktype " + blockType + " [0x" + Integer.toHexString(blockType) + "]", "!------> outOffset=" + outOffset + " outSize=" + outSize + " inOffset=" + inOffset + " inSize=" + inSize); ++warningsReported; if(!testOnly && isoRaf.getFilePointer() != outOffset) println("!------>WARNING: unknown blocktype FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); } offset += 0x28; ++blockCount; } } ++elementNumber; } //printlnVerbose("Progress: 100% Done!"); reportProgress(100); String summary = (errorsReported != 0)?errorsReported+" errors reported":"No errors reported"; summary += (warningsReported != 0)?" ("+warningsReported+" warnings emitted).":"."; if(!graphical) { newline(); println(summary); printlnVerbose("Total extracted bytes: " + totalSize + " B"); } else { progmon.close(); JOptionPane.showMessageDialog(null, "Extraction complete! " + summary + "\n" + "Total extracted bytes: " + totalSize + " B", "Information", JOptionPane.INFORMATION_MESSAGE); System.exit(0); } if(!debug) { if(isoRaf != null) isoRaf.close(); dmgRaf.close(); } else { if(isoRaf != null) isoRaf.close();// System.out.println("blocks.size()=" + blocks.size());// for(DMGBlock b : blocks)// System.out.println(" " + b.toString()); LinkedList<DMGBlock> merged = mergeBlocks(blocks);// System.out.println("merged.size()=" + merged.size());// for(DMGBlock b : merged)// System.out.println(" " + b.toString()); println("Extracting all the parts not containing block data from source file:"); int i = 1; DMGBlock previous = null; for(DMGBlock b : merged) { if(previous == null && b.inOffset > 0) { String filename = i++ + ".block"; println(" " + new File(filename).getCanonicalPath() + "..."); FileOutputStream curFos = new FileOutputStream(new File(filename)); dmgRaf.seek(0); byte[] data = new byte[(int)(b.inOffset)]; dmgRaf.read(data); curFos.write(data); curFos.close(); } else if(previous != null) { String filename = i++ + ".block"; println(" " + new File(filename).getCanonicalPath() + "..."); FileOutputStream curFos = new FileOutputStream(new File(filename)); dmgRaf.seek(previous.inOffset+previous.inSize); byte[] data = new byte[(int)(b.inOffset-(previous.inOffset+previous.inSize))]; dmgRaf.read(data); curFos.write(data); curFos.close(); } previous = b; } if(previous.inOffset+previous.inSize != dmgRaf.length()) { String filename = i++ + ".block"; println(" " + new File(filename).getCanonicalPath() + "..."); FileOutputStream curFos = new FileOutputStream(new File(filename)); dmgRaf.seek(previous.inOffset+previous.inSize); byte[] data = new byte[(int)(dmgRaf.length()-(previous.inOffset+previous.inSize))]; dmgRaf.read(data); curFos.write(data); curFos.close(); } dmgRaf.close(); System.out.println("done!"); } } |
println("Could not parse DMG-file!"); | println("Could not parse UDIF-file!"); | public static void notmain(String[] args) throws Exception { if(debug) verbose = true; parseArgs(args); printlnVerbose("Processing: " + dmgFile); RandomAccessFile dmgRaf = new RandomAccessFile(dmgFile, "r"); RandomAccessFile isoRaf = null; boolean testOnly = false; if(isoFile != null) { isoRaf = new RandomAccessFile(isoFile, "rw"); isoRaf.setLength(0); printlnVerbose("Extracting to: " + isoFile); } else { testOnly = true; printlnVerbose("Simulating extraction..."); } dmgRaf.seek(dmgRaf.length()-PLIST_ADDRESS_1); long plistBegin1 = dmgRaf.readLong(); long plistEnd = dmgRaf.readLong(); dmgRaf.seek(dmgRaf.length()-PLIST_ADDRESS_2); long plistBegin2 = dmgRaf.readLong(); long plistSize = dmgRaf.readLong(); if(debug) { println("Read addresses:", " " + plistBegin1, " " + plistBegin2); } if(plistBegin1 != plistBegin2) { println("ERROR: Addresses not equal! Assumption false.", plistBegin1 + " != " + plistBegin2); System.exit(0); } if(false && plistSize != (plistEnd-plistBegin1)) { // This assumption is proven false. plistEnd is not interpreted correctly println("NOTE: plistSize field does not match plistEnd marker. Assumption false.", "plistSize=" + plistSize + " plistBegin1=" + plistBegin1 + " plistEnd=" + plistEnd + " plistEnd-plistBegin1=" + (plistEnd-plistBegin1)); } printlnVerbose("Jumping to address..."); dmgRaf.seek(plistBegin1); byte[] buffer = new byte[(int)plistSize]; dmgRaf.read(buffer); InputStream is = new ByteArrayInputStream(buffer); NodeBuilder handler = new NodeBuilder(); SAXParser saxParser = SAXParserFactory.newInstance().newSAXParser(); try {// System.out.println("validation: " + saxParser.getProperty("validation"));// System.out.println("external-general-entities: " + saxParser.getProperty("external-general-entities"));// System.out.println("external-parameter-entities: " + saxParser.getProperty("external-parameter-entities"));// System.out.println("is-standalone: " + saxParser.getProperty("is-standalone"));// System.out.println("lexical-handler: " + saxParser.getProperty("lexical-handler"));// System.out.println("parameter-entities: " + saxParser.getProperty("parameter-entities"));// System.out.println("namespaces: " + saxParser.getProperty("namespaces"));// System.out.println("namespace-prefixes: " + saxParser.getProperty("namespace-prefixes"));// System.out.println(": " + saxParser.getProperty(""));// System.out.println(": " + saxParser.getProperty(""));// System.out.println(": " + saxParser.getProperty(""));// System.out.println(": " + saxParser.getProperty(""));// System.out.println("" + saxParser.getProperty(""));// System.out.println("" + saxParser.getProperty(""));// System.out.println("" + saxParser.getProperty(""));// System.out.println("" + saxParser.getProperty(""));// System.out.println("" + saxParser.getProperty(""));// System.out.println("" + saxParser.getProperty(""));// System.out.println("" + saxParser.getProperty(""));// System.out.println("" + saxParser.getProperty("")); //System.out.println("isValidating: " + saxParser.isValidating()); saxParser.parse(is, handler); } catch(SAXException se) { se.printStackTrace(); System.err.println("Could not read the partition list... exiting."); System.exit(1); } XMLNode[] rootNodes = handler.getRoots(); if(rootNodes.length != 1) { println("Could not parse DMG-file!"); System.exit(0); } /* Ok, now we have a tree built from the XML-document. Let's walk to the right place. */ /* cd plist cd dict cdkey resource-fork (type:dict) cdkey blkx (type:array) */ XMLNode current; XMLElement[] children; boolean keyFound; current = rootNodes[0]; //We are at plist... probably (there should be only one root node) current = current.cd("dict"); current = current.cdkey("resource-fork"); current = current.cdkey("blkx"); printlnVerbose("Found " + current.getChildren().length + " partitions:"); byte[] inBuffer = new byte[0x40000]; byte[] outBuffer = new byte[0x40000]; byte[] zeroblock = new byte[4096]; /* I think java always zeroes its arrays on creation... but let's play safe. */ for(int y = 0; y < zeroblock.length; ++y) zeroblock[y] = 0; LinkedList<DMGBlock> blocks = new LinkedList<DMGBlock>(); long elementNumber = 0; //long lastOffs = 0; long lastOutOffset = 0; long lastInOffset = 0; long totalSize = 0; int errorsReported = 0; int warningsReported = 0; reportProgress(0); for(XMLElement xe : current.getChildren()) { if(progmon != null && progmon.isCanceled()) System.exit(0); if(xe instanceof XMLNode) { XMLNode xn = (XMLNode)xe; byte[] data = Base64.decode(xn.getKeyValue("Data")); long partitionSize = calculatePartitionSize(data); totalSize += partitionSize; printlnVerbose(" " + xn.getKeyValue("Name")); printlnVerbose(" ID: " + xn.getKeyValue("ID")); printlnVerbose(" Attributes: " + xn.getKeyValue("Attributes")); printlnVerbose(" Partition map data length: " + data.length + " bytes"); printlnVerbose(" Partition size: " + partitionSize + " bytes"); if(debug) { File dumpFile = new File("data(" + xn.getKeyValue("ID") + ").bin"); println(" Dumping partition map to file: " + dumpFile); FileOutputStream dump = new FileOutputStream(dumpFile); dump.write(data); dump.close(); } int offset = 0xCC; int blockType = 0; /* Offset of the input data for the current block in the input file */ long inOffset = 0; /* Size of the input data for the current block */ long inSize = 0; /* Offset of the output data for the current block in the output file */ long outOffset = 0; /* Size of the output data (possibly larger than inSize because of decompression, zero expansion...) */ long outSize = 0; long lastByteReadInBlock = -1; boolean addInOffset = false; //, lastInOffs = 0; int blockCount = 0; while(blockType != BT_END) { if(progmon != null && progmon.isCanceled()) System.exit(0); DataInputStream dis = new DataInputStream(new ByteArrayInputStream(data)); int bytesSkipped = 0; while(bytesSkipped < offset) bytesSkipped += dis.skipBytes(offset-bytesSkipped); blockType = dis.readInt(); int skipped = dis.readInt(); //Skip 4 bytes forward outOffset = dis.readLong()*0x200;//(dis.readInt() & 0xffffffffL)*0x200; //unsigned int -> long //dis.readInt(); //Skip 4 bytes forward outSize = dis.readLong()*0x200;//(dis.readInt() & 0xffffffffL)*0x200; //unsigned int -> long inOffset = dis.readLong();// & 0xffffffffL; //unsigned int -> long //dis.readInt(); //Skip 4 bytes forward inSize = dis.readLong();//dis.readInt() & 0xffffffffL; //unsigned int -> long String blockTypeString = blockTypeToString(blockType); if(debug) println(" " + elementNumber + ":" + blockCount + ". " + blockTypeString + " processing..."); if(lastByteReadInBlock == -1) lastByteReadInBlock = inOffset; lastByteReadInBlock += inSize; /* The lines below are a "hack" that I had to do to make dmgx work with certain dmg-files. I don't understand the issue at all, which is why this hack is here, but sometimes inOffset == 0 means that it is 0 relative to the previous partition's last inOffset. And sometimes it doesn't (meaning the actual position 0 in the dmg file). */ if(addInOffset) { if(debug) println("------->NOTE: addInOffset mode: inOffset tranformation " + inOffset + "->" + (inOffset+lastInOffset)); inOffset += lastInOffset; } else if(inOffset == 0 && blockCount == 0) { if(debug) println("------->NOTE: Detected inOffset == 0, setting to " + lastInOffset); addInOffset = true; inOffset = lastInOffset; } outOffset += lastOutOffset; DMGBlock currentBlock = new DMGBlock(blockType, skipped, outOffset, outSize, inOffset, inSize); blocks.add(currentBlock); if(debug) { println(" outOffset=" + outOffset + " outSize=" + outSize + " inOffset=" + inOffset, " inSize=" + inSize + " lastOutOffset=" + lastOutOffset + " lastInOffset=" + lastInOffset /*+ " lastInOffs=" + lastInOffs + " lastOffs=" + lastOffs*/); } if(blockType == BT_ADC) { println("!------>ERROR: BT_ADC not supported."); ++errorsReported; if(!testOnly) System.exit(0); } else if(blockType == BT_ZLIB) {// if(debug)// println(" " + elementNumber + ":" + blockCount + ". BT_ZLIB processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) println("!------>WARNING: BT_ZLIB FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); try { DMGBlockHandlers.processZlibBlock(currentBlock, dmgRaf, isoRaf, testOnly, dummyMonitor); } catch(DataFormatException dfe) { println("!------>ERROR: BT_ZLIB Could not decode..."); ++errorsReported; if(!debug) { println("!------> outOffset=" + outOffset + " outSize=" + outSize + " inOffset=" + inOffset + " inSize=" + inSize + " lastOutOffset=" + lastOutOffset + " lastInOffset=" + lastInOffset); } dfe.printStackTrace(); if(!testOnly) System.exit(0); else { println("!------> Testing mode, so continuing..."); //System.exit(0); break; } } } else if(blockType == BT_BZIP2) { println("!------>ERROR: BT_BZIP2 not currently supported."); ++errorsReported; if(!testOnly) System.exit(0); } else if(blockType == BT_COPY) {// if(debug)// println(" " + elementNumber + ":" + blockCount + ". BT_COPY processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) { println("!------>WARNING: BT_COPY FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); ++warningsReported; } dmgRaf.seek(/*lastOffs+*/inOffset); int bytesRead = dmgRaf.read(inBuffer, 0, Math.min((int)inSize, inBuffer.length)); long totalBytesRead = bytesRead; while(bytesRead != -1) { reportFilePointerProgress(dmgRaf); if(!testOnly) isoRaf.write(inBuffer, 0, bytesRead); if(totalBytesRead >= inSize) break; bytesRead = dmgRaf.read(inBuffer, 0, Math.min((int)(inSize-totalBytesRead), inBuffer.length)); if(bytesRead > 0) totalBytesRead += bytesRead; } //lastInOffs = inOffset+inSize; } else if(blockType == BT_ZERO) {// if(debug)// println(" " + elementNumber + ":" + blockCount + ". BT_ZERO processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) { println("!------>WARNING: BT_ZERO FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); ++warningsReported; } reportFilePointerProgress(dmgRaf); long numberOfZeroBlocks = outSize/zeroblock.length; int numberOfRemainingBytes = (int)(outSize%zeroblock.length); for(int j = 0; j < numberOfZeroBlocks; ++j) { if(!testOnly) isoRaf.write(zeroblock); } if(!testOnly) isoRaf.write(zeroblock, 0, numberOfRemainingBytes); //lastInOffs = inOffset+inSize; } else if(blockType == BT_ZERO2) {// if(debug)// println(" " + elementNumber + ":" + blockCount + ". BT_ZERO2 processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) { println("!------>WARNING: BT_ZERO2 FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); ++warningsReported; } reportFilePointerProgress(dmgRaf); long numberOfZeroBlocks = outSize/zeroblock.length; int numberOfRemainingBytes = (int)(outSize%zeroblock.length); for(int j = 0; j < numberOfZeroBlocks; ++j) { if(!testOnly) isoRaf.write(zeroblock); } if(!testOnly) isoRaf.write(zeroblock, 0, numberOfRemainingBytes); //lastInOffs = inOffset+inSize; } else if(blockType == BT_UNKNOWN) { /* I have no idea what this blocktype is... but it's common, and usually doesn't appear more than 2-3 times in a dmg. As long as its input and output sizes are 0, there's no reason to complain... is there? */// if(debug)// println(" " + elementNumber + ":" + blockCount + ". BT_UNKNOWN processing..."); if(!(inSize == 0 && outSize == 0)) { println("!------>WARNING: Blocktype BT_UNKNOWN had non-zero sizes...", "!------> inSize=" + inSize + ", outSize=" + outSize); ++warningsReported; //println(" The author of the program would be pleased if you contacted him about this."); // ...or would I? } } else if(blockType == BT_END) {// if(debug)// println(" " + elementNumber + ":" + blockCount + ". BT_END processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) { println("!------>WARNING: BT_END FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); ++warningsReported; } //lastOffs += lastInOffs; lastOutOffset = outOffset; lastInOffset += lastByteReadInBlock; } else { println("!------>WARNING: previously unseen blocktype " + blockType + " [0x" + Integer.toHexString(blockType) + "]", "!------> outOffset=" + outOffset + " outSize=" + outSize + " inOffset=" + inOffset + " inSize=" + inSize); ++warningsReported; if(!testOnly && isoRaf.getFilePointer() != outOffset) println("!------>WARNING: unknown blocktype FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); } offset += 0x28; ++blockCount; } } ++elementNumber; } //printlnVerbose("Progress: 100% Done!"); reportProgress(100); String summary = (errorsReported != 0)?errorsReported+" errors reported":"No errors reported"; summary += (warningsReported != 0)?" ("+warningsReported+" warnings emitted).":"."; if(!graphical) { newline(); println(summary); printlnVerbose("Total extracted bytes: " + totalSize + " B"); } else { progmon.close(); JOptionPane.showMessageDialog(null, "Extraction complete! " + summary + "\n" + "Total extracted bytes: " + totalSize + " B", "Information", JOptionPane.INFORMATION_MESSAGE); System.exit(0); } if(!debug) { if(isoRaf != null) isoRaf.close(); dmgRaf.close(); } else { if(isoRaf != null) isoRaf.close();// System.out.println("blocks.size()=" + blocks.size());// for(DMGBlock b : blocks)// System.out.println(" " + b.toString()); LinkedList<DMGBlock> merged = mergeBlocks(blocks);// System.out.println("merged.size()=" + merged.size());// for(DMGBlock b : merged)// System.out.println(" " + b.toString()); println("Extracting all the parts not containing block data from source file:"); int i = 1; DMGBlock previous = null; for(DMGBlock b : merged) { if(previous == null && b.inOffset > 0) { String filename = i++ + ".block"; println(" " + new File(filename).getCanonicalPath() + "..."); FileOutputStream curFos = new FileOutputStream(new File(filename)); dmgRaf.seek(0); byte[] data = new byte[(int)(b.inOffset)]; dmgRaf.read(data); curFos.write(data); curFos.close(); } else if(previous != null) { String filename = i++ + ".block"; println(" " + new File(filename).getCanonicalPath() + "..."); FileOutputStream curFos = new FileOutputStream(new File(filename)); dmgRaf.seek(previous.inOffset+previous.inSize); byte[] data = new byte[(int)(b.inOffset-(previous.inOffset+previous.inSize))]; dmgRaf.read(data); curFos.write(data); curFos.close(); } previous = b; } if(previous.inOffset+previous.inSize != dmgRaf.length()) { String filename = i++ + ".block"; println(" " + new File(filename).getCanonicalPath() + "..."); FileOutputStream curFos = new FileOutputStream(new File(filename)); dmgRaf.seek(previous.inOffset+previous.inSize); byte[] data = new byte[(int)(dmgRaf.length()-(previous.inOffset+previous.inSize))]; dmgRaf.read(data); curFos.write(data); curFos.close(); } dmgRaf.close(); System.out.println("done!"); } } |
println(" options:"); println(" -v verbose operation... for finding out what went wrong"); println(" -saxparser use the standard SAX parser for XML processing instead of"); println(" the homewritten parser (will connect to Apple's website"); println(" for validation)"); println(); | public static void parseArgs(String[] args) { boolean parseSuccessful = false; try { /* Take care of the options... */ int i; for(i = 0; i < args.length; ++i) { String cur = args[i]; if(!cur.startsWith("-")) break; else if(cur.equals("-gui")) { graphical = true; // This should be moved to UI class in the future. System.setProperty("swing.aatext", "true"); //Antialiased text try { javax.swing.UIManager.setLookAndFeel(javax.swing.UIManager.getSystemLookAndFeelClassName()); } catch(Exception e) {} } else if(cur.equals("-v")) verbose = true; else if(cur.equals("-debug")) debug = true; else if(cur.equals("-startupcommand")) { startupCommand = args[i+1]; ++i; } } println(APPNAME + " " + BUILDSTRING, "Copyright (c) 2006 Erik Larsson <[email protected]>", " based on dmg2iso, Copyright (c) 2004 vu1tur <[email protected]>", " also using the iHarder Base64 Encoder/Decoder <http://iharder.sf.net>", "", "This program is distributed under the GNU General Public License version 2 or", "later. See <http://www.gnu.org/copyleft/gpl.html> for the details.", ""); if(i == args.length) { dmgFile = getInputFileFromUser(); if(dmgFile == null) System.exit(0); if(getOutputConfirmationFromUser()) { isoFile = getOutputFileFromUser(); if(isoFile == null) System.exit(0); } } else { dmgFile = new File(args[i++]); if(!dmgFile.exists()) { println("File \"" + dmgFile + "\" could not be found!"); System.exit(0); } if(i == args.length-1) isoFile = new File(args[i]); else if(i != args.length) throw new Exception(); } parseSuccessful = true; } catch(Exception e) { println(); println(" usage: " + startupCommand + " [options] <dmgFile> [<isoFile>]"); println(" if an iso-file is not supplied, the program will simulate an extraction"); println(" (useful for detecting errors in dmg-files)"); println(); System.exit(0); } } |
|
private JFileChooser getJFileChooserForFileSelection() { | private JFileChooser getJFileChooserForFileSelection( final String currentDirectoryKey) { | private JFileChooser getJFileChooserForFileSelection() { if(null == jFileChooser) { jFileChooser = new JFileChooser(); jFileChooser.setMultiSelectionEnabled(Boolean.TRUE); } jFileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY); jFileChooser.setCurrentDirectory(persistence.get( Keys.Persistence.JFILECHOOSER_CURRENT_DIRECTORY_FILE_SELECTION, (File) null)); return jFileChooser; } |
jFileChooser.setCurrentDirectory(persistence.get( Keys.Persistence.JFILECHOOSER_CURRENT_DIRECTORY_FILE_SELECTION, (File) null)); | jFileChooser.setCurrentDirectory( persistence.get(currentDirectoryKey, (File) null)); | private JFileChooser getJFileChooserForFileSelection() { if(null == jFileChooser) { jFileChooser = new JFileChooser(); jFileChooser.setMultiSelectionEnabled(Boolean.TRUE); } jFileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY); jFileChooser.setCurrentDirectory(persistence.get( Keys.Persistence.JFILECHOOSER_CURRENT_DIRECTORY_FILE_SELECTION, (File) null)); return jFileChooser; } |
private JFileChooser getJFileChooserForFolderSelection() { | private JFileChooser getJFileChooserForFolderSelection(final String currentDirectoryKey) { | private JFileChooser getJFileChooserForFolderSelection() { if(null == jFileChooser) { jFileChooser = new JFileChooser(); jFileChooser.setMultiSelectionEnabled(Boolean.FALSE); } jFileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); jFileChooser.setCurrentDirectory(persistence.get( Keys.Persistence.JFILECHOOSER_CURRENT_DIRECTORY_FOLDER_SELECTION, (File) null)); return jFileChooser; } |
jFileChooser.setCurrentDirectory(persistence.get( Keys.Persistence.JFILECHOOSER_CURRENT_DIRECTORY_FOLDER_SELECTION, (File) null)); | jFileChooser.setCurrentDirectory( persistence.get(currentDirectoryKey, (File) null)); | private JFileChooser getJFileChooserForFolderSelection() { if(null == jFileChooser) { jFileChooser = new JFileChooser(); jFileChooser.setMultiSelectionEnabled(Boolean.FALSE); } jFileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); jFileChooser.setCurrentDirectory(persistence.get( Keys.Persistence.JFILECHOOSER_CURRENT_DIRECTORY_FOLDER_SELECTION, (File) null)); return jFileChooser; } |
if(JFileChooser.APPROVE_OPTION == getJFileChooserForFileSelection().showOpenDialog(mainWindow)) { persistence.set( Keys.Persistence.JFILECHOOSER_CURRENT_DIRECTORY_FILE_SELECTION, | if(JFileChooser.APPROVE_OPTION == getJFileChooserForFileSelection( Keys.Persistence.CONTAINER_ADD_DOCUMENT_CURRENT_DIRECTORY).showOpenDialog(mainWindow)) { persistence.set(Keys.Persistence.CONTAINER_ADD_DOCUMENT_CURRENT_DIRECTORY, | public void runAddContainerDocuments(final Long containerId) { if(JFileChooser.APPROVE_OPTION == getJFileChooserForFileSelection().showOpenDialog(mainWindow)) { persistence.set( Keys.Persistence.JFILECHOOSER_CURRENT_DIRECTORY_FILE_SELECTION, jFileChooser.getCurrentDirectory()); runAddContainerDocuments(containerId, jFileChooser.getSelectedFiles()); } } |
if(JFileChooser.APPROVE_OPTION == getJFileChooserForFolderSelection().showOpenDialog(mainWindow)) { persistence.set( Keys.Persistence.JFILECHOOSER_CURRENT_DIRECTORY_FOLDER_SELECTION, jFileChooser.getCurrentDirectory()); | if(JFileChooser.APPROVE_OPTION == getJFileChooserForFolderSelection( Keys.Persistence.CONTAINER_EXPORT_DRAFT_SELECTED_DIRECTORY).showOpenDialog(mainWindow)) { persistence.set(Keys.Persistence.CONTAINER_EXPORT_DRAFT_SELECTED_DIRECTORY, jFileChooser.getSelectedFile()); | public void runExportDraft(final Long containerId) { if(JFileChooser.APPROVE_OPTION == getJFileChooserForFolderSelection().showOpenDialog(mainWindow)) { persistence.set( Keys.Persistence.JFILECHOOSER_CURRENT_DIRECTORY_FOLDER_SELECTION, jFileChooser.getCurrentDirectory()); runExportDraft(containerId, jFileChooser.getSelectedFile()); } } |
if(JFileChooser.APPROVE_OPTION == getJFileChooserForFolderSelection().showOpenDialog(mainWindow)) { persistence.set( Keys.Persistence.JFILECHOOSER_CURRENT_DIRECTORY_FOLDER_SELECTION, jFileChooser.getCurrentDirectory()); | if(JFileChooser.APPROVE_OPTION == getJFileChooserForFolderSelection( Keys.Persistence.CONTAINER_EXPORT_VERSION_SELECTED_DIRECTORY).showOpenDialog(mainWindow)) { persistence.set(Keys.Persistence.CONTAINER_EXPORT_VERSION_SELECTED_DIRECTORY, jFileChooser.getSelectedFile()); | public void runExportVersion(final Long containerId, final Long versionId) { if(JFileChooser.APPROVE_OPTION == getJFileChooserForFolderSelection().showOpenDialog(mainWindow)) { persistence.set( Keys.Persistence.JFILECHOOSER_CURRENT_DIRECTORY_FOLDER_SELECTION, jFileChooser.getCurrentDirectory()); runExportVersion(containerId, versionId, jFileChooser.getSelectedFile()); } } |
send(JabberIdBuilder.parseQualifiedJabberId(jid.toBareJID()), iq); | send(JabberIdBuilder.parseQualifiedUsername(jid.toBareJID()), iq); | void send(final QueueItem queueItem) { logApiId(); logger.debug(queueItem); final JID jid = JIDBuilder.build(queueItem.getUsername()); try { final Document queueItemDocument = readXml(queueItem.getQueueMessage()); final IQ iq = new IQ(queueItemDocument.getRootElement()); iq.setTo(jid); send(JabberIdBuilder.parseQualifiedJabberId(jid.toBareJID()), iq); } catch (final Throwable t) { throw translateError(t); } } |
s.setPublicationDate(item.getDate()); | private void handleItem(ItemIF item) { Story s = new Story(); s.setID(item.getGuid().getLocation().replaceAll("[^\\p{Print}]", "")); s.setAuthor(item.getCreator().replaceAll("[^\\p{Print}]", "")); s.setTitle(item.getTitle().replaceAll("[^\\p{Print}]", "")); s.setContent(item.getDescription().replaceAll("[^\\p{Print}]", "")); Message msg = new Message(); msg.to = "WB.Stories"; msg.type = "Story"; msg.content = s.toYAML(); airBrush.postMessage(msg); } |
|
public String getAuthorRelevance() { return getProperty(keyAuthorRelevance); | public Double getAuthorRelevance() { return getDoubleProperty(keyAuthorRelevance); | public String getAuthorRelevance() { return getProperty(keyAuthorRelevance); } |
public String getTopicRelevance() { return getProperty(keyTopicRelevance); | public Double getTopicRelevance() { return getDoubleProperty(keyTopicRelevance); | public String getTopicRelevance() { return getProperty(keyTopicRelevance); } |
if(TxUtils.containsJavaFileList(transferFlavors)) { return true; } | if(TxUtils.containsJavaFileList(transferFlavors)) { if(Connection.ONLINE == browser.getConnectionStatus()) { return true; } } | public boolean canImport(final JComponent comp, final DataFlavor[] transferFlavors) { logger.debug(comp.getClass().getSimpleName()); if(TxUtils.containsJavaFileList(transferFlavors)) { return true; } return false; } |
this.id = JVMUniqueId.nextId(); | protected ListItem(final String l18nContext) { super(); this.localization = new ListItemLocalization(l18nContext); this.logger = LoggerFactory.getLogger(getClass()); this.modelFactory = ModelFactory.getInstance(); this.propertyMap = new Hashtable<Object,Object>(7, 0.75F); } |
|
final Object[] arguments, final ActionListener actionListener) { return createJMenuItem(getString(localKey, arguments), getMnemonic(localKey), | final ActionListener actionListener) { return createJMenuItem(getString(localKey), getMnemonic(localKey), | protected JMenuItem createJMenuItem(final String localKey, final Object[] arguments, final ActionListener actionListener) { return createJMenuItem(getString(localKey, arguments), getMnemonic(localKey), actionListener); } |
.append("LSAHD-QOIUQOE-ZXBVMNZNX-MZXXNCBVMX") .insert(0, "LKSJD-ZXVBNZM-QPWOEIURY-NXBCVMXNBC") | .append(System.currentTimeMillis()) | protected String createSessionId(final JabberId userId) { // TODO Generate a unique id per user id and store it in the user's // meta-data final String hashString = new StringBuffer(userId.toString()) .append("LSAHD-QOIUQOE-ZXBVMNZNX-MZXXNCBVMX") .insert(0, "LKSJD-ZXVBNZM-QPWOEIURY-NXBCVMXNBC") .toString(); return MD5Util.md5Hex(hashString.getBytes()); } |
new StreamSocketDelegate(streamServer, clientSocket).run(); | try { new StreamSocketDelegate(streamServer, clientSocket).run(); } catch (final Throwable t) { logger.logError(t, "Failed to negotiate stream {0}.", clientSocket.getRemoteSocketAddress()); } finally { clientSocket.close(); } | public void run() { logger.logApiId(); logger.logVariable("run", run); try { while (run) { started = true; synchronized (this) { notifyAll(); } final Socket clientSocket = serverSocket.accept(); logger.logTrace("Socket connected."); new StreamSocketDelegate(streamServer, clientSocket).run(); logger.logTrace("Socket handler executed."); } } catch (final Throwable t) { logger.logFatal(t, "Fatal stream socket server error."); } } |
revertDraft(documentId, readLatestVersion(documentId).getVersionId()); | try { revertDraft(documentId, readLatestVersion(documentId).getVersionId()); } catch (final Throwable t) { throw translateError(t); } | void revertDraft(final Long documentId) { logger.logApiId(); logger.logVariable("documentId", documentId); revertDraft(documentId, readLatestVersion(documentId).getVersionId()); } |
if (!this.isAbsoluteUrl) | if (!isAbsoluteUrl(url)) | protected Reader acquireReader(String url) throws IOException, Exception { if (!this.isAbsoluteUrl) { // for relative URLs, delegate to our peer return new StringReader(acquireString(url)); } else { // absolute URL try { // handle absolute URLs ourselves, using java.net.URL URL u = new URL(url); //URL u = new URL("http", "proxy.hi.is", 8080, target); URLConnection uc = u.openConnection(); InputStream i = uc.getInputStream(); // okay, we've got a stream; encode it appropriately Reader r = null; String charSet; // charSet extracted according to RFC 2045, section 5.1 String contentType = uc.getContentType(); if (contentType != null) { charSet = ImportSupport.getContentTypeAttribute(contentType, "charset"); if (charSet == null) { charSet = DEFAULT_ENCODING; } } else { charSet = DEFAULT_ENCODING; } try { r = new InputStreamReader(i, charSet); } catch (Exception ex) { r = new InputStreamReader(i, DEFAULT_ENCODING); } // check response code for HTTP URLs before returning, per spec, // before returning if (uc instanceof HttpURLConnection) { int status = ((HttpURLConnection)uc).getResponseCode(); if (status < 200 || status > 299) { throw new Exception(status + " " + url); } } return r; } catch (IOException ex) { throw new Exception("Problem accessing the absolute URL \"" + url + "\". " + ex); } catch (RuntimeException ex) { // because the spec makes us throw new Exception("Problem accessing the absolute URL \"" + url + "\". " + ex); } } } |
URLConnection uc = u.openConnection(); InputStream i = uc.getInputStream(); | uc = u.openConnection(); i = uc.getInputStream(); if (uc instanceof HttpURLConnection) { huc = (HttpURLConnection)uc; int status = huc.getResponseCode(); if (status < 200 || status > 299) { throw new Exception(status + " " + url); } } | protected Reader acquireReader(String url) throws IOException, Exception { if (!this.isAbsoluteUrl) { // for relative URLs, delegate to our peer return new StringReader(acquireString(url)); } else { // absolute URL try { // handle absolute URLs ourselves, using java.net.URL URL u = new URL(url); //URL u = new URL("http", "proxy.hi.is", 8080, target); URLConnection uc = u.openConnection(); InputStream i = uc.getInputStream(); // okay, we've got a stream; encode it appropriately Reader r = null; String charSet; // charSet extracted according to RFC 2045, section 5.1 String contentType = uc.getContentType(); if (contentType != null) { charSet = ImportSupport.getContentTypeAttribute(contentType, "charset"); if (charSet == null) { charSet = DEFAULT_ENCODING; } } else { charSet = DEFAULT_ENCODING; } try { r = new InputStreamReader(i, charSet); } catch (Exception ex) { r = new InputStreamReader(i, DEFAULT_ENCODING); } // check response code for HTTP URLs before returning, per spec, // before returning if (uc instanceof HttpURLConnection) { int status = ((HttpURLConnection)uc).getResponseCode(); if (status < 200 || status > 299) { throw new Exception(status + " " + url); } } return r; } catch (IOException ex) { throw new Exception("Problem accessing the absolute URL \"" + url + "\". " + ex); } catch (RuntimeException ex) { // because the spec makes us throw new Exception("Problem accessing the absolute URL \"" + url + "\". " + ex); } } } |
catch (Exception ex) | catch (UnsupportedEncodingException ueex) | protected Reader acquireReader(String url) throws IOException, Exception { if (!this.isAbsoluteUrl) { // for relative URLs, delegate to our peer return new StringReader(acquireString(url)); } else { // absolute URL try { // handle absolute URLs ourselves, using java.net.URL URL u = new URL(url); //URL u = new URL("http", "proxy.hi.is", 8080, target); URLConnection uc = u.openConnection(); InputStream i = uc.getInputStream(); // okay, we've got a stream; encode it appropriately Reader r = null; String charSet; // charSet extracted according to RFC 2045, section 5.1 String contentType = uc.getContentType(); if (contentType != null) { charSet = ImportSupport.getContentTypeAttribute(contentType, "charset"); if (charSet == null) { charSet = DEFAULT_ENCODING; } } else { charSet = DEFAULT_ENCODING; } try { r = new InputStreamReader(i, charSet); } catch (Exception ex) { r = new InputStreamReader(i, DEFAULT_ENCODING); } // check response code for HTTP URLs before returning, per spec, // before returning if (uc instanceof HttpURLConnection) { int status = ((HttpURLConnection)uc).getResponseCode(); if (status < 200 || status > 299) { throw new Exception(status + " " + url); } } return r; } catch (IOException ex) { throw new Exception("Problem accessing the absolute URL \"" + url + "\". " + ex); } catch (RuntimeException ex) { // because the spec makes us throw new Exception("Problem accessing the absolute URL \"" + url + "\". " + ex); } } } |
if (uc instanceof HttpURLConnection) | if (huc == null) | protected Reader acquireReader(String url) throws IOException, Exception { if (!this.isAbsoluteUrl) { // for relative URLs, delegate to our peer return new StringReader(acquireString(url)); } else { // absolute URL try { // handle absolute URLs ourselves, using java.net.URL URL u = new URL(url); //URL u = new URL("http", "proxy.hi.is", 8080, target); URLConnection uc = u.openConnection(); InputStream i = uc.getInputStream(); // okay, we've got a stream; encode it appropriately Reader r = null; String charSet; // charSet extracted according to RFC 2045, section 5.1 String contentType = uc.getContentType(); if (contentType != null) { charSet = ImportSupport.getContentTypeAttribute(contentType, "charset"); if (charSet == null) { charSet = DEFAULT_ENCODING; } } else { charSet = DEFAULT_ENCODING; } try { r = new InputStreamReader(i, charSet); } catch (Exception ex) { r = new InputStreamReader(i, DEFAULT_ENCODING); } // check response code for HTTP URLs before returning, per spec, // before returning if (uc instanceof HttpURLConnection) { int status = ((HttpURLConnection)uc).getResponseCode(); if (status < 200 || status > 299) { throw new Exception(status + " " + url); } } return r; } catch (IOException ex) { throw new Exception("Problem accessing the absolute URL \"" + url + "\". " + ex); } catch (RuntimeException ex) { // because the spec makes us throw new Exception("Problem accessing the absolute URL \"" + url + "\". " + ex); } } } |
int status = ((HttpURLConnection)uc).getResponseCode(); if (status < 200 || status > 299) { throw new Exception(status + " " + url); } | return r; | protected Reader acquireReader(String url) throws IOException, Exception { if (!this.isAbsoluteUrl) { // for relative URLs, delegate to our peer return new StringReader(acquireString(url)); } else { // absolute URL try { // handle absolute URLs ourselves, using java.net.URL URL u = new URL(url); //URL u = new URL("http", "proxy.hi.is", 8080, target); URLConnection uc = u.openConnection(); InputStream i = uc.getInputStream(); // okay, we've got a stream; encode it appropriately Reader r = null; String charSet; // charSet extracted according to RFC 2045, section 5.1 String contentType = uc.getContentType(); if (contentType != null) { charSet = ImportSupport.getContentTypeAttribute(contentType, "charset"); if (charSet == null) { charSet = DEFAULT_ENCODING; } } else { charSet = DEFAULT_ENCODING; } try { r = new InputStreamReader(i, charSet); } catch (Exception ex) { r = new InputStreamReader(i, DEFAULT_ENCODING); } // check response code for HTTP URLs before returning, per spec, // before returning if (uc instanceof HttpURLConnection) { int status = ((HttpURLConnection)uc).getResponseCode(); if (status < 200 || status > 299) { throw new Exception(status + " " + url); } } return r; } catch (IOException ex) { throw new Exception("Problem accessing the absolute URL \"" + url + "\". " + ex); } catch (RuntimeException ex) { // because the spec makes us throw new Exception("Problem accessing the absolute URL \"" + url + "\". " + ex); } } } |
return r; | else { return new SafeClosingHttpURLConnectionReader(r, huc); } | protected Reader acquireReader(String url) throws IOException, Exception { if (!this.isAbsoluteUrl) { // for relative URLs, delegate to our peer return new StringReader(acquireString(url)); } else { // absolute URL try { // handle absolute URLs ourselves, using java.net.URL URL u = new URL(url); //URL u = new URL("http", "proxy.hi.is", 8080, target); URLConnection uc = u.openConnection(); InputStream i = uc.getInputStream(); // okay, we've got a stream; encode it appropriately Reader r = null; String charSet; // charSet extracted according to RFC 2045, section 5.1 String contentType = uc.getContentType(); if (contentType != null) { charSet = ImportSupport.getContentTypeAttribute(contentType, "charset"); if (charSet == null) { charSet = DEFAULT_ENCODING; } } else { charSet = DEFAULT_ENCODING; } try { r = new InputStreamReader(i, charSet); } catch (Exception ex) { r = new InputStreamReader(i, DEFAULT_ENCODING); } // check response code for HTTP URLs before returning, per spec, // before returning if (uc instanceof HttpURLConnection) { int status = ((HttpURLConnection)uc).getResponseCode(); if (status < 200 || status > 299) { throw new Exception(status + " " + url); } } return r; } catch (IOException ex) { throw new Exception("Problem accessing the absolute URL \"" + url + "\". " + ex); } catch (RuntimeException ex) { // because the spec makes us throw new Exception("Problem accessing the absolute URL \"" + url + "\". " + ex); } } } |
if (i != null) { try { i.close(); } catch (IOException ioe) { LOG.error("Could not close InputStream", ioe); } } if (huc != null) { huc.disconnect(); } | protected Reader acquireReader(String url) throws IOException, Exception { if (!this.isAbsoluteUrl) { // for relative URLs, delegate to our peer return new StringReader(acquireString(url)); } else { // absolute URL try { // handle absolute URLs ourselves, using java.net.URL URL u = new URL(url); //URL u = new URL("http", "proxy.hi.is", 8080, target); URLConnection uc = u.openConnection(); InputStream i = uc.getInputStream(); // okay, we've got a stream; encode it appropriately Reader r = null; String charSet; // charSet extracted according to RFC 2045, section 5.1 String contentType = uc.getContentType(); if (contentType != null) { charSet = ImportSupport.getContentTypeAttribute(contentType, "charset"); if (charSet == null) { charSet = DEFAULT_ENCODING; } } else { charSet = DEFAULT_ENCODING; } try { r = new InputStreamReader(i, charSet); } catch (Exception ex) { r = new InputStreamReader(i, DEFAULT_ENCODING); } // check response code for HTTP URLs before returning, per spec, // before returning if (uc instanceof HttpURLConnection) { int status = ((HttpURLConnection)uc).getResponseCode(); if (status < 200 || status > 299) { throw new Exception(status + " " + url); } } return r; } catch (IOException ex) { throw new Exception("Problem accessing the absolute URL \"" + url + "\". " + ex); } catch (RuntimeException ex) { // because the spec makes us throw new Exception("Problem accessing the absolute URL \"" + url + "\". " + ex); } } } |
|
this.isAbsoluteUrl = isAbsoluteUrl(url); if (this.isAbsoluteUrl) | if (isAbsoluteUrl(url)) | protected String acquireString(String url) throws IOException, Exception { // Record whether our URL is absolute or relative this.isAbsoluteUrl = isAbsoluteUrl(url); if (this.isAbsoluteUrl) { // for absolute URLs, delegate to our peer BufferedReader r = new BufferedReader(acquireReader(url)); StringBuffer sb = new StringBuffer(); int i; // under JIT, testing seems to show this simple loop is as fast // as any of the alternatives while ((i = r.read()) != -1) { sb.append((char)i); } r.close(); return sb.toString(); } else // handle relative URLs ourselves { // URL is relative, so we must be an HTTP request if (!(request instanceof HttpServletRequest && response instanceof HttpServletResponse)) { throw new Exception("Relative import from non-HTTP request not allowed"); } // retrieve an appropriate ServletContext // normalize the URL if we have an HttpServletRequest if (!url.startsWith("/")) { String sp = ((HttpServletRequest)request).getServletPath(); url = sp.substring(0, sp.lastIndexOf('/')) + '/' + url; } // strip the session id from the url url = stripSession(url); // from this context, get a dispatcher RequestDispatcher rd = application.getRequestDispatcher(url); if (rd == null) { throw new Exception("Couldn't get a RequestDispatcher for \"" + url + "\""); } // include the resource, using our custom wrapper ImportResponseWrapper irw = new ImportResponseWrapper((HttpServletResponse)response); try { rd.include(request, irw); } catch (IOException ex) { throw new Exception("Problem importing the relative URL \"" + url + "\". " + ex); } catch (RuntimeException ex) { throw new Exception("Problem importing the relative URL \"" + url + "\". " + ex); } // disallow inappropriate response codes per JSTL spec if (irw.getStatus() < 200 || irw.getStatus() > 299) { throw new Exception("Invalid response code '" + irw.getStatus() + "' for \"" + url + "\""); } // recover the response String from our wrapper return irw.getString(); } } |
BufferedReader r = new BufferedReader(acquireReader(url)); StringBuffer sb = new StringBuffer(); int i; while ((i = r.read()) != -1) | BufferedReader r = null; try | protected String acquireString(String url) throws IOException, Exception { // Record whether our URL is absolute or relative this.isAbsoluteUrl = isAbsoluteUrl(url); if (this.isAbsoluteUrl) { // for absolute URLs, delegate to our peer BufferedReader r = new BufferedReader(acquireReader(url)); StringBuffer sb = new StringBuffer(); int i; // under JIT, testing seems to show this simple loop is as fast // as any of the alternatives while ((i = r.read()) != -1) { sb.append((char)i); } r.close(); return sb.toString(); } else // handle relative URLs ourselves { // URL is relative, so we must be an HTTP request if (!(request instanceof HttpServletRequest && response instanceof HttpServletResponse)) { throw new Exception("Relative import from non-HTTP request not allowed"); } // retrieve an appropriate ServletContext // normalize the URL if we have an HttpServletRequest if (!url.startsWith("/")) { String sp = ((HttpServletRequest)request).getServletPath(); url = sp.substring(0, sp.lastIndexOf('/')) + '/' + url; } // strip the session id from the url url = stripSession(url); // from this context, get a dispatcher RequestDispatcher rd = application.getRequestDispatcher(url); if (rd == null) { throw new Exception("Couldn't get a RequestDispatcher for \"" + url + "\""); } // include the resource, using our custom wrapper ImportResponseWrapper irw = new ImportResponseWrapper((HttpServletResponse)response); try { rd.include(request, irw); } catch (IOException ex) { throw new Exception("Problem importing the relative URL \"" + url + "\". " + ex); } catch (RuntimeException ex) { throw new Exception("Problem importing the relative URL \"" + url + "\". " + ex); } // disallow inappropriate response codes per JSTL spec if (irw.getStatus() < 200 || irw.getStatus() > 299) { throw new Exception("Invalid response code '" + irw.getStatus() + "' for \"" + url + "\""); } // recover the response String from our wrapper return irw.getString(); } } |
sb.append((char)i); | r = new BufferedReader(acquireReader(url)); StringBuffer sb = new StringBuffer(); int i; while ((i = r.read()) != -1) { sb.append((char)i); } return sb.toString(); | protected String acquireString(String url) throws IOException, Exception { // Record whether our URL is absolute or relative this.isAbsoluteUrl = isAbsoluteUrl(url); if (this.isAbsoluteUrl) { // for absolute URLs, delegate to our peer BufferedReader r = new BufferedReader(acquireReader(url)); StringBuffer sb = new StringBuffer(); int i; // under JIT, testing seems to show this simple loop is as fast // as any of the alternatives while ((i = r.read()) != -1) { sb.append((char)i); } r.close(); return sb.toString(); } else // handle relative URLs ourselves { // URL is relative, so we must be an HTTP request if (!(request instanceof HttpServletRequest && response instanceof HttpServletResponse)) { throw new Exception("Relative import from non-HTTP request not allowed"); } // retrieve an appropriate ServletContext // normalize the URL if we have an HttpServletRequest if (!url.startsWith("/")) { String sp = ((HttpServletRequest)request).getServletPath(); url = sp.substring(0, sp.lastIndexOf('/')) + '/' + url; } // strip the session id from the url url = stripSession(url); // from this context, get a dispatcher RequestDispatcher rd = application.getRequestDispatcher(url); if (rd == null) { throw new Exception("Couldn't get a RequestDispatcher for \"" + url + "\""); } // include the resource, using our custom wrapper ImportResponseWrapper irw = new ImportResponseWrapper((HttpServletResponse)response); try { rd.include(request, irw); } catch (IOException ex) { throw new Exception("Problem importing the relative URL \"" + url + "\". " + ex); } catch (RuntimeException ex) { throw new Exception("Problem importing the relative URL \"" + url + "\". " + ex); } // disallow inappropriate response codes per JSTL spec if (irw.getStatus() < 200 || irw.getStatus() > 299) { throw new Exception("Invalid response code '" + irw.getStatus() + "' for \"" + url + "\""); } // recover the response String from our wrapper return irw.getString(); } } |
r.close(); return sb.toString(); | finally { if(r != null) { try { r.close(); } catch (IOException ioe) { LOG.error("Could not close reader.", ioe); } } } | protected String acquireString(String url) throws IOException, Exception { // Record whether our URL is absolute or relative this.isAbsoluteUrl = isAbsoluteUrl(url); if (this.isAbsoluteUrl) { // for absolute URLs, delegate to our peer BufferedReader r = new BufferedReader(acquireReader(url)); StringBuffer sb = new StringBuffer(); int i; // under JIT, testing seems to show this simple loop is as fast // as any of the alternatives while ((i = r.read()) != -1) { sb.append((char)i); } r.close(); return sb.toString(); } else // handle relative URLs ourselves { // URL is relative, so we must be an HTTP request if (!(request instanceof HttpServletRequest && response instanceof HttpServletResponse)) { throw new Exception("Relative import from non-HTTP request not allowed"); } // retrieve an appropriate ServletContext // normalize the URL if we have an HttpServletRequest if (!url.startsWith("/")) { String sp = ((HttpServletRequest)request).getServletPath(); url = sp.substring(0, sp.lastIndexOf('/')) + '/' + url; } // strip the session id from the url url = stripSession(url); // from this context, get a dispatcher RequestDispatcher rd = application.getRequestDispatcher(url); if (rd == null) { throw new Exception("Couldn't get a RequestDispatcher for \"" + url + "\""); } // include the resource, using our custom wrapper ImportResponseWrapper irw = new ImportResponseWrapper((HttpServletResponse)response); try { rd.include(request, irw); } catch (IOException ex) { throw new Exception("Problem importing the relative URL \"" + url + "\". " + ex); } catch (RuntimeException ex) { throw new Exception("Problem importing the relative URL \"" + url + "\". " + ex); } // disallow inappropriate response codes per JSTL spec if (irw.getStatus() < 200 || irw.getStatus() > 299) { throw new Exception("Invalid response code '" + irw.getStatus() + "' for \"" + url + "\""); } // recover the response String from our wrapper return irw.getString(); } } |
protected final InputStream downloadStream(final String streamId) throws IOException { | protected final File downloadStream(final String streamId) throws IOException { | protected final InputStream downloadStream(final String streamId) throws IOException { final File streamFile = workspace.createTempFile(streamId); final FileOutputStream stream = new FileOutputStream(streamFile); final StreamSession session = getSessionModel().createStreamSession(); final StreamReader reader = new StreamReader(session); reader.open(); try { reader.read(streamId, stream); } finally { try { stream.close(); } finally { reader.close(); } } return new FileInputStream(streamFile); } |
return new FileInputStream(streamFile); | return streamFile; | protected final InputStream downloadStream(final String streamId) throws IOException { final File streamFile = workspace.createTempFile(streamId); final FileOutputStream stream = new FileOutputStream(streamFile); final StreamSession session = getSessionModel().createStreamSession(); final StreamReader reader = new StreamReader(session); reader.open(); try { reader.read(streamId, stream); } finally { try { stream.close(); } finally { reader.close(); } } return new FileInputStream(streamFile); } |
Mapper mapper = collectionDescriptor.getClassDescriptor().getMappingDescriptor().getMapper(); ClassDescriptor elementClassDescriptor = mapper.getClassDescriptor( ReflectionUtils.forName(collectionDescriptor.getElementClassName())); | ClassDescriptor elementClassDescriptor = mapper.getClassDescriptor( ReflectionUtils.forName(collectionDescriptor.getElementClassName())); | protected void doInsertCollection(Session session, Node parentNode, CollectionDescriptor collectionDescriptor, ManageableCollection collection) throws RepositoryException { if (collection == null) { return; } String jcrName = collectionDescriptor.getJcrName(); if (jcrName == null) { throw new JcrMappingException( "The JcrName attribute is not defined for the CollectionDescriptor : " + collectionDescriptor.getFieldName()); } Node collectionNode = parentNode.addNode(jcrName); Mapper mapper = collectionDescriptor.getClassDescriptor().getMappingDescriptor().getMapper(); ClassDescriptor elementClassDescriptor = mapper.getClassDescriptor( ReflectionUtils.forName(collectionDescriptor.getElementClassName())); Iterator collectionIterator = collection.getIterator(); int elementCollectionCount = 0; while (collectionIterator.hasNext()) { Object item = collectionIterator.next(); String elementJcrName = null; // If the element object has a unique id => the element jcr node name = the id value if (elementClassDescriptor.hasIdField()) { String idFieldName = elementClassDescriptor.getIdFieldDescriptor() .getFieldName(); elementJcrName = ReflectionUtils.getNestedProperty(item, idFieldName).toString(); } else { elementCollectionCount++; elementJcrName = COLLECTION_ELEMENT_NAME + elementCollectionCount; } objectConverter.insert(session, collectionNode, elementJcrName, item); } } |
Mapper mapper = collectionDescriptor.getClassDescriptor().getMappingDescriptor().getMapper(); ClassDescriptor elementClassDescriptor = mapper.getClassDescriptor( ReflectionUtils.forName(collectionDescriptor.getElementClassName())); | ClassDescriptor elementClassDescriptor = mapper.getClassDescriptor( ReflectionUtils.forName(collectionDescriptor.getElementClassName())); | protected void doUpdateCollection(Session session, Node parentNode, CollectionDescriptor collectionDescriptor, ManageableCollection collection) throws RepositoryException { String jcrName = getCollectionJcrName(collectionDescriptor); if (collection == null) { if (parentNode.hasNode(jcrName)) { parentNode.getNode(jcrName).remove(); } return; } Mapper mapper = collectionDescriptor.getClassDescriptor().getMappingDescriptor().getMapper(); ClassDescriptor elementClassDescriptor = mapper.getClassDescriptor( ReflectionUtils.forName(collectionDescriptor.getElementClassName())); Node collectionNode = parentNode.getNode(jcrName); // If the collection elements have not an id, it is not possible to find the matching JCR nodes => delete the complete collection if (!elementClassDescriptor.hasIdField()) { collectionNode.remove(); collectionNode = parentNode.addNode(jcrName); } Iterator collectionIterator = collection.getIterator(); int elementCollectionCount = 0; Map updatedItems = new HashMap(); while (collectionIterator.hasNext()) { Object item = collectionIterator.next(); elementCollectionCount++; String elementJcrName = null; if (elementClassDescriptor.hasIdField()) { String idFieldName = elementClassDescriptor.getIdFieldDescriptor().getFieldName(); elementJcrName = ReflectionUtils.getNestedProperty(item, idFieldName).toString(); // Update existing JCR Nodes if (collectionNode.hasNode(elementJcrName)) { objectConverter.update(session, collectionNode, elementJcrName, item); } else { // Add new collection elements objectConverter.insert(session, collectionNode, elementJcrName, item); } updatedItems.put(elementJcrName, item); } else { elementCollectionCount++; elementJcrName = COLLECTION_ELEMENT_NAME + elementCollectionCount; objectConverter.insert(session, collectionNode, elementJcrName, item); } } // Delete JCR nodes that are not present in the collection if (elementClassDescriptor.hasIdField()) { NodeIterator nodeIterator = collectionNode.getNodes(); List removeNodes = new ArrayList(); while (nodeIterator.hasNext()) { Node child = nodeIterator.nextNode(); if (!updatedItems.containsKey(child.getName())) { removeNodes.add(child); } } for(int i = 0; i < removeNodes.size(); i++) { ((Node) removeNodes.get(i)).remove(); } } } |
info = request.getPathInfo(); } if (info != null) { path += info; | protected Template handleRequest(HttpServletRequest request, HttpServletResponse response, Context ctx) throws Exception { // If we get here from RequestDispatcher.include(), getServletPath() // will return the original (wrong) URI requested. The following special // attribute holds the correct path. See section 8.3 of the Servlet // 2.3 specification. String path = (String)request.getAttribute("javax.servlet.include.servlet_path"); if (path == null) { path = request.getServletPath(); } return getTemplate(path); } |
|
data.add(new Fixture(document, documentModel, 4)); | data.add(new Fixture(document, documentModel, 3)); | protected void setUp() throws Exception { super.setUp(); data = new Vector<Fixture>(getInputFilesLength()); final DocumentModel documentModel = getDocumentModel(); String name, description; Document document; for(File testFile : getInputFiles()) { name = testFile.getName(); description = "Document: " + name; document = documentModel.create(name, description, testFile); documentModel.createVersion(document.getId()); documentModel.createVersion(document.getId()); documentModel.createVersion(document.getId()); data.add(new Fixture(document, documentModel, 4)); } } |
new PopupDocument((MainCellDocument) mainCell).trigger(browser, jPopupMenu, e); | new PopupDocument((MainCellDocument) mainCell, browser.getConnectionStatus()).trigger(browser, jPopupMenu, e); | void triggerPopup(final MainCell mainCell, final Component invoker, final MouseEvent e, final int x, final int y) { final JPopupMenu jPopupMenu = MenuFactory.createPopup(); if(mainCell instanceof MainCellDocument) { new PopupDocument((MainCellDocument) mainCell).trigger(browser, jPopupMenu, e); } else if(mainCell instanceof MainCellHistoryItem) { new PopupHistoryItem((MainCellHistoryItem) mainCell).trigger(browser, jPopupMenu, e); } jPopupMenu.show(invoker, x, y); } |
new PopupHistoryItem((MainCellHistoryItem) mainCell).trigger(browser, jPopupMenu, e); | new PopupHistoryItem((MainCellHistoryItem) mainCell, browser.getConnectionStatus()).trigger(browser, jPopupMenu, e); | void triggerPopup(final MainCell mainCell, final Component invoker, final MouseEvent e, final int x, final int y) { final JPopupMenu jPopupMenu = MenuFactory.createPopup(); if(mainCell instanceof MainCellDocument) { new PopupDocument((MainCellDocument) mainCell).trigger(browser, jPopupMenu, e); } else if(mainCell instanceof MainCellHistoryItem) { new PopupHistoryItem((MainCellHistoryItem) mainCell).trigger(browser, jPopupMenu, e); } jPopupMenu.show(invoker, x, y); } |
logger.info("[LBROWSER] [APPLICATION] [BROWSER] [DOCUMENT AVATAR] [TRIGGER POPUP]"); logger.debug(browser.getConnectionStatus()); | void triggerPopup(final MainCell mainCell, final Component invoker, final MouseEvent e, final int x, final int y) { final JPopupMenu jPopupMenu = MenuFactory.createPopup(); if(mainCell instanceof MainCellDocument) { new PopupDocument((MainCellDocument) mainCell).trigger(browser, jPopupMenu, e); } else if(mainCell instanceof MainCellHistoryItem) { new PopupHistoryItem((MainCellHistoryItem) mainCell).trigger(browser, jPopupMenu, e); } jPopupMenu.show(invoker, x, y); } |
|
String requestPath = ServletUtils.getPath(ctx.getRequest()); System.out.println("path: "+requestPath); | public Map getToolbox(Object initData) { //we know the initData is a ViewContext ViewContext ctx = (ViewContext)initData; //create the toolbox map with the application tools in it Map toolbox = new HashMap(appTools); if (!sessionToolInfo.isEmpty()) { HttpSession session = ctx.getRequest().getSession(createSession); if (session != null) { // allow only one thread per session at a time synchronized(getMutex(session)) { // get the session tools Map stmap = (Map)session.getAttribute(SESSION_TOOLS_KEY); if (stmap == null) { // init and store session tools map stmap = new HashMap(sessionToolInfo.size()); Iterator i = sessionToolInfo.iterator(); while(i.hasNext()) { ToolInfo ti = (ToolInfo)i.next(); stmap.put(ti.getKey(), ti.getInstance(ctx)); } session.setAttribute(SESSION_TOOLS_KEY, stmap); } // add them to the toolbox toolbox.putAll(stmap); } } } //add and initialize request tools Iterator i = requestToolInfo.iterator(); while(i.hasNext()) { ToolInfo info = (ToolInfo)i.next(); toolbox.put(info.getKey(), info.getInstance(ctx)); } return toolbox; } |
|
ToolInfo ti = (ToolInfo)i.next(); stmap.put(ti.getKey(), ti.getInstance(ctx)); | ServletToolInfo sti = (ServletToolInfo)i.next(); if (sti.allowsRequestPath(requestPath)) { stmap.put(sti.getKey(), sti.getInstance(ctx)); } | public Map getToolbox(Object initData) { //we know the initData is a ViewContext ViewContext ctx = (ViewContext)initData; //create the toolbox map with the application tools in it Map toolbox = new HashMap(appTools); if (!sessionToolInfo.isEmpty()) { HttpSession session = ctx.getRequest().getSession(createSession); if (session != null) { // allow only one thread per session at a time synchronized(getMutex(session)) { // get the session tools Map stmap = (Map)session.getAttribute(SESSION_TOOLS_KEY); if (stmap == null) { // init and store session tools map stmap = new HashMap(sessionToolInfo.size()); Iterator i = sessionToolInfo.iterator(); while(i.hasNext()) { ToolInfo ti = (ToolInfo)i.next(); stmap.put(ti.getKey(), ti.getInstance(ctx)); } session.setAttribute(SESSION_TOOLS_KEY, stmap); } // add them to the toolbox toolbox.putAll(stmap); } } } //add and initialize request tools Iterator i = requestToolInfo.iterator(); while(i.hasNext()) { ToolInfo info = (ToolInfo)i.next(); toolbox.put(info.getKey(), info.getInstance(ctx)); } return toolbox; } |
if (info instanceof ServletToolInfo) { ServletToolInfo sti = (ServletToolInfo)info; if (!sti.allowsRequestPath(requestPath)) { continue; } } | public Map getToolbox(Object initData) { //we know the initData is a ViewContext ViewContext ctx = (ViewContext)initData; //create the toolbox map with the application tools in it Map toolbox = new HashMap(appTools); if (!sessionToolInfo.isEmpty()) { HttpSession session = ctx.getRequest().getSession(createSession); if (session != null) { // allow only one thread per session at a time synchronized(getMutex(session)) { // get the session tools Map stmap = (Map)session.getAttribute(SESSION_TOOLS_KEY); if (stmap == null) { // init and store session tools map stmap = new HashMap(sessionToolInfo.size()); Iterator i = sessionToolInfo.iterator(); while(i.hasNext()) { ToolInfo ti = (ToolInfo)i.next(); stmap.put(ti.getKey(), ti.getInstance(ctx)); } session.setAttribute(SESSION_TOOLS_KEY, stmap); } // add them to the toolbox toolbox.putAll(stmap); } } } //add and initialize request tools Iterator i = requestToolInfo.iterator(); while(i.hasNext()) { ToolInfo info = (ToolInfo)i.next(); toolbox.put(info.getKey(), info.getInstance(ctx)); } return toolbox; } |
|
final XMPPMethodResponse response = new XMPPMethodResponse(); parser.next(); while(true) { logger.logVariable("parser.getName()", parser.getName()); logger.logVariable("parser.getDepth()", parser.getDepth()); logger.logVariable("parser.getNamespace()", parser.getNamespace()); if (XmlPullParser.END_TAG == parser.getEventType()) { if (Service.NAME.equals(parser.getName())) { break; } else { Assert.assertUnreachable(MessageFormat.format( "Parsing incomplete for xmlns {0}; tag {1} at depth {2}.", parser.getNamespace(), parser.getName(), parser.getDepth())); } } else { response.writeResult(parseResult(parser)); } | try { return doParseIQ(parser); } catch (final Throwable t) { logger.logFatal(t, "Could not parse remote method response."); throw new XMPPException(t); | public IQ parseIQ(final XmlPullParser parser) throws Exception { final XMPPMethodResponse response = new XMPPMethodResponse(); parser.next(); while(true) { logger.logVariable("parser.getName()", parser.getName()); logger.logVariable("parser.getDepth()", parser.getDepth()); logger.logVariable("parser.getNamespace()", parser.getNamespace()); // stop processing when we hit the trailing query tag if (XmlPullParser.END_TAG == parser.getEventType()) { if (Service.NAME.equals(parser.getName())) { break; } else { Assert.assertUnreachable(MessageFormat.format( "Parsing incomplete for xmlns {0}; tag {1} at depth {2}.", parser.getNamespace(), parser.getName(), parser.getDepth())); } } else { response.writeResult(parseResult(parser)); } } return response; } |
return response; | public IQ parseIQ(final XmlPullParser parser) throws Exception { final XMPPMethodResponse response = new XMPPMethodResponse(); parser.next(); while(true) { logger.logVariable("parser.getName()", parser.getName()); logger.logVariable("parser.getDepth()", parser.getDepth()); logger.logVariable("parser.getNamespace()", parser.getNamespace()); // stop processing when we hit the trailing query tag if (XmlPullParser.END_TAG == parser.getEventType()) { if (Service.NAME.equals(parser.getName())) { break; } else { Assert.assertUnreachable(MessageFormat.format( "Parsing incomplete for xmlns {0}; tag {1} at depth {2}.", parser.getNamespace(), parser.getName(), parser.getDepth())); } } else { response.writeResult(parseResult(parser)); } } return response; } |
|
private Fixture(final List<Contact> contacts, final Container container, final ContainerModel containerModel) { this.contacts = contacts; this.container = container; this.containerModel = containerModel; | private Fixture(final OpheliaTestUser junit, final OpheliaTestUser junit_x, final OpheliaTestUser junit_y) { this.junit = junit; this.junit_x = junit_x; this.junit_y = junit_y; | private Fixture(final List<Contact> contacts, final Container container, final ContainerModel containerModel) { this.contacts = contacts; this.container = container; this.containerModel = containerModel; this.didNotify = Boolean.FALSE; this.teamMembers = Collections.emptyList(); } |
this.teamMembers = Collections.emptyList(); | addQueueHelper(junit); addQueueHelper(junit_x); addQueueHelper(junit_y); | private Fixture(final List<Contact> contacts, final Container container, final ContainerModel containerModel) { this.contacts = contacts; this.container = container; this.containerModel = containerModel; this.didNotify = Boolean.FALSE; this.teamMembers = Collections.emptyList(); } |
login(OpheliaTestUser.JUNIT); final ContainerModel containerModel = getContainerModel(OpheliaTestUser.JUNIT); final Container container = createContainer(OpheliaTestUser.JUNIT, NAME); addDocuments(OpheliaTestUser.JUNIT, container); final List<Contact> contacts = readContacts(OpheliaTestUser.JUNIT); datum = new Fixture(contacts, container, containerModel); containerModel.addListener(datum); | datum = new Fixture(OpheliaTestUser.JUNIT, OpheliaTestUser.JUNIT_X, OpheliaTestUser.JUNIT_Y); login(datum.junit); login(datum.junit_x); login(datum.junit_y); | protected void setUp() throws Exception { super.setUp(); login(OpheliaTestUser.JUNIT); final ContainerModel containerModel = getContainerModel(OpheliaTestUser.JUNIT); final Container container = createContainer(OpheliaTestUser.JUNIT, NAME); addDocuments(OpheliaTestUser.JUNIT, container); final List<Contact> contacts = readContacts(OpheliaTestUser.JUNIT); datum = new Fixture(contacts, container, containerModel); containerModel.addListener(datum); } |
logger.logTraceId(); datum.containerModel.removeListener(datum); | logout(datum.junit); logout(datum.junit_x); logout(datum.junit_y); | protected void tearDown() throws Exception { logger.logTraceId(); datum.containerModel.removeListener(datum); datum = null; logger.logTraceId(); logout(OpheliaTestUser.JUNIT); logger.logTraceId(); super.tearDown(); logger.logTraceId(); } |
logger.logTraceId(); logout(OpheliaTestUser.JUNIT); logger.logTraceId(); | protected void tearDown() throws Exception { logger.logTraceId(); datum.containerModel.removeListener(datum); datum = null; logger.logTraceId(); logout(OpheliaTestUser.JUNIT); logger.logTraceId(); super.tearDown(); logger.logTraceId(); } |
|
logger.logTraceId(); | protected void tearDown() throws Exception { logger.logTraceId(); datum.containerModel.removeListener(datum); datum = null; logger.logTraceId(); logout(OpheliaTestUser.JUNIT); logger.logTraceId(); super.tearDown(); logger.logTraceId(); } |
|
datum.containerModel.publish( datum.container.getId(), datum.contacts, datum.teamMembers); logger.logTraceId(); | final Container c = createContainer(datum.junit, NAME); final List<Document> documents = addDocuments(datum.junit, c.getId()); getContainerModel(datum.junit).addListener(datum); publishToContacts(datum.junit, c.getId(), "JUnit.X thinkParity", "JUnit.Y thinkParity"); getContainerModel(datum.junit).addListener(datum); datum.waitForEvents(); final Container c_x = readContainer(datum.junit_x, c.getUniqueId()); logger.logVariable("c_x", c_x); assertNotNull("Container for user \"" + datum.junit_x.getSimpleUsername() + "\" is null.", c_x); final Container c_y = readContainer(datum.junit_y, c.getUniqueId()); logger.logVariable("c_y", c_y); assertNotNull("Container for user \"" + datum.junit_y.getSimpleUsername() + "\" is null.", c_y); final ContainerDraft draft = readContainerDraft(datum.junit, c.getId()); assertNull("Draft for container " + c.getName() + " for user " + datum.junit.getSimpleUsername() + " is not null.", draft); final ContainerDraft draft_x = readContainerDraft(datum.junit_x, c_x.getId()); assertNull("Draft for container " + c_x.getName() + " for user " + datum.junit_y.getSimpleUsername() + " is not null.", draft_x); final ContainerDraft draft_y = readContainerDraft(datum.junit_y, c_x.getId()); assertNull("Draft for container " + c_y.getName() + " for user " + datum.junit_y.getSimpleUsername() + " is not null.", draft_y); | public void testPublish() { logger.logTraceId(); datum.containerModel.publish( datum.container.getId(), datum.contacts, datum.teamMembers); logger.logTraceId(); assertTrue("The draft published event was not fired.", datum.didNotify); // ensure the system is the key holder again final JabberId keyHolder = getArtifactModel(OpheliaTestUser.JUNIT).readKeyHolder(datum.container.getId()); assertEquals("Local artifact key holder does not match expectation.", User.THINK_PARITY.getId(), keyHolder); assertTrue("Local key flag is still mistakenly applied.", !getArtifactModel(OpheliaTestUser.JUNIT).isFlagApplied(datum.container.getId(), ArtifactFlag.KEY)); } |
final JabberId keyHolder = getArtifactModel(OpheliaTestUser.JUNIT).readKeyHolder(datum.container.getId()); assertEquals("Local artifact key holder does not match expectation.", User.THINK_PARITY.getId(), keyHolder); assertTrue("Local key flag is still mistakenly applied.", !getArtifactModel(OpheliaTestUser.JUNIT).isFlagApplied(datum.container.getId(), ArtifactFlag.KEY)); | documentModel = getDocumentModel(datum.junit_x); d_other = readDocument(datum.junit_x, d.getUniqueId()); assertFalse("Document \"" + d_other.getName() + "\" for user \"" + datum.junit_x.getSimpleUsername() + "\" still maintains draft.", documentModel.doesExistDraft(d_other.getId())); documentModel = getDocumentModel(datum.junit_y); d_other = readDocument(datum.junit_y, d.getUniqueId()); assertFalse("Document \"" + d_other.getName() + "\" for user \"" + datum.junit_y.getSimpleUsername() + "\" still maintains draft.", documentModel.doesExistDraft(d_other.getId())); } | public void testPublish() { logger.logTraceId(); datum.containerModel.publish( datum.container.getId(), datum.contacts, datum.teamMembers); logger.logTraceId(); assertTrue("The draft published event was not fired.", datum.didNotify); // ensure the system is the key holder again final JabberId keyHolder = getArtifactModel(OpheliaTestUser.JUNIT).readKeyHolder(datum.container.getId()); assertEquals("Local artifact key holder does not match expectation.", User.THINK_PARITY.getId(), keyHolder); assertTrue("Local key flag is still mistakenly applied.", !getArtifactModel(OpheliaTestUser.JUNIT).isFlagApplied(datum.container.getId(), ArtifactFlag.KEY)); } |
if (obj instanceof Long) { Date d = new Date(); d.setTime(((Long)obj).longValue()); return d; } | public static Date toDate(Object obj) { if (obj == null) { return null; } if (obj instanceof Date) { return (Date)obj; } if (obj instanceof Calendar) { return ((Calendar)obj).getTime(); } try { //try parsing the obj as String w/a DateFormat DateFormat parser = DateFormat.getInstance(); return parser.parse(String.valueOf(obj)); } catch (Exception e) { return null; } } |
|
System.setProperty("thinkparity.log4j.file", new File(logDirectory, "desdemona.log").getAbsolutePath()); | System.setProperty("thinkparity.log4j.directory", logDirectory.getAbsolutePath()); | private void initializeLogging() { final File logDirectory = new File(JiveGlobals.getHomeDirectory(), "logs"); System.setProperty("thinkparity.log4j.file", new File(logDirectory, "desdemona.log").getAbsolutePath()); logger = new Log4JWrapper(); } |
publisher = readPublisher(); | publisher = readLatestPublisher(); | private void reloadJList() { final List<TeamMember> teamMembers; final List<Contact> contacts; final Map<User, ArtifactReceipt> versionUsers; final User publisher; Boolean firstContact; if (getPublishTypeSpecific() == PublishTypeSpecific.PUBLISH_NOT_FIRST_TIME) { teamMembers = readTeamMembers(); versionUsers = readLatestVersionUsers(); publisher = readPublisher(); firstContact = !teamMembers.isEmpty(); } else { teamMembers = Collections.emptyList(); versionUsers = null; publisher = null; firstContact = Boolean.FALSE; } contacts = readContacts(teamMembers); namesListModel.clear(); for (final TeamMember teamMember : teamMembers) { namesListModel.addElement(new PublishContainerAvatarUser(teamMember, isVersionUser(teamMember, publisher, versionUsers))); } for (final Contact contact : contacts) { namesListModel.addElement(new PublishContainerAvatarUser(contact, Boolean.FALSE, firstContact)); firstContact = Boolean.FALSE; } } |
Object o = rsvc.getApplicationAttribute( "org.apache.velocity.tools.view.servlet.WebappLoader" ); | Object obj = rsvc.getApplicationAttribute(VelocityViewServlet.SERVLET_CONTEXT_KEY); | public void init( ExtendedProperties configuration) { rsvc.info("WebappLoader : initialization starting."); Object o = rsvc.getApplicationAttribute( "org.apache.velocity.tools.view.servlet.WebappLoader" ); if ( o instanceof WebappLoaderAppContext) { servletContext = ( (WebappLoaderAppContext) o ).getServletContext(); } else rsvc.error("WebappLoader : unable to retrieve ServletContext"); rsvc.info("WebappLoader : initialization complete."); } |
if ( o instanceof WebappLoaderAppContext) | if (obj instanceof ServletContext) | public void init( ExtendedProperties configuration) { rsvc.info("WebappLoader : initialization starting."); Object o = rsvc.getApplicationAttribute( "org.apache.velocity.tools.view.servlet.WebappLoader" ); if ( o instanceof WebappLoaderAppContext) { servletContext = ( (WebappLoaderAppContext) o ).getServletContext(); } else rsvc.error("WebappLoader : unable to retrieve ServletContext"); rsvc.info("WebappLoader : initialization complete."); } |
servletContext = ( (WebappLoaderAppContext) o ).getServletContext(); | servletContext = (ServletContext)obj; | public void init( ExtendedProperties configuration) { rsvc.info("WebappLoader : initialization starting."); Object o = rsvc.getApplicationAttribute( "org.apache.velocity.tools.view.servlet.WebappLoader" ); if ( o instanceof WebappLoaderAppContext) { servletContext = ( (WebappLoaderAppContext) o ).getServletContext(); } else rsvc.error("WebappLoader : unable to retrieve ServletContext"); rsvc.info("WebappLoader : initialization complete."); } |
public Applet(String moduleName) { super(moduleName); | public Applet(String moduleName, String hostname, Integer port) { super("Applet." + moduleName, hostname, port); | public Applet(String moduleName) { super(moduleName); // TODO Auto-generated constructor stub } |
public void setUtcTimeOnly(int field, Date value) { | public void setUtcTimeOnly(int field, Date value) throws NoTagValue { | public void setUtcTimeOnly(int field, Date value) { setUtcTimeOnly(field, value, false); } |
public UtilDateTypeConverterImpl(ValueFactory factory) { super(factory); } | public UtilDateTypeConverterImpl() { super(); } | public UtilDateTypeConverterImpl(ValueFactory factory) { super(factory); } |
document.setParent(new Document()); | public void testDocument() { Document document = new Document(); document.setId(Long.MAX_VALUE); document.setId(Long.MIN_VALUE); document.setEntity(new Entity()); document.setDocCode(""); document.setDocName(""); document.setChildren(new ArrayList<Tree>(0)); } |
|
externalDocument.setParent(new ExternalDocument()); | public void testExternalDocument() { ExternalDocument externalDocument = new ExternalDocument(); externalDocument.setId(Long.MAX_VALUE); externalDocument.setId(Long.MIN_VALUE); externalDocument.setEntity(new Entity()); externalDocument.setDocCode(""); externalDocument.setDocName(""); externalDocument.setDocUrl(""); externalDocument.setDocType(DocumentType.CATEGORY.getValue()); externalDocument.setDocType(DocumentType.FILE.getValue()); externalDocument.setDocType(DocumentType.FOLDER.getValue()); externalDocument.setParent(new ExternalDocument()); } |
|
alpha = Math.max( 0, alpha ); | private void paintScopeList( DownloadScopeList scopeList, Color baseColor, Graphics2D g2 ) { double valPerPixel = (fileSize-1) / (double)viewRect.width; int scopeCount = scopeList.size(); Color useColor; for( int i = 0; i < scopeCount; i++ ) { DownloadScope scope; try { scope = scopeList.getScopeAt(i); } catch ( IndexOutOfBoundsException exp ) {// list changed while painting break; } double startPx = scope.getStart() / valPerPixel; double endPx = scope.getEnd() / valPerPixel; double width = endPx - startPx; int alpha = (int)Math.min( 245*width, 245 )+10; if ( alpha < 255 ) { useColor = new Color( baseColor.getRed(), baseColor.getGreen(), baseColor.getBlue(), alpha ); } else { useColor = baseColor; } g2.setColor( useColor ); int rectWidth = (int)Math.max( width, 1 ); g2.fillRect(viewRect.x + (int)startPx, viewRect.y, rectWidth, viewRect.height); } } |
|
logger.log(Level.WARNING,"Unable to load "+dir,e); | private void reload() { try { TreeMap<String,ExternalRun> runs = new TreeMap<String,ExternalRun>(reverseComparator); File[] subdirs = getBuildDir().listFiles(new FileFilter() { public boolean accept(File subdir) { return subdir.isDirectory(); } }); Arrays.sort(subdirs,fileComparator); ExternalRun lastBuild = null; for( File dir : subdirs ) { try { ExternalRun b = new ExternalRun(this,dir,lastBuild); lastBuild = b; runs.put( b.getId(), b ); } catch (IOException e) { e.printStackTrace(); try { Util.deleteRecursive(dir); } catch (IOException e1) { e1.printStackTrace(); // but ignore } } } // replace the list with new one atomically. this.runs = runs; } finally { reloadingInProgress = false; nextUpdate = System.currentTimeMillis()+1000; } } |
|
protected final Map createEnvVarMap() { | protected final Map createEnvVarMap(boolean overrideOnly) { | protected final Map createEnvVarMap() { Map env = new HashMap(); buildEnvVars(env); return env; } |
if(!overrideOnly) env.putAll(EnvVars.masterEnvVars); | protected final Map createEnvVarMap() { Map env = new HashMap(); buildEnvVars(env); return env; } |
|
Map env = createEnvVarMap(); | Map env = createEnvVarMap(true); | protected final boolean run(Launcher launcher, String cmd, TaskListener listener, FilePath dir, OutputStream out) throws IOException { Map env = createEnvVarMap(); int r = launcher.launch(cmd,env,out,dir).join(); if(r!=0) listener.fatalError(getDescriptor().getDisplayName()+" failed"); return r==0; } |
t1.join(); t2.join(); | public int join() { try { return proc.waitFor(); } catch (InterruptedException e) { return -1; } } |
|
public Job doCreateJob(StaplerRequest req, StaplerResponse rsp) throws IOException { | public Job doCreateJob(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { | public Job doCreateJob(StaplerRequest req, StaplerResponse rsp) throws IOException { if(!Hudson.adminCheck(req,rsp)) return null; Job job = owner.doCreateJob(req, rsp); if(job!=null) { jobNames.add(job.getName()); owner.save(); } return job; } |
public abstract RecipeDetailsView getRecipeDetailsView(); | public abstract RecipeDetailsView getRecipeDetailsView(String title); | public abstract RecipeDetailsView getRecipeDetailsView(); |
log.debug("User successfully authorized."); | public void doFilter(final ServletRequest servletRequest, final ServletResponse servletResponse, final FilterChain filterChain) throws IOException, ServletException { final HttpServletRequest request = (HttpServletRequest) servletRequest; final HttpServletResponse response = (HttpServletResponse) servletResponse; final Assertion assertion = (Assertion) WebUtils.getRequiredSessionAttribute(request, AbstractCasFilter.CONST_ASSERTION); final Principal principal = assertion.getPrincipal(); final boolean authorized = this.decider .isAuthorizedToUseApplication(principal); if (!authorized) { response.setStatus(HttpServletResponse.SC_FORBIDDEN); throw new AuthorizationException(principal.getId() + " is not authorized to use this application."); } filterChain.doFilter(servletRequest, servletResponse); } |
|
if (principal != null && principal.length() > 0) { | if (principal == null || principal.length() == 0) { | public void validatePrincipal(Credential credential, Errors errors) { if (logger.isDebugEnabled()) { logger.debug("Validating Credential principal"); } String principal = credential.getPrincipal(); if (principal != null && principal.length() > 0) { errors.rejectValue("principal", "credential.error.whitespace", "Credential principal should not be empty or have whitespace"); } for (char c : principal.toCharArray()) { if (!Character.isLetterOrDigit(c)) { errors.rejectValue("principal", "credential.error.invalidchar", "Credential principal should include invalid char " + c); } } } |
"credential.error.whitespace", | "credential.error.empty", | public void validatePrincipal(Credential credential, Errors errors) { if (logger.isDebugEnabled()) { logger.debug("Validating Credential principal"); } String principal = credential.getPrincipal(); if (principal != null && principal.length() > 0) { errors.rejectValue("principal", "credential.error.whitespace", "Credential principal should not be empty or have whitespace"); } for (char c : principal.toCharArray()) { if (!Character.isLetterOrDigit(c)) { errors.rejectValue("principal", "credential.error.invalidchar", "Credential principal should include invalid char " + c); } } } |
} for (char c : principal.toCharArray()) { if (!Character.isLetterOrDigit(c)) { errors.rejectValue("principal", "credential.error.invalidchar", "Credential principal should include invalid char " + c); | } else { for (char c : principal.toCharArray()) { if (Character.isWhitespace(c)) { errors.rejectValue("principal", "credential.error.whitespace", "Credential principal should include invalid char " + c); } if (!Character.isLetterOrDigit(c)) { errors.rejectValue("principal", "credential.error.invalidchar", "Credential principal should include invalid char " + c); } | public void validatePrincipal(Credential credential, Errors errors) { if (logger.isDebugEnabled()) { logger.debug("Validating Credential principal"); } String principal = credential.getPrincipal(); if (principal != null && principal.length() > 0) { errors.rejectValue("principal", "credential.error.whitespace", "Credential principal should not be empty or have whitespace"); } for (char c : principal.toCharArray()) { if (!Character.isLetterOrDigit(c)) { errors.rejectValue("principal", "credential.error.invalidchar", "Credential principal should include invalid char " + c); } } } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.