<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
 * You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "nfcd.h"

#include "NfcManager.h"
#include "NfcService.h"
#include "NfcIpcSocket.h"
#include "DeviceHost.h"
#include "MessageHandler.h"
#include "SnepServer.h"
#include "NdefPushServer.h"
#include "HandoverServer.h"

#undef LOG_TAG
#define LOG_TAG "nfcd"
#include <cutils/log.h>

int main() {

  // 1. Create NFC Manager and do initialize
  NfcManager* pNfcManager = new NfcManager();
  pNfcManager->doInitialize();

  MessageHandler* msgHandler = new MessageHandler();

  // 2. Enable Discovery
  pNfcManager->enableDiscovery();

  // 3. Create service thread to receive message from nfc library
  NfcService* pNfcService = NfcService::Instance();
  pNfcService->initialize(pNfcManager, msgHandler);

  // 4. Create snep server
  // TODO : Maybe we should put this when p2p connection is established ?
  // Mark first because the function is not yet complete
  SnepCallback snepCallback;
  SnepServer snepServer(static_cast<ISnepCallback*>(&snepCallback));
  snepServer.start();

  NdefPushCallback ndefpushCallback;
  NdefPushServer ndefpushServer(static_cast<INdefPushCallback*>(&ndefpushCallback));
  ndefpushServer.start();

  HandoverCallback handoverCallback;
  HandoverServer handoverServer(static_cast<IHandoverCallback*>(&handoverCallback));
  handoverServer.start();

  // 5. Create IPC socket & main thread will enter while loop to read data from socket
  NfcIpcSocket* pNfcIpcSocket = NfcIpcSocket::Instance();
  pNfcIpcSocket->initialize(msgHandler);
  msgHandler->setSocket(pNfcIpcSocket);
  pNfcIpcSocket->loop();

  //TODO delete NfcIpcSocket, NfcService
  delete msgHandler;
  delete pNfcManager;
  //exit(0);
}
<commit_msg>Fix llcp connection cannot bw established<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
 * You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "nfcd.h"

#include "NfcManager.h"
#include "NfcService.h"
#include "NfcIpcSocket.h"
#include "DeviceHost.h"
#include "MessageHandler.h"
#include "SnepServer.h"
#include "NdefPushServer.h"
#include "HandoverServer.h"

#undef LOG_TAG
#define LOG_TAG "nfcd"
#include <cutils/log.h>

int main() {

  // 1. Create NFC Manager and do initialize
  NfcManager* pNfcManager = new NfcManager();
  pNfcManager->doInitialize();

  MessageHandler* msgHandler = new MessageHandler();

  // 2. Create service thread to receive message from nfc library
  NfcService* pNfcService = NfcService::Instance();
  pNfcService->initialize(pNfcManager, msgHandler);

  // 3. Create snep server
  // TODO : Maybe we should put this when p2p connection is established ?
  // Mark first because the function is not yet complete
  SnepCallback snepCallback;
  SnepServer snepServer(static_cast<ISnepCallback*>(&snepCallback));
  snepServer.start();

  // 4. Enable discovery MUST after push,snep,handover servers are established
  pNfcManager->enableDiscovery();

  NdefPushCallback ndefpushCallback;
  NdefPushServer ndefpushServer(static_cast<INdefPushCallback*>(&ndefpushCallback));
  ndefpushServer.start();

  HandoverCallback handoverCallback;
  HandoverServer handoverServer(static_cast<IHandoverCallback*>(&handoverCallback));
  handoverServer.start();

  // 5. Create IPC socket & main thread will enter while loop to read data from socket
  NfcIpcSocket* pNfcIpcSocket = NfcIpcSocket::Instance();
  pNfcIpcSocket->initialize(msgHandler);
  msgHandler->setSocket(pNfcIpcSocket);
  pNfcIpcSocket->loop();

  //TODO delete NfcIpcSocket, NfcService
  delete msgHandler;
  delete pNfcManager;
  //exit(0);
}
<|endoftext|>


<commit_before>#include "crt.h"
#include "node.h"
#include "token.h"
#include "scanner.h"
#include "content.h"
#include "parser.h"
#include "scalar.h"
#include "sequence.h"
#include "map.h"
#include "aliascontent.h"
#include "iterpriv.h"
#include "emitter.h"

namespace YAML
{
	// the ordering!
	bool ltnode::operator ()(const Node *pNode1, const Node *pNode2) const
	{
		return *pNode1 < *pNode2;
	}

	Node::Node(): m_pContent(0), m_alias(false), m_pIdentity(this), m_referenced(true)
	{
	}

	Node::~Node()
	{
		Clear();
	}

	void Node::Clear()
	{
		delete m_pContent;
		m_pContent = 0;
		m_alias = false;
		m_referenced = false;
		m_anchor.clear();
		m_tag.clear();
	}

	void Node::Parse(Scanner *pScanner, const ParserState& state)
	{
		Clear();

		// an empty node *is* a possibility
		if(pScanner->empty())
			return;

		// save location
		m_line = pScanner->peek().line;
		m_column = pScanner->peek().column;

		ParseHeader(pScanner, state);

		// is this an alias? if so, its contents are an alias to
		// a previously defined anchor
		if(m_alias) {
			// the scanner throws an exception if it doesn't know this anchor name
			const Node *pReferencedNode = pScanner->Retrieve(m_anchor);
			m_pIdentity = pReferencedNode;

			// mark the referenced node for the sake of the client code
			pReferencedNode->m_referenced = true;

			// use of an Alias object keeps the referenced content from
			// being deleted twice
			Content *pAliasedContent = pReferencedNode->m_pContent;
			if(pAliasedContent)
				m_pContent = new AliasContent(pAliasedContent);

			return;
		}

		// now split based on what kind of node we should be
		switch(pScanner->peek().type) {
			case TT_SCALAR:
				m_pContent = new Scalar;
				break;
			case TT_FLOW_SEQ_START:
			case TT_BLOCK_SEQ_START:
			case TT_BLOCK_ENTRY:
				m_pContent = new Sequence;
				break;
			case TT_FLOW_MAP_START:
			case TT_BLOCK_MAP_START:
				m_pContent = new Map;
				break;
			default:
				break;
		}

		// Have to save anchor before parsing to allow for aliases as
		// contained node (recursive structure)
		if(!m_anchor.empty())
			pScanner->Save(m_anchor, this);

		if(m_pContent)
			m_pContent->Parse(pScanner, state);
	}

	// ParseHeader
	// . Grabs any tag, alias, or anchor tokens and deals with them.
	void Node::ParseHeader(Scanner *pScanner, const ParserState& state)
	{
		while(1) {
			if(pScanner->empty())
				return;

			switch(pScanner->peek().type) {
				case TT_TAG: ParseTag(pScanner, state); break;
				case TT_ANCHOR: ParseAnchor(pScanner, state); break;
				case TT_ALIAS: ParseAlias(pScanner, state); break;
				default: return;
			}
		}
	}

	void Node::ParseTag(Scanner *pScanner, const ParserState& state)
	{
		Token& token = pScanner->peek();
		if(m_tag != "")
			throw ParserException(token.line, token.column, ErrorMsg::MULTIPLE_TAGS);

		m_tag = state.TranslateTag(token.value);

		for(unsigned i=0;i<token.params.size();i++)
			m_tag += token.params[i];
		pScanner->pop();
	}

	void Node::ParseAnchor(Scanner *pScanner, const ParserState& /*state*/)
	{
		Token& token = pScanner->peek();
		if(m_anchor != "")
			throw ParserException(token.line, token.column, ErrorMsg::MULTIPLE_ANCHORS);

		m_anchor = token.value;
		m_alias = false;
		pScanner->pop();
	}

	void Node::ParseAlias(Scanner *pScanner, const ParserState& /*state*/)
	{
		Token& token = pScanner->peek();
		if(m_anchor != "")
			throw ParserException(token.line, token.column, ErrorMsg::MULTIPLE_ALIASES);
		if(m_tag != "")
			throw ParserException(token.line, token.column, ErrorMsg::ALIAS_CONTENT);

		m_anchor = token.value;
		m_alias = true;
		pScanner->pop();
	}

	CONTENT_TYPE Node::GetType() const
	{
		if(!m_pContent)
			return CT_NONE;

		if(m_pContent->IsScalar())
			return CT_SCALAR;
		else if(m_pContent->IsSequence())
			return CT_SEQUENCE;
		else if(m_pContent->IsMap())
			return CT_MAP;

		return CT_NONE;
	}

	// begin
	// Returns an iterator to the beginning of this (sequence or map).
	Iterator Node::begin() const
	{
		if(!m_pContent)
			return Iterator();

		std::vector <Node *>::const_iterator seqIter;
		if(m_pContent->GetBegin(seqIter))
			return Iterator(new IterPriv(seqIter));

		std::map <Node *, Node *, ltnode>::const_iterator mapIter;
		if(m_pContent->GetBegin(mapIter))
			return Iterator(new IterPriv(mapIter));

		return Iterator();
	}

	// end
	// . Returns an iterator to the end of this (sequence or map).
	Iterator Node::end() const
	{
		if(!m_pContent)
			return Iterator();

		std::vector <Node *>::const_iterator seqIter;
		if(m_pContent->GetEnd(seqIter))
			return Iterator(new IterPriv(seqIter));

		std::map <Node *, Node *, ltnode>::const_iterator mapIter;
		if(m_pContent->GetEnd(mapIter))
			return Iterator(new IterPriv(mapIter));

		return Iterator();
	}

	// size
	// . Returns the size of this node, if it's a sequence node.
	// . Otherwise, returns zero.
	unsigned Node::size() const
	{
		if(!m_pContent)
			return 0;

		return m_pContent->GetSize();
	}

	const Node& Node::operator [] (unsigned u) const
	{
		if(!m_pContent)
			throw BadDereference();

		Node *pNode = m_pContent->GetNode(u);
		if(pNode)
			return *pNode;

		return GetValue(u);
	}

	const Node& Node::operator [] (int i) const
	{
		if(!m_pContent)
			throw BadDereference();

		Node *pNode = m_pContent->GetNode(i);
		if(pNode)
			return *pNode;

		return GetValue(i);
	}

	bool Node::GetScalar(std::string& s) const
	{
		if(!m_pContent)
			return false;
		return m_pContent->GetScalar(s);
	}

	Emitter& operator << (Emitter& out, const Node& node)
	{
		// write anchor/alias
		if(node.m_anchor != "") {
			if(node.m_alias)
				out << Alias(node.m_anchor);
			else
				out << Anchor(node.m_anchor);
		}

		// TODO: write tag

		// write content
		if(node.m_pContent)
			node.m_pContent->Write(out);

		return out;
	}

	int Node::Compare(const Node& rhs) const
	{
		// Step 1: no content is the smallest
		if(!m_pContent) {
			if(rhs.m_pContent)
				return -1;
			else
				return 0;
		}
		if(!rhs.m_pContent)
			return 1;

		return m_pContent->Compare(rhs.m_pContent);
	}

	bool operator < (const Node& n1, const Node& n2)
	{
		return n1.Compare(n2) < 0;
	}
}
<commit_msg>Fixed bug in emitting null nodes<commit_after>#include "crt.h"
#include "node.h"
#include "token.h"
#include "scanner.h"
#include "content.h"
#include "parser.h"
#include "scalar.h"
#include "sequence.h"
#include "map.h"
#include "aliascontent.h"
#include "iterpriv.h"
#include "emitter.h"

namespace YAML
{
	// the ordering!
	bool ltnode::operator ()(const Node *pNode1, const Node *pNode2) const
	{
		return *pNode1 < *pNode2;
	}

	Node::Node(): m_pContent(0), m_alias(false), m_pIdentity(this), m_referenced(true)
	{
	}

	Node::~Node()
	{
		Clear();
	}

	void Node::Clear()
	{
		delete m_pContent;
		m_pContent = 0;
		m_alias = false;
		m_referenced = false;
		m_anchor.clear();
		m_tag.clear();
	}

	void Node::Parse(Scanner *pScanner, const ParserState& state)
	{
		Clear();

		// an empty node *is* a possibility
		if(pScanner->empty())
			return;

		// save location
		m_line = pScanner->peek().line;
		m_column = pScanner->peek().column;

		ParseHeader(pScanner, state);

		// is this an alias? if so, its contents are an alias to
		// a previously defined anchor
		if(m_alias) {
			// the scanner throws an exception if it doesn't know this anchor name
			const Node *pReferencedNode = pScanner->Retrieve(m_anchor);
			m_pIdentity = pReferencedNode;

			// mark the referenced node for the sake of the client code
			pReferencedNode->m_referenced = true;

			// use of an Alias object keeps the referenced content from
			// being deleted twice
			Content *pAliasedContent = pReferencedNode->m_pContent;
			if(pAliasedContent)
				m_pContent = new AliasContent(pAliasedContent);

			return;
		}

		// now split based on what kind of node we should be
		switch(pScanner->peek().type) {
			case TT_SCALAR:
				m_pContent = new Scalar;
				break;
			case TT_FLOW_SEQ_START:
			case TT_BLOCK_SEQ_START:
			case TT_BLOCK_ENTRY:
				m_pContent = new Sequence;
				break;
			case TT_FLOW_MAP_START:
			case TT_BLOCK_MAP_START:
				m_pContent = new Map;
				break;
			default:
				break;
		}

		// Have to save anchor before parsing to allow for aliases as
		// contained node (recursive structure)
		if(!m_anchor.empty())
			pScanner->Save(m_anchor, this);

		if(m_pContent)
			m_pContent->Parse(pScanner, state);
	}

	// ParseHeader
	// . Grabs any tag, alias, or anchor tokens and deals with them.
	void Node::ParseHeader(Scanner *pScanner, const ParserState& state)
	{
		while(1) {
			if(pScanner->empty())
				return;

			switch(pScanner->peek().type) {
				case TT_TAG: ParseTag(pScanner, state); break;
				case TT_ANCHOR: ParseAnchor(pScanner, state); break;
				case TT_ALIAS: ParseAlias(pScanner, state); break;
				default: return;
			}
		}
	}

	void Node::ParseTag(Scanner *pScanner, const ParserState& state)
	{
		Token& token = pScanner->peek();
		if(m_tag != "")
			throw ParserException(token.line, token.column, ErrorMsg::MULTIPLE_TAGS);

		m_tag = state.TranslateTag(token.value);

		for(unsigned i=0;i<token.params.size();i++)
			m_tag += token.params[i];
		pScanner->pop();
	}

	void Node::ParseAnchor(Scanner *pScanner, const ParserState& /*state*/)
	{
		Token& token = pScanner->peek();
		if(m_anchor != "")
			throw ParserException(token.line, token.column, ErrorMsg::MULTIPLE_ANCHORS);

		m_anchor = token.value;
		m_alias = false;
		pScanner->pop();
	}

	void Node::ParseAlias(Scanner *pScanner, const ParserState& /*state*/)
	{
		Token& token = pScanner->peek();
		if(m_anchor != "")
			throw ParserException(token.line, token.column, ErrorMsg::MULTIPLE_ALIASES);
		if(m_tag != "")
			throw ParserException(token.line, token.column, ErrorMsg::ALIAS_CONTENT);

		m_anchor = token.value;
		m_alias = true;
		pScanner->pop();
	}

	CONTENT_TYPE Node::GetType() const
	{
		if(!m_pContent)
			return CT_NONE;

		if(m_pContent->IsScalar())
			return CT_SCALAR;
		else if(m_pContent->IsSequence())
			return CT_SEQUENCE;
		else if(m_pContent->IsMap())
			return CT_MAP;

		return CT_NONE;
	}

	// begin
	// Returns an iterator to the beginning of this (sequence or map).
	Iterator Node::begin() const
	{
		if(!m_pContent)
			return Iterator();

		std::vector <Node *>::const_iterator seqIter;
		if(m_pContent->GetBegin(seqIter))
			return Iterator(new IterPriv(seqIter));

		std::map <Node *, Node *, ltnode>::const_iterator mapIter;
		if(m_pContent->GetBegin(mapIter))
			return Iterator(new IterPriv(mapIter));

		return Iterator();
	}

	// end
	// . Returns an iterator to the end of this (sequence or map).
	Iterator Node::end() const
	{
		if(!m_pContent)
			return Iterator();

		std::vector <Node *>::const_iterator seqIter;
		if(m_pContent->GetEnd(seqIter))
			return Iterator(new IterPriv(seqIter));

		std::map <Node *, Node *, ltnode>::const_iterator mapIter;
		if(m_pContent->GetEnd(mapIter))
			return Iterator(new IterPriv(mapIter));

		return Iterator();
	}

	// size
	// . Returns the size of this node, if it's a sequence node.
	// . Otherwise, returns zero.
	unsigned Node::size() const
	{
		if(!m_pContent)
			return 0;

		return m_pContent->GetSize();
	}

	const Node& Node::operator [] (unsigned u) const
	{
		if(!m_pContent)
			throw BadDereference();

		Node *pNode = m_pContent->GetNode(u);
		if(pNode)
			return *pNode;

		return GetValue(u);
	}

	const Node& Node::operator [] (int i) const
	{
		if(!m_pContent)
			throw BadDereference();

		Node *pNode = m_pContent->GetNode(i);
		if(pNode)
			return *pNode;

		return GetValue(i);
	}

	bool Node::GetScalar(std::string& s) const
	{
		if(!m_pContent)
			return false;
		return m_pContent->GetScalar(s);
	}

	Emitter& operator << (Emitter& out, const Node& node)
	{
		// write anchor/alias
		if(node.m_anchor != "") {
			if(node.m_alias)
				out << Alias(node.m_anchor);
			else
				out << Anchor(node.m_anchor);
		}

		// TODO: write tag

		// write content
		if(node.m_pContent)
			node.m_pContent->Write(out);
		else
			out << "";

		return out;
	}

	int Node::Compare(const Node& rhs) const
	{
		// Step 1: no content is the smallest
		if(!m_pContent) {
			if(rhs.m_pContent)
				return -1;
			else
				return 0;
		}
		if(!rhs.m_pContent)
			return 1;

		return m_pContent->Compare(rhs.m_pContent);
	}

	bool operator < (const Node& n1, const Node& n2)
	{
		return n1.Compare(n2) < 0;
	}
}
<|endoftext|>


<commit_before>// Base header file.  Must be first.
#include <Include/PlatformDefinitions.hpp>

#if defined(XALAN_OLD_STREAM_HEADERS)
#include <iostream.h>
#include <strstream.h>
#include <fstream.h>
#else
#include <iostream>
#include <strstream>
#include <fstream>
#endif

#include <xercesc/util/PlatformUtils.hpp>

#include <XalanTransformer/XalanTransformer.hpp>

int
main(
			int				argc,
			const char*		/* argv */[])
{
#if !defined(XALAN_NO_NAMESPACES)
	using std::cerr;
	using std::cout;
	using std::endl;
	using std::istrstream;
	using std::ofstream;
	using std::ostrstream;
#if defined(XALAN_STRICT_ANSI_HEADERS)
		using std::strlen;
#endif
#endif

	int	theResult = 0;

	if (argc != 1)
	{
		cerr << "Usage: StreamTransform"
			 << endl
			 << endl;
	}
	else
	{
		// Call the static initializer for Xerces.
		XMLPlatformUtils::Initialize();

		// Initialize Xalan.
		XalanTransformer::initialize();

		// Create a XalanTransformer.
		XalanTransformer theXalanTransformer;

		// A simple input document...
#if defined(XALAN_NON_ASCII_PLATFORM)
		const char* const  theInputDocument = "<?xml version='1.0' encoding='EBCDIC-CP-US' ?><doc>Hello world!</doc>";
#else
		const char* const  theInputDocument = "<?xml version='1.0' encoding='ISO-8859-1' ?><doc>Hello world!</doc>";
#endif

		// A "hello world" stylesheet.  Note that the encoding for the output is platform-dependent,
		// since we're writing to a string.  It could be any encoding, but "binary" encodings,
		// or encodings that could produce multi-byte characters would require transcoding on
		// some platforms.
		const char* const  theStylesheet =
#if defined(XALAN_NON_ASCII_PLATFORM)
"<?xml version='1.0' encoding='EBCDIC-CP-US'?>\
<xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform' version='1.0'>\
<xsl:output encoding='EBCDIC-CP-US'/>\
<xsl:template match='doc'>\
<out><xsl:value-of select='.'/></out>\
</xsl:template>\
</xsl:stylesheet>";
#else
"<?xml version='1.0'?>\
<xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform' version='1.0'>\
<xsl:output encoding='US-ASCII'/>\
<xsl:template match='doc'>\
<out><xsl:value-of select='.'/></out>\
</xsl:template>\
</xsl:stylesheet>";
#endif

		// Our input streams...
		istrstream	theXMLStream(theInputDocument, strlen(theInputDocument));
		istrstream	theXSLStream(theStylesheet, strlen(theStylesheet));

		XSLTInputSource	inputSource(&theXSLStream);

		inputSource.setSystemId(c_wstr(XalanDOMString("foo")));

		// Do the transform.
		theResult = theXalanTransformer.transform(&theXMLStream, inputSource, cout);

		if(theResult != 0)
		{
			cerr << "StreamTransform Error: \n" << theXalanTransformer.getLastError()
				 << endl
				 << endl;
		}

		// Terminate Xalan.
		XalanTransformer::terminate();

		// Call the static terminator for Xerces.
		XMLPlatformUtils::Terminate();
	}

	return theResult;
}
<commit_msg>Scope XalanTransformer instance.<commit_after>// Base header file.  Must be first.
#include <Include/PlatformDefinitions.hpp>

#if defined(XALAN_OLD_STREAM_HEADERS)
#include <iostream.h>
#include <strstream.h>
#include <fstream.h>
#else
#include <iostream>
#include <strstream>
#include <fstream>
#endif

#include <xercesc/util/PlatformUtils.hpp>

#include <XalanTransformer/XalanTransformer.hpp>

int
main(
			int				argc,
			const char*		/* argv */[])
{
#if !defined(XALAN_NO_NAMESPACES)
	using std::cerr;
	using std::cout;
	using std::endl;
	using std::istrstream;
	using std::ofstream;
	using std::ostrstream;
#if defined(XALAN_STRICT_ANSI_HEADERS)
		using std::strlen;
#endif
#endif

	int	theResult = 0;

	if (argc != 1)
	{
		cerr << "Usage: StreamTransform"
			 << endl
			 << endl;
	}
	else
	{
		// Call the static initializer for Xerces.
		XMLPlatformUtils::Initialize();

		// Initialize Xalan.
		XalanTransformer::initialize();

		{
			// Create a XalanTransformer.
			XalanTransformer theXalanTransformer;

			// A simple input document...
#if defined(XALAN_NON_ASCII_PLATFORM)
			const char* const  theInputDocument = "<?xml version='1.0' encoding='EBCDIC-CP-US' ?><doc>Hello world!</doc>";
#else
			const char* const  theInputDocument = "<?xml version='1.0' encoding='ISO-8859-1' ?><doc>Hello world!</doc>";
#endif

			// A "hello world" stylesheet.  Note that the encoding for the output is platform-dependent,
			// since we're writing to a string.  It could be any encoding, but "binary" encodings,
			// or encodings that could produce multi-byte characters would require transcoding on
			// some platforms.
			const char* const  theStylesheet =
#if defined(XALAN_NON_ASCII_PLATFORM)
"<?xml version='1.0' encoding='EBCDIC-CP-US'?>\
<xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform' version='1.0'>\
<xsl:output encoding='EBCDIC-CP-US'/>\
<xsl:template match='doc'>\
<out><xsl:value-of select='.'/></out>\
</xsl:template>\
</xsl:stylesheet>";
#else
"<?xml version='1.0'?>\
<xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform' version='1.0'>\
<xsl:output encoding='US-ASCII'/>\
<xsl:template match='doc'>\
<out><xsl:value-of select='.'/></out>\
</xsl:template>\
</xsl:stylesheet>";
#endif

			// Our input streams...
			istrstream	theXMLStream(theInputDocument, strlen(theInputDocument));
			istrstream	theXSLStream(theStylesheet, strlen(theStylesheet));

			XSLTInputSource	inputSource(&theXSLStream);

			inputSource.setSystemId(c_wstr(XalanDOMString("foo")));

			// Do the transform.
			theResult = theXalanTransformer.transform(&theXMLStream, inputSource, cout);

			if(theResult != 0)
			{
				cerr << "StreamTransform Error: \n" << theXalanTransformer.getLastError()
					 << endl
					 << endl;
			}
		}

		// Terminate Xalan.
		XalanTransformer::terminate();

		// Call the static terminator for Xerces.
		XMLPlatformUtils::Terminate();
	}

	return theResult;
}
<|endoftext|>


<commit_before>#include <opencv2/opencv.hpp>
#include <vector>
#include <iostream>

using namespace std;
using namespace cv;

int main(void)
{
    vector<String> typeAlgoMatch;
    typeAlgoMatch.push_back("BruteForce");
    typeAlgoMatch.push_back("BruteForce-Hamming");
    typeAlgoMatch.push_back("BruteForce-Hamming(2)");

    vector<String> typeDesc;
    typeDesc.push_back("AKAZE");
    typeDesc.push_back("ORB");
    typeDesc.push_back("BRISK");

    String  dataFolder("../data/");
    vector<String> fileName;
    fileName.push_back("basketball1.png");
    fileName.push_back("basketball2.png");

    Mat img1 = imread(dataFolder+fileName[0], IMREAD_GRAYSCALE);
    Mat img2 = imread(dataFolder+fileName[1], IMREAD_GRAYSCALE);

    Ptr<Feature2D> b;

    vector<String>::iterator itDesc;
// Descriptor loop
    for (itDesc = typeDesc.begin(); itDesc != typeDesc.end(); itDesc++){
        Ptr<DescriptorMatcher> descriptorMatcher;
        vector<DMatch> matches;	        /*<! Match between img and img2*/
        vector<KeyPoint> keyImg1;		/*<! keypoint  for img1 */
        vector<KeyPoint> keyImg2;		/*<! keypoint  for img2 */
        Mat descImg1, descImg2;         /*<! Descriptor for img1 and img2 */
        vector<String>::iterator itMatcher = typeAlgoMatch.end();
        if (*itDesc == "AKAZE"){
            b = AKAZE::create();
        }
        if (*itDesc == "ORB"){
            b = ORB::create();
        }
        else if (*itDesc == "BRISK"){
            b = BRISK::create();
        }
        try {
            b->detect(img1, keyImg1, Mat());
            b->compute(img1, keyImg1, descImg1);
            b->detectAndCompute(img2, Mat(),keyImg2, descImg2,false);
 // Match method loop
             for (itMatcher = typeAlgoMatch.begin(); itMatcher != typeAlgoMatch.end(); itMatcher++){
                descriptorMatcher = DescriptorMatcher::create(*itMatcher);
                descriptorMatcher->match(descImg1, descImg2, matches, Mat());
 // Keep best matches only to have a nice drawing
                Mat index;
                Mat tab(matches.size(), 1, CV_32F);
                for (int i = 0; i<matches.size(); i++)
                    tab.at<float>(i, 0) = matches[i].distance;
                sortIdx(tab, index, SORT_EVERY_COLUMN + SORT_ASCENDING);
                vector<DMatch> bestMatches;	/*<! best match */
                for (int i = 0; i<30; i++)
                    bestMatches.push_back(matches[index.at<int>(i, 0)]);
                Mat result;
                drawMatches(img1, keyImg1, img2, keyImg2, bestMatches, result);
                namedWindow(*itDesc+": "+*itMatcher, WINDOW_AUTOSIZE);
                imshow(*itDesc + ": " + *itMatcher, result);
                FileStorage fs(*itDesc+"_"+*itMatcher+"_"+fileName[0]+"_"+fileName[1]+".xml", FileStorage::WRITE);
                fs<<"Matches"<<matches;
                vector<DMatch>::iterator it;
                cout << "Index \tIndex \tindex \tdistance\n";
                cout << "in img1\tin img2\timage\t\n";
                for (it = matches.begin(); it != matches.end(); it++)
                    cout << it->queryIdx << "\t" << it->trainIdx << "\t" << it->imgIdx << "\t" << it->distance<<"\n";
                waitKey();
            }
        }
        catch (Exception& e){
            cout << "Feature : " << *itDesc << "\n";
            if (itMatcher != typeAlgoMatch.end())
                cout << "Matcher : " << *itMatcher << "\n";
            cout<<e.msg<<endl;
        }
    }
    return 0;
}
<commit_msg>trailing whitespace<commit_after>#include <opencv2/opencv.hpp>
#include <vector>
#include <iostream>

using namespace std;
using namespace cv;

int main(void)
{
    vector<String> typeAlgoMatch;
    typeAlgoMatch.push_back("BruteForce");
    typeAlgoMatch.push_back("BruteForce-Hamming");
    typeAlgoMatch.push_back("BruteForce-Hamming(2)");

    vector<String> typeDesc;
    typeDesc.push_back("AKAZE");
    typeDesc.push_back("ORB");
    typeDesc.push_back("BRISK");

    String  dataFolder("../data/");
    vector<String> fileName;
    fileName.push_back("basketball1.png");
    fileName.push_back("basketball2.png");

    Mat img1 = imread(dataFolder+fileName[0], IMREAD_GRAYSCALE);
    Mat img2 = imread(dataFolder+fileName[1], IMREAD_GRAYSCALE);

    Ptr<Feature2D> b;

    vector<String>::iterator itDesc;
// Descriptor loop
    for (itDesc = typeDesc.begin(); itDesc != typeDesc.end(); itDesc++){
        Ptr<DescriptorMatcher> descriptorMatcher;
        vector<DMatch> matches;	        /*<! Match between img and img2*/
        vector<KeyPoint> keyImg1;		/*<! keypoint  for img1 */
        vector<KeyPoint> keyImg2;		/*<! keypoint  for img2 */
        Mat descImg1, descImg2;         /*<! Descriptor for img1 and img2 */
        vector<String>::iterator itMatcher = typeAlgoMatch.end();
        if (*itDesc == "AKAZE"){
            b = AKAZE::create();
        }
        if (*itDesc == "ORB"){
            b = ORB::create();
        }
        else if (*itDesc == "BRISK"){
            b = BRISK::create();
        }
        try {
            b->detect(img1, keyImg1, Mat());
            b->compute(img1, keyImg1, descImg1);
            b->detectAndCompute(img2, Mat(),keyImg2, descImg2,false);
 // Match method loop
             for (itMatcher = typeAlgoMatch.begin(); itMatcher != typeAlgoMatch.end(); itMatcher++){
                descriptorMatcher = DescriptorMatcher::create(*itMatcher);
                descriptorMatcher->match(descImg1, descImg2, matches, Mat());
 // Keep best matches only to have a nice drawing
                Mat index;
                Mat tab(matches.size(), 1, CV_32F);
                for (int i = 0; i<matches.size(); i++)
                    tab.at<float>(i, 0) = matches[i].distance;
                sortIdx(tab, index, SORT_EVERY_COLUMN + SORT_ASCENDING);
                vector<DMatch> bestMatches;
                for (int i = 0; i<30; i++)
                    bestMatches.push_back(matches[index.at<int>(i, 0)]);
                Mat result;
                drawMatches(img1, keyImg1, img2, keyImg2, bestMatches, result);
                namedWindow(*itDesc+": "+*itMatcher, WINDOW_AUTOSIZE);
                imshow(*itDesc + ": " + *itMatcher, result);
                FileStorage fs(*itDesc+"_"+*itMatcher+"_"+fileName[0]+"_"+fileName[1]+".xml", FileStorage::WRITE);
                fs<<"Matches"<<matches;
                vector<DMatch>::iterator it;
                cout << "Index \tIndex \tindex \tdistance\n";
                cout << "in img1\tin img2\timage\t\n";
                for (it = matches.begin(); it != matches.end(); it++)
                    cout << it->queryIdx << "\t" << it->trainIdx << "\t" << it->imgIdx << "\t" << it->distance<<"\n";
                waitKey();
            }
        }
        catch (Exception& e){
            cout << "Feature : " << *itDesc << "\n";
            if (itMatcher != typeAlgoMatch.end())
                cout << "Matcher : " << *itMatcher << "\n";
            cout<<e.msg<<endl;
        }
    }
    return 0;
}
<|endoftext|>


<commit_before>#include <stdlib.h>
#include <algorithm>
#include <iostream>
#include <vector>
#include <unistd.h>
#include <dirent.h>
#include <fstream>
#include <sstream>
#include <queue>
#include "omp.h"

// Contains the various options the user can pass ptgz.
struct Settings {
	Settings(): extract(),
				compress(),
   				verbose(),
				keep(),
				output() {}
	bool extract;
	bool compress;
	bool verbose;
	bool keep;
	bool output;
	std::string name;
};

// Checks if the user asks for help.
// Provides usage information to the user.
// Parameters: argc (int) number of cli arguments.
// 			   argv (char *[]) user provided arguments.
void helpCheck(int argc, char *argv[]) {
	if (argc == 1) {
		std::cout << "ERROR: ptgz was passed no parameters. \"ptgz -h\" for help." << std::endl;
		exit(0);
	}

	if (argv[1] == std::string("-h") || argv[1] == std::string("--help")) {
		std::cout << "\nptgz - Parallel Tar GZ by Ryan Chui (2017)\n" << std::endl;
		std::cout << "    ptgz is a custom multi-threaded C++ file archiving utility to quickly bundle millions of files in \n";
		std::cout << "    terrabyte sized directories into a single file. ptgz was developed at the National Center for \n";
		std::cout << "    Supercomputing Applications.\n" << std::endl;
		std::cout << "    Usage:\n";
		std::cout << "    If you are compressing, your current working directory should be parent directory of all directories you\n";
		std::cout << "    want to archive. If you are extracting, your current working directory should be the same as your archive.\n" << std::endl;
		std::cout << "    ptgz [-c|-k|-v|-x] <archive>\n" << std::endl;
		std::cout << "    Modes:\n";
		std::cout << "    -c    Compression           ptgz will perform file compression. The current directory and all of it's\n";
		std::cout << "                                children will be archived and added to a single tarball. <archive> will be \n";
		std::cout << "                                prefix of the ptgz archive created.\n" << std::endl;
		std::cout << "    -k    Keep Archive          ptgz will not delete the ptgz archive it has been passed to extract. \"-x\" \n";
		std::cout << "                                must also be used to use this option.\n" << std::endl;
		std::cout << "    -v    Enable Verbose        ptgz will print the commands as they are called to STDOUT\n" << std::endl;
		std::cout << "    -x    Extraction            ptgz will perform file extraction from an archive. The passed ptgz archive\n";
		std::cout << "                                will be unpacked and split into its component files. <archive> should be the\n";
		std::cout << "                                the name of the archive to extract." << std::endl;
		exit(0);
	}
}

// Gets the parameters passed by the user and stores them.
// Parameters: argc (int) number of cli arguments.
// 			   argv (char *[]) user provided arguments.
// 			   instance (Settings *) user argument storage.
void getSettings(int argc, char *argv[], Settings *instance) {
	// Get all passed arguments
	std::queue<std::string> settings;
	for (int i = 1; i < argc; ++i) {
		settings.push(argv[i]);
	}

	// Continue to check until there are no more passed arguments.
	while (!settings.empty()) {
		std::string arg = settings.front();

		if (arg == "-x") {
			if ((*instance).compress) {
				std::cout << "ERROR: ptgz cannot both compress and extract. \"ptgz -h\" for help." << std::endl;
				exit(0);
			}
			(*instance).extract = true;
		} else if (arg == "-c") {
			if ((*instance).extract) {
				std::cout << "ERROR: ptgz cannot both compress and extract. \"ptgz -h\" for help." << std::endl;
				exit(0);
			}
			(*instance).compress = true;
		} else if (arg == "-v"){
			(*instance).verbose = true;
		} else if (arg == "-o") {
			(*instance).output = true;
		} else if (arg == "-k") {
			(*instance).keep = true;
		} else {
			if (settings.size() > 1) {
				std::cout << "ERROR: ptgz was called incorrectly. \"ptgz -h\" for help." << std::endl;
				exit(0);
			}
			(*instance).output = true;
			(*instance).name = arg;
		}

		settings.pop();
	}

	if (!(*instance).output) {
		std::cout << "ERROR: No output file name given. \"ptgz -h\" for help." << std::endl;
		exit(0);
	} else if ((*instance).keep && !(*instance).extract) {
		std::cout << "ERROR: Can't use keep option without extract. \"ptgz -h\" for help." << std::endl;
	}
}

// Finds the number of files in the space to store.
// Parameters: numFiles (int *) number of files.
// 			   cwd (const char *) current working directory.
void findAll(int *numFiles, const char *cwd) {
	DIR *dir;
	struct dirent *ent;

	// Check if cwd is a directory
	if ((dir = opendir(cwd)) != NULL) {
		// Get all file paths within directory.
		while ((ent = readdir (dir)) != NULL) {
			std::string fileBuff = std::string(ent -> d_name);
			if (fileBuff != "." && fileBuff != "..") {
				DIR *dir2;
				std::string filePath = std::string(cwd) + "/" + fileBuff;
				// Check if file path is a directory.
				if ((dir2 = opendir(filePath.c_str())) != NULL) {
					closedir(dir2);
					findAll(numFiles, filePath.c_str());
				} else {
					*numFiles += 1;
				}
			}
		}
		closedir(dir);
	}
}

// Gets the paths for all files in the space to store.
// Parameters: filePaths (std::vector<std::string> *) holder for all file paths.
// 			   cwd (const char *) current working directory.
// 			   rootPath (std::string) path from the root of the directory to be stored.
void getPaths(std::vector<std::string> *filePaths, const char *cwd, std::string rootPath) {
	DIR *dir;
	struct dirent *ent;

	// Check if cwd is a directory
	if ((dir = opendir(cwd)) != NULL) {
		// Get all file paths within directory.
		while ((ent = readdir (dir)) != NULL) {
			std::string fileBuff = std::string(ent -> d_name);
			if (fileBuff != "." && fileBuff != "..") {
				DIR *dir2;
				std::string filePath = std::string(cwd) + "/" + fileBuff;
				// Check if file path is a directory.
				if ((dir2 = opendir(filePath.c_str())) != NULL) {
					closedir(dir2);
					getPaths(filePaths, filePath.c_str(), rootPath + fileBuff + "/");
				} else {
					filePaths->push_back(rootPath + fileBuff);
				}
			}
		}
		closedir(dir);
	}
}

// Divides files into blocks.
// Compresses each block into a single file.
// Combines all compressed blocks into a single file.
// Removes temporary blocks and header files.
// Parameters: filePaths (std::vector<std::string> *) holder for all file paths.
// 			   name (std::string) user given name for storage file.
// 			   verbose (bool) user option for verbose output.
void compression(std::vector<std::string> *filePaths, std::string name, bool verbose) {
	std::random_shuffle(filePaths->begin(), filePaths->end());
	unsigned long long int filePathSize = filePaths->size();
	unsigned long long int blockSize = (filePathSize / (omp_get_max_threads() * 10)) + 1;
	std::vector<std::string> *tarNames = new std::vector<std::string>(filePathSize / blockSize + 1);

	// Gzips the blocks of files into a single compressed file
	#pragma omp parallel for schedule(dynamic)
	for (int i = 0; i < omp_get_max_threads() * 10; ++i) {
		unsigned long long int start = blockSize * i;
		if (start < filePathSize) {
			// Store the name of each file for a block owned by each thread.
			// Each thread will use the file to tar and gzip compress their block.
			std::ofstream tmp;
			tmp.open(std::to_string(i) + "." + name + ".ptgz.tmp", std::ios_base::app);
			std::string gzCommand = "GZIP=-1 tar -cz -T " + std::to_string(i) + "." + name + ".ptgz.tmp -f " + std::to_string(i) + "." + name + ".tar.gz";
			for (unsigned long long int j = start; j < std::min(start + blockSize, filePathSize); ++j) {
				tmp << filePaths->at(j) + "\n";
			}

			if (verbose) {
				std::cout << gzCommand + "\n";
			}

			tmp.close();
			system(gzCommand.c_str());
			tarNames->at(i) = std::to_string(i) + "." + name + ".tar.gz";
		}
	}

	// Combines gzipped blocks together into a single tarball.
	// Write tarball names into an idx file for extraction.
	std::ofstream idx, tmp;
	idx.open(name + ".ptgz.idx", std::ios_base::app);
	std::string tarCommand = "tar -c -T " + name + ".ptgz.idx -f " + name + ".ptgz.tar";
	for (unsigned long long int i = 0; i < tarNames->size(); ++i) {
		idx << tarNames->at(i) + "\n";
	}
	idx << name + ".ptgz.idx" + "\n";
	idx.close();

	if (verbose) {
		std::cout << tarCommand + "\n";
	}

	system(tarCommand.c_str());

	// Removes all temporary blocks and idx file.
	#pragma omp parallel for schedule(static)
	for (unsigned long long int i = 0; i < tarNames->size(); ++i) {
		std::string rmCommand = tarNames->at(i);
		if (verbose) {
			std::cout << "remove(" + rmCommand + ")\n";
		}
		if (remove(rmCommand.c_str())) {
			std::cout << "ERROR: " + rmCommand + " could not be removed.\n";
		}

		rmCommand = std::to_string(i) + "." + name + ".ptgz.tmp";
		if (verbose) {
			std::cout << "remove(" + rmCommand + ")\n";
		}
		if (remove(rmCommand.c_str())) {
			std::cout << "ERROR: " + rmCommand + " could not be removed.\n";
		}
	}

	std::string rmCommand;
	if (verbose) {
		std::cout << "remove(" + name + ".ptgz.idx)\n";
	}
	rmCommand = name + ".ptgz.idx";
	if (remove(rmCommand.c_str())) {
		std::cout << "ERROR: " + rmCommand + " could not be removed.\n";
	}

	tarNames->clear();
	delete(tarNames);
}

// Unpacks the archive.
// Reads in all the files from the index file.
// Unpacks each file.
// Deletes all temporary file blocks and header files.
// Parameters: filePaths (std::vector<std::string> *) holder for all file paths.
// 			   name (std::string) name of ptgz archive file.
// 			   verbose (bool) user option for verbose output.
// 			   keep (bool) user option for keeping ptgz archive.
void extraction(std::vector<std::string> *filePaths, std::string name, bool verbose, bool keep) {
	// Unpack the 1st layer tarball
	std::string exCommand = "tar xf " + name;
	if (verbose) {
		std::cout << exCommand + "\n";
	}
	// system(exCommand.c_str());

	// Get the name from the name of the 1st layer tarball
	for (int i = 0; i < 9; ++i) {
		name.pop_back();
	}

	// Read in all tar.gz files form the ptgz.idx file
	// Delete the ptgz.idx file
	std::ifstream idx;
	std::string line;
	idx.open(name + ".ptgz.idx", std::ios_base::in);
	while (std::getline(idx, line)) {
		filePaths->push_back(line);
	}
	idx.close();
	std::string idxRmCommand = filePaths->back();
	remove(idxRmCommand.c_str());
	filePaths->pop_back();

	// Unpack each tar.gz file
	#pragma omp parallel for schedule(dynamic)
	for (int i = 0; i < filePaths->size(); ++i) {
		std::string gzCommand = "tar xzf " + filePaths->at(i);
		if (verbose) {
			std::cout << gzCommand + "\n";
		}
		system(gzCommand.c_str());
	}

	// Delete each tar.gz file
	#pragma omp parallel for schedule(static)
	for (int i = 0; i < filePaths->size(); ++i) {
		std::string gzRmCommand = filePaths->at(i);
		if (verbose) {
			std::cout << "remove(" + gzRmCommand + ")\n";
		}
		remove(gzRmCommand.c_str());
	}

	// Decided whether or not to keep the ptgz.tar archive
	if (!keep) {
		std::string tarRmCommand = name + ".ptgz.tar";
		if (verbose) {
			std::cout << "remove(" + tarRmCommand + ")\n";
		}
		remove(tarRmCommand.c_str());
	}
}

char cwd [PATH_MAX];

// Checks to see if the user asks for help.
// Gathers the user provided settings for ptgz.
// Finds the number of files that need to be stored.
// Gathers the file paths of all files to be stored.
// Either compresses the files or extracts the ptgz.tar archive.
int main(int argc, char *argv[]) {
	Settings *instance = new Settings;
	int *numFiles = new int(0);
	std::vector<std::string> *filePaths = new std::vector<std::string>();

	helpCheck(argc, argv);
	getSettings(argc, argv, instance);
	getcwd(cwd, PATH_MAX);

	if ((*instance).compress) {
		findAll(numFiles, cwd);
		getPaths(filePaths, cwd, "");
		compression(filePaths, (*instance).name, (*instance).verbose);
	} else {
		extraction(filePaths, (*instance).name, (*instance).verbose, (*instance).keep);
	}

	delete(instance);
	delete(numFiles);
	filePaths->clear();
	delete(filePaths);
	return 0;
}
<commit_msg>Update ptgz.cpp<commit_after>#include <stdlib.h>
#include <algorithm>
#include <iostream>
#include <vector>
#include <unistd.h>
#include <dirent.h>
#include <fstream>
#include <sstream>
#include <queue>
#include "omp.h"

// Contains the various options the user can pass ptgz.
struct Settings {
	Settings(): extract(),
				compress(),
   				verbose(),
				keep(),
				output() {}
	bool extract;
	bool compress;
	bool verbose;
	bool keep;
	bool output;
	std::string name;
};

// Checks if the user asks for help.
// Provides usage information to the user.
// Parameters: argc (int) number of cli arguments.
// 			   argv (char *[]) user provided arguments.
void helpCheck(int argc, char *argv[]) {
	if (argc == 1) {
		std::cout << "ERROR: ptgz was passed no parameters. \"ptgz -h\" for help." << std::endl;
		exit(0);
	}

	if (argv[1] == std::string("-h") || argv[1] == std::string("--help")) {
		std::cout << "\nptgz - Parallel Tar GZ by Ryan Chui (2017)\n" << std::endl;
		std::cout << "    ptgz is a custom multi-threaded C++ file archiving utility to quickly bundle millions of files in \n";
		std::cout << "    terrabyte sized directories into a single file. ptgz was developed at the National Center for \n";
		std::cout << "    Supercomputing Applications.\n" << std::endl;
		std::cout << "    Usage:\n";
		std::cout << "    If you are compressing, your current working directory should be parent directory of all directories you\n";
		std::cout << "    want to archive. If you are extracting, your current working directory should be the same as your archive.\n" << std::endl;
		std::cout << "    ptgz [-c|-k|-v|-x] <archive>\n" << std::endl;
		std::cout << "    Modes:\n";
		std::cout << "    -c    Compression           ptgz will perform file compression. The current directory and all of it's\n";
		std::cout << "                                children will be archived and added to a single tarball. <archive> will be \n";
		std::cout << "                                prefix of the ptgz archive created.\n" << std::endl;
		std::cout << "    -k    Keep Archive          ptgz will not delete the ptgz archive it has been passed to extract. \"-x\" \n";
		std::cout << "                                must also be used to use this option.\n" << std::endl;
		std::cout << "    -v    Enable Verbose        ptgz will print the commands as they are called to STDOUT\n" << std::endl;
		std::cout << "    -x    Extraction            ptgz will perform file extraction from an archive. The passed ptgz archive\n";
		std::cout << "                                will be unpacked and split into its component files. <archive> should be the\n";
		std::cout << "                                the name of the archive to extract." << std::endl;
		exit(0);
	}
}

// Gets the parameters passed by the user and stores them.
// Parameters: argc (int) number of cli arguments.
// 			   argv (char *[]) user provided arguments.
// 			   instance (Settings *) user argument storage.
void getSettings(int argc, char *argv[], Settings *instance) {
	// Get all passed arguments
	std::queue<std::string> settings;
	for (int i = 1; i < argc; ++i) {
		settings.push(argv[i]);
	}

	// Continue to check until there are no more passed arguments.
	while (!settings.empty()) {
		std::string arg = settings.front();

		if (arg == "-x") {
			if ((*instance).compress) {
				std::cout << "ERROR: ptgz cannot both compress and extract. \"ptgz -h\" for help." << std::endl;
				exit(0);
			}
			(*instance).extract = true;
		} else if (arg == "-c") {
			if ((*instance).extract) {
				std::cout << "ERROR: ptgz cannot both compress and extract. \"ptgz -h\" for help." << std::endl;
				exit(0);
			}
			(*instance).compress = true;
		} else if (arg == "-v"){
			(*instance).verbose = true;
		} else if (arg == "-o") {
			(*instance).output = true;
		} else if (arg == "-k") {
			(*instance).keep = true;
		} else {
			if (settings.size() > 1) {
				std::cout << "ERROR: ptgz was called incorrectly. \"ptgz -h\" for help." << std::endl;
				exit(0);
			}
			(*instance).output = true;
			(*instance).name = arg;
		}

		settings.pop();
	}

	if (!(*instance).output) {
		std::cout << "ERROR: No output file name given. \"ptgz -h\" for help." << std::endl;
		exit(0);
	} else if ((*instance).keep && !(*instance).extract) {
		std::cout << "ERROR: Can't use keep option without extract. \"ptgz -h\" for help." << std::endl;
	}
}

// Finds the number of files in the space to store.
// Parameters: numFiles (int *) number of files.
// 			   cwd (const char *) current working directory.
void findAll(int *numFiles, const char *cwd) {
	DIR *dir;
	struct dirent *ent;

	// Check if cwd is a directory
	if ((dir = opendir(cwd)) != NULL) {
		// Get all file paths within directory.
		while ((ent = readdir (dir)) != NULL) {
			std::string fileBuff = std::string(ent -> d_name);
			if (fileBuff != "." && fileBuff != "..") {
				DIR *dir2;
				std::string filePath = std::string(cwd) + "/" + fileBuff;
				// Check if file path is a directory.
				if ((dir2 = opendir(filePath.c_str())) != NULL) {
					closedir(dir2);
					findAll(numFiles, filePath.c_str());
				} else {
					*numFiles += 1;
				}
			}
		}
		closedir(dir);
	}
}

// Gets the paths for all files in the space to store.
// Parameters: filePaths (std::vector<std::string> *) holder for all file paths.
// 			   cwd (const char *) current working directory.
// 			   rootPath (std::string) path from the root of the directory to be stored.
void getPaths(std::vector<std::string> *filePaths, const char *cwd, std::string rootPath) {
	DIR *dir;
	struct dirent *ent;

	// Check if cwd is a directory
	if ((dir = opendir(cwd)) != NULL) {
		// Get all file paths within directory.
		while ((ent = readdir (dir)) != NULL) {
			std::string fileBuff = std::string(ent -> d_name);
			if (fileBuff != "." && fileBuff != "..") {
				DIR *dir2;
				std::string filePath = std::string(cwd) + "/" + fileBuff;
				// Check if file path is a directory.
				if ((dir2 = opendir(filePath.c_str())) != NULL) {
					closedir(dir2);
					getPaths(filePaths, filePath.c_str(), rootPath + fileBuff + "/");
				} else {
					filePaths->push_back(rootPath + fileBuff);
				}
			}
		}
		closedir(dir);
	}
}

// Divides files into blocks.
// Compresses each block into a single file.
// Combines all compressed blocks into a single file.
// Removes temporary blocks and header files.
// Parameters: filePaths (std::vector<std::string> *) holder for all file paths.
// 			   name (std::string) user given name for storage file.
// 			   verbose (bool) user option for verbose output.
void compression(std::vector<std::string> *filePaths, std::string name, bool verbose) {
	std::random_shuffle(filePaths->begin(), filePaths->end());
	unsigned long long int filePathSize = filePaths->size();
	unsigned long long int blockSize = (filePathSize / (omp_get_max_threads() * 10)) + 1;
	std::vector<std::string> *tarNames = new std::vector<std::string>(filePathSize / blockSize + 1);

	// Gzips the blocks of files into a single compressed file
	#pragma omp parallel for schedule(dynamic)
	for (int i = 0; i < omp_get_max_threads() * 10; ++i) {
		unsigned long long int start = blockSize * i;
		if (start < filePathSize) {
			// Store the name of each file for a block owned by each thread.
			// Each thread will use the file to tar and gzip compress their block.
			std::ofstream tmp;
			tmp.open(std::to_string(i) + "." + name + ".ptgz.tmp", std::ios_base::app);
			std::string gzCommand = "GZIP=-1 tar -cz -T " + std::to_string(i) + "." + name + ".ptgz.tmp -f " + std::to_string(i) + "." + name + ".tar.gz";
			for (unsigned long long int j = start; j < std::min(start + blockSize, filePathSize); ++j) {
				tmp << filePaths->at(j) + "\n";
			}

			if (verbose) {
				std::cout << gzCommand + "\n";
			}

			tmp.close();
			system(gzCommand.c_str());
			tarNames->at(i) = std::to_string(i) + "." + name + ".tar.gz";
		}
	}

	// Combines gzipped blocks together into a single tarball.
	// Write tarball names into an idx file for extraction.
	std::ofstream idx, tmp;
	idx.open(name + ".ptgz.idx", std::ios_base::app);
	std::string tarCommand = "tar -c -T " + name + ".ptgz.idx -f " + name + ".ptgz.tar";
	for (unsigned long long int i = 0; i < tarNames->size(); ++i) {
		idx << tarNames->at(i) + "\n";
	}
	idx << name + ".ptgz.idx" + "\n";
	idx.close();

	if (verbose) {
		std::cout << tarCommand + "\n";
	}

	system(tarCommand.c_str());

	// Removes all temporary blocks and idx file.
	#pragma omp parallel for schedule(static)
	for (unsigned long long int i = 0; i < tarNames->size(); ++i) {
		std::string rmCommand = tarNames->at(i);
		if (verbose) {
			std::cout << "remove(" + rmCommand + ")\n";
		}
		if (remove(rmCommand.c_str())) {
			std::cout << "ERROR: " + rmCommand + " could not be removed.\n";
		}

		rmCommand = std::to_string(i) + "." + name + ".ptgz.tmp";
		if (verbose) {
			std::cout << "remove(" + rmCommand + ")\n";
		}
		if (remove(rmCommand.c_str())) {
			std::cout << "ERROR: " + rmCommand + " could not be removed.\n";
		}
	}

	std::string rmCommand;
	if (verbose) {
		std::cout << "remove(" + name + ".ptgz.idx)\n";
	}
	rmCommand = name + ".ptgz.idx";
	if (remove(rmCommand.c_str())) {
		std::cout << "ERROR: " + rmCommand + " could not be removed.\n";
	}

	tarNames->clear();
	delete(tarNames);
}

// Unpacks the archive.
// Reads in all the files from the index file.
// Unpacks each file.
// Deletes all temporary file blocks and header files.
// Parameters: filePaths (std::vector<std::string> *) holder for all file paths.
// 			   name (std::string) name of ptgz archive file.
// 			   verbose (bool) user option for verbose output.
// 			   keep (bool) user option for keeping ptgz archive.
void extraction(std::vector<std::string> *filePaths, std::string name, bool verbose, bool keep) {
	// Unpack the 1st layer tarball
	std::string exCommand = "tar xf " + name;
	if (verbose) {
		std::cout << exCommand + "\n";
	}
	system(exCommand.c_str());

	// Get the name from the name of the 1st layer tarball
	for (int i = 0; i < 9; ++i) {
		name.pop_back();
	}

	// Read in all tar.gz files form the ptgz.idx file
	// Delete the ptgz.idx file
	std::ifstream idx;
	std::string line;
	idx.open(name + ".ptgz.idx", std::ios_base::in);
	while (std::getline(idx, line)) {
		filePaths->push_back(line);
	}
	idx.close();
	std::string idxRmCommand = filePaths->back();
	remove(idxRmCommand.c_str());
	filePaths->pop_back();

	// Unpack each tar.gz file
	#pragma omp parallel for schedule(dynamic)
	for (int i = 0; i < filePaths->size(); ++i) {
		std::string gzCommand = "tar xzf " + filePaths->at(i);
		if (verbose) {
			std::cout << gzCommand + "\n";
		}
		system(gzCommand.c_str());
	}

	// Delete each tar.gz file
	#pragma omp parallel for schedule(static)
	for (int i = 0; i < filePaths->size(); ++i) {
		std::string gzRmCommand = filePaths->at(i);
		if (verbose) {
			std::cout << "remove(" + gzRmCommand + ")\n";
		}
		remove(gzRmCommand.c_str());
	}

	// Decided whether or not to keep the ptgz.tar archive
	if (!keep) {
		std::string tarRmCommand = name + ".ptgz.tar";
		if (verbose) {
			std::cout << "remove(" + tarRmCommand + ")\n";
		}
		remove(tarRmCommand.c_str());
	}
}

char cwd [PATH_MAX];

// Checks to see if the user asks for help.
// Gathers the user provided settings for ptgz.
// Finds the number of files that need to be stored.
// Gathers the file paths of all files to be stored.
// Either compresses the files or extracts the ptgz.tar archive.
int main(int argc, char *argv[]) {
	Settings *instance = new Settings;
	int *numFiles = new int(0);
	std::vector<std::string> *filePaths = new std::vector<std::string>();

	helpCheck(argc, argv);
	getSettings(argc, argv, instance);
	getcwd(cwd, PATH_MAX);

	if ((*instance).compress) {
		findAll(numFiles, cwd);
		getPaths(filePaths, cwd, "");
		compression(filePaths, (*instance).name, (*instance).verbose);
	} else {
		extraction(filePaths, (*instance).name, (*instance).verbose, (*instance).keep);
	}

	delete(instance);
	delete(numFiles);
	filePaths->clear();
	delete(filePaths);
	return 0;
}
<|endoftext|>


<commit_before>#include <stdlib.h>
#include <algorithm>
#include <iostream>
#include <vector>
#include <unistd.h>
#include <dirent.h>
#include <fstream>
#include <queue>
#include "omp.h"

// Contains the various options the user can pass ptgz.
struct Settings {
	Settings(): extract(),
				compress(),
   				verbose(),
				output() {}
	bool extract;
	bool compress;
	bool verbose;
	bool output;
	std::string name;
};

// Checks if the user asks for help.
// Provides usage information to the user.
// Parameters: argc (int) number of cli arguments.
// 			   argv (char *[]) user provided arguments.
void helpCheck(int argc, char *argv[]) {
	if (argc == 1) {
		std::cout << "ERROR: ptgz was passed no parameters. \"ptgz -h\" for help." << std::endl;
		exit(0);
	}

	if (argv[1] == std::string("-h") || argv[1] == std::string("--help")) {
		std::cout << "\nptgz - Parallel Tar GZ by Ryan Chui (2017)\n" << std::endl;
		exit(0);
	}
}

// Gets the parameters passed by the user and stores them.
// Parameters: argc (int) number of cli arguments.
// 			   argv (char *[]) user provided arguments.
// 			   instance (Settings *) user argument storage.
void getSettings(int argc, char *argv[], Settings *instance) {
	// Get all passed arguments
	std::queue<std::string> settings;
	for (int i = 1; i < argc; ++i) {
		settings.push(argv[i]);
	}

	// Continue to check until there are no more passed arguments.
	while (!settings.empty()) {
		std::string arg = settings.front();

		if (arg == "-x") {
			if ((*instance).compress) {
				std::cout << "ERROR: ptgz cannot both compress and extract. \"ptgz -h\" for help." << std::endl;
				exit(0);
			}
			(*instance).extract = true;
		} else if (arg == "-c") {
			if ((*instance).extract) {
				std::cout << "ERROR: ptgz cannot both compress and extract. \"ptgz -h\" for help." << std::endl;
				exit(0);
			}
			(*instance).compress = true;
		} else if (arg == "-v"){
			(*instance).verbose = true;
		} else if (arg == "-o") {
			(*instance).output = true;
		} else {
			if (settings.size() > 1) {
				std::cout << "ERROR: ptgz was called incorrectly. \"ptgz -h\" for help." << std::endl;
				exit(0);
			}
			(*instance).output = true;
			(*instance).name = arg;
		}

		settings.pop();
	}

	if (!(*instance).output) {
		std::cout << "ERROR: No output file name given. \"ptgz -h\" for help." << std::endl;
		exit(0);
	}
}

// Finds the number of files in the space to store.
// Parameters: numFiles (int *) number of files.
// 			   cwd (const char *) current working directory.
void findAll(int *numFiles, const char *cwd) {
	DIR *dir;
	struct dirent *ent;

	// Check if cwd is a directory
	if ((dir = opendir(cwd)) != NULL) {
		// Get all file paths within directory.
		while ((ent = readdir (dir)) != NULL) {
			std::string fileBuff = std::string(ent -> d_name);
			if (fileBuff != "." && fileBuff != "..") {
				DIR *dir2;
				std::string filePath = std::string(cwd) + "/" + fileBuff;
				// Check if file path is a directory.
				if ((dir2 = opendir(filePath.c_str())) != NULL) {
					closedir(dir2);
					findAll(numFiles, filePath.c_str());
				} else {
					*numFiles += 1;
				}
			}
		}
		closedir(dir);
	}
}

// Gets the paths for all files in the space to store.
// Parameters: filePaths (std::vector<std::string> *) holder for all file paths.
// 			   cwd (const char *) current working directory.
// 			   rootPath (std::string) path from the root of the directory to be stored.
void getPaths(std::vector<std::string> *filePaths, const char *cwd, std::string rootPath) {
	DIR *dir;
	struct dirent *ent;

	// Check if cwd is a directory
	if ((dir = opendir(cwd)) != NULL) {
		// Get all file paths within directory.
		while ((ent = readdir (dir)) != NULL) {
			std::string fileBuff = std::string(ent -> d_name);
			if (fileBuff != "." && fileBuff != "..") {
				DIR *dir2;
				std::string filePath = std::string(cwd) + "/" + fileBuff;
				// Check if file path is a directory.
				if ((dir2 = opendir(filePath.c_str())) != NULL) {
					closedir(dir2);
					getPaths(filePaths, filePath.c_str(), rootPath + fileBuff + "/");
				} else {
					filePaths->push_back(rootPath + fileBuff);
				}
			}
		}
		closedir(dir);
	}
}

// Divides files into blocks.
// Compresses each block into a single file.
// Combines all compressed blocks into a single file.
// Removes temporary blocks and header files.
// Parameters: filePaths (std::vector<std::string> *) holder for all file paths.
// 			   name (std::string) user given name for storage file.
// 			   verbose (bool) user option for verbose output.
void compression(std::vector<std::string> *filePaths, std::string name, bool verbose) {
	std::random_shuffle(filePaths->begin(), filePaths->end());
	unsigned long long int filePathSize = filePaths->size();
	unsigned long long int blockSize = (filePathSize / (omp_get_max_threads() * 10)) + 1;
	std::vector<std::string> *tarNames = new std::vector<std::string>(filePathSize / blockSize + 1);

	// Gzips the blocks of files into a single compressed file
	#pragma omp parallel for schedule(dynamic)
	for (int i = 0; i < omp_get_max_threads() * 10; ++i) {
		unsigned long long int start = blockSize * i;
		if (start < filePathSize) {
			// Store the name of each file for a block owned by each thread.
			// Each thread will use the file to tar and gzip compress their block.
			std::ofstream tmp;
			tmp.open(std::to_string(i) + "." + name + ".ptgz.tmp", std::ios_base::app);
			std::string gzCommand = "GZIP=-1 tar -cz -T " + std::to_string(i) + "." + name + ".ptgz.tmp -f " + std::to_string(i) + "." + name + ".tar.gz";
			for (unsigned long long int j = start; j < std::min(start + blockSize, filePathSize); ++j) {
				tmp << filePaths->at(j) + "\n";
			}

			if (verbose) {
				std::cout << gzCommand + "\n";
			}

			tmp.close();
			system(gzCommand.c_str());
			tarNames->at(i) = std::to_string(i) + "." + name + ".tar.gz";
		}
	}

	// Combines gzipped blocks together into a single tarball.
	// Write tarball names into an idx file for extraction.
	std::ofstream idx, tmp;
	idx.open(name + ".ptgz.idx", std::ios_base::app);
	std::string tarCommand = "tar -c -T " + name + ".ptgz.idx -f " + name + ".ptgz.tar";
	for (unsigned long long int i = 0; i < tarNames->size(); ++i) {
		idx << tarNames->at(i) + "\n";
	}
	idx << name + ".ptgz.idx" + "\n";
	idx.close();

	if (verbose) {
		std::cout << tarCommand + "\n";
	}

	system(tarCommand.c_str());

	// Removes all temporary blocks and idx file.
	#pragma omp parallel for schedule(static)
	for (unsigned long long int i = 0; i < tarNames->size(); ++i) {
		std::string rmCommand = tarNames->at(i);
		if (verbose) {
			std::cout << "remove(" + rmCommand + ")\n";
		}
		if (remove(rmCommand.c_str())) {
			std::cout << "ERROR: " + rmCommand + " could not be removed.\n";
		}

		rmCommand = std::to_string(i) + "." + name + ".ptgz.tmp";
		if (verbose) {
			std::cout << "remove(" + rmCommand + ")\n";
		}
		if (remove(rmCommand.c_str())) {
			std::cout << "ERROR: " + rmCommand + " could not be removed.\n";
		}
	}

	std::string rmCommand;
	if (verbose) {
		std::cout << "remove(" + name + ".ptgz.idx)\n";
	}
	rmCommand = name + ".ptgz.idx";
	if (remove(rmCommand.c_str())) {
		std::cout << "ERROR: " + rmCommand + " could not be removed.\n";
	}

	tarNames->clear();
	delete(tarNames);
}

void extraction(std::vector<std::string> *filePaths, std::string name, bool verbose) {
	exCommand = "tar xf " + name;
	system(exCommand.c_str());
}

char cwd [PATH_MAX];

// Checks to see if the user asks for help.
// Gathers the user provided settings for ptgz.
// Finds the number of files that need to be stored.
// Gathers the file paths of all files to be stored.
// Either compresses the files or extracts the ptgz.tar archive.
int main(int argc, char *argv[]) {
	Settings *instance = new Settings;
	int *numFiles = new int(0);
	std::vector<std::string> *filePaths = new std::vector<std::string>();

	helpCheck(argc, argv);
	getSettings(argc, argv, instance);
	getcwd(cwd, PATH_MAX);

	if ((*instance).compress) {
		findAll(numFiles, cwd);
		getPaths(filePaths, cwd, "");
		compression(filePaths, (*instance).name, (*instance).verbose);
	} else {
		extraction(filePaths, (*instance).name, (*instance).verbose);
	}

	delete(instance);
	delete(numFiles);
	filePaths->clear();
	delete(filePaths);
	return 0;
}
<commit_msg>Forgot to declare exCommand<commit_after>#include <stdlib.h>
#include <algorithm>
#include <iostream>
#include <vector>
#include <unistd.h>
#include <dirent.h>
#include <fstream>
#include <queue>
#include "omp.h"

// Contains the various options the user can pass ptgz.
struct Settings {
	Settings(): extract(),
				compress(),
   				verbose(),
				output() {}
	bool extract;
	bool compress;
	bool verbose;
	bool output;
	std::string name;
};

// Checks if the user asks for help.
// Provides usage information to the user.
// Parameters: argc (int) number of cli arguments.
// 			   argv (char *[]) user provided arguments.
void helpCheck(int argc, char *argv[]) {
	if (argc == 1) {
		std::cout << "ERROR: ptgz was passed no parameters. \"ptgz -h\" for help." << std::endl;
		exit(0);
	}

	if (argv[1] == std::string("-h") || argv[1] == std::string("--help")) {
		std::cout << "\nptgz - Parallel Tar GZ by Ryan Chui (2017)\n" << std::endl;
		exit(0);
	}
}

// Gets the parameters passed by the user and stores them.
// Parameters: argc (int) number of cli arguments.
// 			   argv (char *[]) user provided arguments.
// 			   instance (Settings *) user argument storage.
void getSettings(int argc, char *argv[], Settings *instance) {
	// Get all passed arguments
	std::queue<std::string> settings;
	for (int i = 1; i < argc; ++i) {
		settings.push(argv[i]);
	}

	// Continue to check until there are no more passed arguments.
	while (!settings.empty()) {
		std::string arg = settings.front();

		if (arg == "-x") {
			if ((*instance).compress) {
				std::cout << "ERROR: ptgz cannot both compress and extract. \"ptgz -h\" for help." << std::endl;
				exit(0);
			}
			(*instance).extract = true;
		} else if (arg == "-c") {
			if ((*instance).extract) {
				std::cout << "ERROR: ptgz cannot both compress and extract. \"ptgz -h\" for help." << std::endl;
				exit(0);
			}
			(*instance).compress = true;
		} else if (arg == "-v"){
			(*instance).verbose = true;
		} else if (arg == "-o") {
			(*instance).output = true;
		} else {
			if (settings.size() > 1) {
				std::cout << "ERROR: ptgz was called incorrectly. \"ptgz -h\" for help." << std::endl;
				exit(0);
			}
			(*instance).output = true;
			(*instance).name = arg;
		}

		settings.pop();
	}

	if (!(*instance).output) {
		std::cout << "ERROR: No output file name given. \"ptgz -h\" for help." << std::endl;
		exit(0);
	}
}

// Finds the number of files in the space to store.
// Parameters: numFiles (int *) number of files.
// 			   cwd (const char *) current working directory.
void findAll(int *numFiles, const char *cwd) {
	DIR *dir;
	struct dirent *ent;

	// Check if cwd is a directory
	if ((dir = opendir(cwd)) != NULL) {
		// Get all file paths within directory.
		while ((ent = readdir (dir)) != NULL) {
			std::string fileBuff = std::string(ent -> d_name);
			if (fileBuff != "." && fileBuff != "..") {
				DIR *dir2;
				std::string filePath = std::string(cwd) + "/" + fileBuff;
				// Check if file path is a directory.
				if ((dir2 = opendir(filePath.c_str())) != NULL) {
					closedir(dir2);
					findAll(numFiles, filePath.c_str());
				} else {
					*numFiles += 1;
				}
			}
		}
		closedir(dir);
	}
}

// Gets the paths for all files in the space to store.
// Parameters: filePaths (std::vector<std::string> *) holder for all file paths.
// 			   cwd (const char *) current working directory.
// 			   rootPath (std::string) path from the root of the directory to be stored.
void getPaths(std::vector<std::string> *filePaths, const char *cwd, std::string rootPath) {
	DIR *dir;
	struct dirent *ent;

	// Check if cwd is a directory
	if ((dir = opendir(cwd)) != NULL) {
		// Get all file paths within directory.
		while ((ent = readdir (dir)) != NULL) {
			std::string fileBuff = std::string(ent -> d_name);
			if (fileBuff != "." && fileBuff != "..") {
				DIR *dir2;
				std::string filePath = std::string(cwd) + "/" + fileBuff;
				// Check if file path is a directory.
				if ((dir2 = opendir(filePath.c_str())) != NULL) {
					closedir(dir2);
					getPaths(filePaths, filePath.c_str(), rootPath + fileBuff + "/");
				} else {
					filePaths->push_back(rootPath + fileBuff);
				}
			}
		}
		closedir(dir);
	}
}

// Divides files into blocks.
// Compresses each block into a single file.
// Combines all compressed blocks into a single file.
// Removes temporary blocks and header files.
// Parameters: filePaths (std::vector<std::string> *) holder for all file paths.
// 			   name (std::string) user given name for storage file.
// 			   verbose (bool) user option for verbose output.
void compression(std::vector<std::string> *filePaths, std::string name, bool verbose) {
	std::random_shuffle(filePaths->begin(), filePaths->end());
	unsigned long long int filePathSize = filePaths->size();
	unsigned long long int blockSize = (filePathSize / (omp_get_max_threads() * 10)) + 1;
	std::vector<std::string> *tarNames = new std::vector<std::string>(filePathSize / blockSize + 1);

	// Gzips the blocks of files into a single compressed file
	#pragma omp parallel for schedule(dynamic)
	for (int i = 0; i < omp_get_max_threads() * 10; ++i) {
		unsigned long long int start = blockSize * i;
		if (start < filePathSize) {
			// Store the name of each file for a block owned by each thread.
			// Each thread will use the file to tar and gzip compress their block.
			std::ofstream tmp;
			tmp.open(std::to_string(i) + "." + name + ".ptgz.tmp", std::ios_base::app);
			std::string gzCommand = "GZIP=-1 tar -cz -T " + std::to_string(i) + "." + name + ".ptgz.tmp -f " + std::to_string(i) + "." + name + ".tar.gz";
			for (unsigned long long int j = start; j < std::min(start + blockSize, filePathSize); ++j) {
				tmp << filePaths->at(j) + "\n";
			}

			if (verbose) {
				std::cout << gzCommand + "\n";
			}

			tmp.close();
			system(gzCommand.c_str());
			tarNames->at(i) = std::to_string(i) + "." + name + ".tar.gz";
		}
	}

	// Combines gzipped blocks together into a single tarball.
	// Write tarball names into an idx file for extraction.
	std::ofstream idx, tmp;
	idx.open(name + ".ptgz.idx", std::ios_base::app);
	std::string tarCommand = "tar -c -T " + name + ".ptgz.idx -f " + name + ".ptgz.tar";
	for (unsigned long long int i = 0; i < tarNames->size(); ++i) {
		idx << tarNames->at(i) + "\n";
	}
	idx << name + ".ptgz.idx" + "\n";
	idx.close();

	if (verbose) {
		std::cout << tarCommand + "\n";
	}

	system(tarCommand.c_str());

	// Removes all temporary blocks and idx file.
	#pragma omp parallel for schedule(static)
	for (unsigned long long int i = 0; i < tarNames->size(); ++i) {
		std::string rmCommand = tarNames->at(i);
		if (verbose) {
			std::cout << "remove(" + rmCommand + ")\n";
		}
		if (remove(rmCommand.c_str())) {
			std::cout << "ERROR: " + rmCommand + " could not be removed.\n";
		}

		rmCommand = std::to_string(i) + "." + name + ".ptgz.tmp";
		if (verbose) {
			std::cout << "remove(" + rmCommand + ")\n";
		}
		if (remove(rmCommand.c_str())) {
			std::cout << "ERROR: " + rmCommand + " could not be removed.\n";
		}
	}

	std::string rmCommand;
	if (verbose) {
		std::cout << "remove(" + name + ".ptgz.idx)\n";
	}
	rmCommand = name + ".ptgz.idx";
	if (remove(rmCommand.c_str())) {
		std::cout << "ERROR: " + rmCommand + " could not be removed.\n";
	}

	tarNames->clear();
	delete(tarNames);
}

void extraction(std::vector<std::string> *filePaths, std::string name, bool verbose) {
	std::string exCommand = "tar xf " + name;
	system(exCommand.c_str());
}

char cwd [PATH_MAX];

// Checks to see if the user asks for help.
// Gathers the user provided settings for ptgz.
// Finds the number of files that need to be stored.
// Gathers the file paths of all files to be stored.
// Either compresses the files or extracts the ptgz.tar archive.
int main(int argc, char *argv[]) {
	Settings *instance = new Settings;
	int *numFiles = new int(0);
	std::vector<std::string> *filePaths = new std::vector<std::string>();

	helpCheck(argc, argv);
	getSettings(argc, argv, instance);
	getcwd(cwd, PATH_MAX);

	if ((*instance).compress) {
		findAll(numFiles, cwd);
		getPaths(filePaths, cwd, "");
		compression(filePaths, (*instance).name, (*instance).verbose);
	} else {
		extraction(filePaths, (*instance).name, (*instance).verbose);
	}

	delete(instance);
	delete(numFiles);
	filePaths->clear();
	delete(filePaths);
	return 0;
}
<|endoftext|>


<commit_before>#ifndef GUNUNU_PIMPL_HPP
#define GUNUNU_PIMPL_HPP

#include <memory>
#include <utility>

namespace gununu {

struct pimpl_noinit_t{};

template <class T>
class pimpl {
public:
    pimpl(): ptr_(new T()) {}
    ~pimpl() { incomplete_check(); }
    constexpr pimpl(pimpl_noinit_t) noexcept {}

    pimpl(pimpl&&) noexcept = default;
    pimpl(pimpl const& rhs) {
        *this = rhs;
    }

    explicit pimpl(T const& v) {
        ptr_.reset(new T(v));
    }
    explicit pimpl(T&& v) {
        ptr_.reset(new T(std::move(v)));
    }

    T* get() const noexcept {
        return ptr_.get();
    }

    T& operator *() const {
        return *ptr_.get();
    }
    T* operator ->() const noexcept {
        return ptr_.get();
    }

    explicit operator bool() const noexcept {
        return ptr_.operator bool();
    }

    void swap(pimpl& rhs) noexcept {
        ptr_.swap(rhs.ptr_);
    }

    pimpl& operator = (pimpl&&) noexcept = default;
    pimpl& operator = (pimpl const& rhs) {
        ptr_.reset(rhs ? new T(*rhs.get()) : nullptr);
        return *this;
    }
private:
    template <class T2, class... Args2>
    friend pimpl<T2> make_pimpl(Args2&&...);
    void incomplete_check() { (void)sizeof(T); }
private:
    std::unique_ptr<T> ptr_;
};

template <class T, class... Args>
pimpl<T> make_pimpl(Args&&... args)
{
    pimpl<T> v(pimpl_noinit_t{});
    v.ptr_.reset(new T(std::forward<Args>(args)...));
    return v;
}

template <class T>
void swap(pimpl<T>& lhs, pimpl<T>& rhs) noexcept {
    lhs.swap(rhs);
}

} //namespace

#endif
<commit_msg>Change implimentation<commit_after>#ifndef GUNUNU_PIMPL_HPP
#define GUNUNU_PIMPL_HPP

#include <memory>
#include <utility>

namespace gununu {

struct pimpl_noinit_t{};

namespace detail {
struct holder {
    holder(){};
    virtual ~holder(){};
    virtual holder* clone() = 0;
    virtual void destroy() = 0;
    virtual void* get() = 0;
};

template <class T>
struct holder_t : public holder {
    template <class... Args>
    holder_t(Args&&... args) : obj(std::forward<Args>(args)...) {}
    holder* clone() override {
        return new holder_t<T>(obj);
    }

    void destroy() override {
        (void)sizeof(T);
        std::default_delete<holder_t<T>>()(this);
    }

    void* get() override {
        return static_cast<void*>(&obj);
    }
private:
    T obj;
};
} //namespace detail

template <class T>
class pimpl {
public:
    pimpl(): ptr_(new detail::holder_t<T>()) {}
    ~pimpl() { if (ptr_) ptr_->destroy(); }
    constexpr pimpl(pimpl_noinit_t) noexcept {}

    pimpl(pimpl&& rhs) noexcept : ptr_(nullptr) {
        *this = std::move(rhs);
    }
    pimpl(pimpl const& rhs) : ptr_(nullptr){
        *this = rhs;
    }

    explicit pimpl(T const& v) {
        ptr_ = new detail::holder_t<T>(v);
    }
    explicit pimpl(T&& v) {
        ptr_ = new detail::holder_t<T>(std::move(v));
    }

    T* get() const noexcept {
        return static_cast<T*>(ptr_->get());
    }

    T& operator *() const {
        return *get();
    }
    T* operator ->() const noexcept {
        return get();
    }

    explicit operator bool() const noexcept {
        return !!ptr_;
    }

    void swap(pimpl& rhs) noexcept {
        std::swap(ptr_, rhs.ptr_);
    }

    pimpl& operator = (pimpl&& rhs) noexcept {
        swap(rhs);
        return *this;
    }
    pimpl& operator = (pimpl const& rhs) {
        auto* cloned = (rhs ? rhs.ptr_->clone() : nullptr);
        if (ptr_) ptr_->destroy();
        ptr_ = cloned;
        return *this;
    }
private:
    template <class T2, class... Args2>
    friend pimpl<T2> make_pimpl(Args2&&...);
private:
    detail::holder* ptr_;
};

template <class T, class... Args>
pimpl<T> make_pimpl(Args&&... args)
{
    pimpl<T> v(pimpl_noinit_t{});
    v.ptr_ = new detail::holder_t<T>(std::forward<Args>(args)...);
    return v;
}

template <class T>
void swap(pimpl<T>& lhs, pimpl<T>& rhs) noexcept {
    lhs.swap(rhs);
}

} //namespace

#endif
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: activitiesqueue.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-07 20:22:55 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// must be first
#include <canvas/debug.hxx>
#ifndef _CANVAS_VERBOSETRACE_HXX
#include <canvas/verbosetrace.hxx>
#endif
#include <comphelper/scopeguard.hxx>
#include <comphelper/anytostring.hxx>
#include <cppuhelper/exc_hlp.hxx>

#include <slideshowexceptions.hxx>
#include <activity.hxx>
#include <activitiesqueue.hxx>

#include <boost/bind.hpp>
#include <boost/mem_fn.hpp>
#include <algorithm>

using namespace ::com::sun::star;

namespace presentation
{
    namespace internal
    {
        ActivitiesQueue::ActivitiesQueue( const ::boost::shared_ptr< ::canvas::tools::ElapsedTime >&    pPresTimer,
                                          EventMultiplexer&                                             rEventMultiplexer ) :
            mpTimer( pPresTimer ),
            maCurrentActivitiesWaiting(),
            maCurrentActivitiesReinsert(),
            mrEventMultiplexer( rEventMultiplexer ),
            mbCurrentRoundNeedsScreenUpdate( false )
        {
        }

        ActivitiesQueue::~ActivitiesQueue()
        {
            // dispose all queue entries
            try {
                std::for_each( maCurrentActivitiesWaiting.begin(),
                               maCurrentActivitiesWaiting.end(),
                               boost::mem_fn( &Disposable::dispose ) );
                std::for_each( maCurrentActivitiesReinsert.begin(),
                               maCurrentActivitiesReinsert.end(),
                               boost::mem_fn( &Disposable::dispose ) );
            }
            catch (uno::Exception &) {
                OSL_ENSURE( false, rtl::OUStringToOString(
                                comphelper::anyToString(
                                    cppu::getCaughtException() ),
                                RTL_TEXTENCODING_UTF8 ).getStr() );
            }
        }

        bool ActivitiesQueue::addActivity( const ActivitySharedPtr& pActivity )
        {
            OSL_ENSURE( pActivity.get() != NULL, "ActivitiesQueue::addActivity: activity ptr NULL" );

            if( pActivity.get() == NULL )
                return false;

            // add entry to waiting list
            maCurrentActivitiesWaiting.push_back( pActivity );

            return true;
        }

        void ActivitiesQueue::process()
        {
            VERBOSE_TRACE( "ActivitiesQueue: outer loop heartbeat" );

            // accumulate time lag for all activities, and lag time
            // base if necessary:
            ActivityQueue::const_iterator iPos(
                maCurrentActivitiesWaiting.begin() );
            const ActivityQueue::const_iterator iEnd(
                maCurrentActivitiesWaiting.end() );
            double fLag = 0.0;
            for ( ; iPos != iEnd; ++iPos )
                fLag = std::max<double>( fLag, (*iPos)->calcTimeLag() );
            if (fLag > 0.0) {
                mpTimer->adjustTimer( -fLag );
            }

            // This list collects all activities which did not request
            // a reinsertion. After the screen update has been
            // performed, those are notified via dequeued(). This
            // facilitates cleanup actions taking place _after_ the
            // current frame has been displayed.
            ActivityQueue aDequeuedActivities;

            // process list of activities
            while( !maCurrentActivitiesWaiting.empty() )
            {
                // process topmost activity
                ActivitySharedPtr pActivity( maCurrentActivitiesWaiting.front() );
                maCurrentActivitiesWaiting.pop_front();

                bool bReinsert( false );

                try
                {
                    // fire up activity
                    bReinsert = pActivity->perform();
                }
                catch( uno::Exception& )
                {
                    // catch anything here, we don't want
                    // to leave this scope under _any_
                    // circumstance. Although, do _not_
                    // reinsert an activity that threw
                    // once.

                    // NOTE: we explicitely don't catch(...) here,
                    // since this will also capture segmentation
                    // violations and the like. In such a case, we
                    // still better let our clients now...
                    OSL_TRACE( "::presentation::internal::ActivitiesQueue: Activity threw a uno::Exception, removing from ring" );
                }
                catch( SlideShowException& )
                {
                    // catch anything here, we don't want
                    // to leave this scope under _any_
                    // circumstance. Although, do _not_
                    // reinsert an activity that threw
                    // once.

                    // NOTE: we explicitely don't catch(...) here,
                    // since this will also capture segmentation
                    // violations and the like. In such a case, we
                    // still better let our clients now...
                    OSL_TRACE( "::presentation::internal::ActivitiesQueue: Activity threw a SlideShowException, removing from ring" );
                }

                // always query need for screen updates. Note that
                // ending activities (i.e. those that return
                // bReinsert=false) might also need one last screen
                // update
                if( pActivity->needsScreenUpdate() )
                    mbCurrentRoundNeedsScreenUpdate = true;

                if( bReinsert )
                    maCurrentActivitiesReinsert.push_back( pActivity );
                else
                    aDequeuedActivities.push_back( pActivity );

                VERBOSE_TRACE( "ActivitiesQueue: inner loop heartbeat" );
            }

            // when true, the code below has determined that a screen
            // update is necessary.
            bool bPerformScreenUpdate( false );

            // waiting activities exhausted? Then update screen, and
            // reinsert
            if( maCurrentActivitiesWaiting.empty() )
            {
                if( mbCurrentRoundNeedsScreenUpdate )
                {
                    bPerformScreenUpdate = true;
                }

                // always clear update flag. There's no need to update
                // yesterday's display, even if the canvas sometimes
                // become valid
                mbCurrentRoundNeedsScreenUpdate = false;

                if( !maCurrentActivitiesReinsert.empty() )
                {
                    // reinsert all processed, but not finished
                    // activities back to waiting queue. With swap(),
                    // we kill two birds with one stone: we reuse the
                    // list nodes, and we clear the
                    // maCurrentActivitiesReinsert list
                    maCurrentActivitiesWaiting.swap( maCurrentActivitiesReinsert );
                }
            }

            // perform screen update (not only if one of the
            // activities requested that, but also if the layer
            // manager signals that it needs one. This frees us from
            // introducing dummy activities, just to trigger screen
            // updates. OTOH, this makes it necessary to always call
            // BOTH event queue and activities queue, such that no
            // pending update is unduly delayed)
            mrEventMultiplexer.updateScreenContent( bPerformScreenUpdate );

            // notify all dequeued activities, but only _after_ the
            // screen update.
            ::std::for_each( aDequeuedActivities.begin(),
                             aDequeuedActivities.end(),
                             ::boost::mem_fn( &Activity::dequeued ) );
        }

        bool ActivitiesQueue::isEmpty()
        {
            return maCurrentActivitiesWaiting.empty() && maCurrentActivitiesReinsert.empty();
        }

        void ActivitiesQueue::clear()
        {
            // dequeue all entries:
            std::for_each( maCurrentActivitiesWaiting.begin(),
                           maCurrentActivitiesWaiting.end(),
                           boost::mem_fn( &Activity::dequeued ) );
            ActivityQueue().swap( maCurrentActivitiesWaiting );

            std::for_each( maCurrentActivitiesReinsert.begin(),
                           maCurrentActivitiesReinsert.end(),
                           boost::mem_fn( &Activity::dequeued ) );
            ActivityQueue().swap( maCurrentActivitiesReinsert );

            mbCurrentRoundNeedsScreenUpdate = false;
        }
    }
}
<commit_msg>INTEGRATION: CWS thbpp2 (1.6.28); FILE MERGED 2006/01/27 13:56:29 thb 1.6.28.1: #i61190# Activities might add events - thus, can only reliably retrieve next timeout after processing activities queue.<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: activitiesqueue.cxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: rt $ $Date: 2006-02-09 14:47:39 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// must be first
#include <canvas/debug.hxx>
#ifndef _CANVAS_VERBOSETRACE_HXX
#include <canvas/verbosetrace.hxx>
#endif
#include <comphelper/scopeguard.hxx>
#include <comphelper/anytostring.hxx>
#include <cppuhelper/exc_hlp.hxx>

#include <slideshowexceptions.hxx>
#include <activity.hxx>
#include <activitiesqueue.hxx>

#include <boost/bind.hpp>
#include <boost/mem_fn.hpp>
#include <algorithm>

using namespace ::com::sun::star;

namespace presentation
{
    namespace internal
    {
        ActivitiesQueue::ActivitiesQueue( const ::boost::shared_ptr< ::canvas::tools::ElapsedTime >&    pPresTimer,
                                          EventMultiplexer&                                             rEventMultiplexer ) :
            mpTimer( pPresTimer ),
            maCurrentActivitiesWaiting(),
            maCurrentActivitiesReinsert(),
            mrEventMultiplexer( rEventMultiplexer ),
            mbCurrentRoundNeedsScreenUpdate( false )
        {
        }

        ActivitiesQueue::~ActivitiesQueue()
        {
            // dispose all queue entries
            try {
                std::for_each( maCurrentActivitiesWaiting.begin(),
                               maCurrentActivitiesWaiting.end(),
                               boost::mem_fn( &Disposable::dispose ) );
                std::for_each( maCurrentActivitiesReinsert.begin(),
                               maCurrentActivitiesReinsert.end(),
                               boost::mem_fn( &Disposable::dispose ) );
            }
            catch (uno::Exception &) {
                OSL_ENSURE( false, rtl::OUStringToOString(
                                comphelper::anyToString(
                                    cppu::getCaughtException() ),
                                RTL_TEXTENCODING_UTF8 ).getStr() );
            }
        }

        bool ActivitiesQueue::addActivity( const ActivitySharedPtr& pActivity )
        {
            OSL_ENSURE( pActivity.get() != NULL, "ActivitiesQueue::addActivity: activity ptr NULL" );

            if( pActivity.get() == NULL )
                return false;

            // add entry to waiting list
            maCurrentActivitiesWaiting.push_back( pActivity );

            return true;
        }

        void ActivitiesQueue::process()
        {
            VERBOSE_TRACE( "ActivitiesQueue: outer loop heartbeat" );

            // accumulate time lag for all activities, and lag time
            // base if necessary:
            ActivityQueue::const_iterator iPos(
                maCurrentActivitiesWaiting.begin() );
            const ActivityQueue::const_iterator iEnd(
                maCurrentActivitiesWaiting.end() );
            double fLag = 0.0;
            for ( ; iPos != iEnd; ++iPos )
                fLag = std::max<double>( fLag, (*iPos)->calcTimeLag() );
            if (fLag > 0.0) {
                mpTimer->adjustTimer( -fLag );
            }

            // This list collects all activities which did not request
            // a reinsertion. After the screen update has been
            // performed, those are notified via dequeued(). This
            // facilitates cleanup actions taking place _after_ the
            // current frame has been displayed.
            ActivityQueue aDequeuedActivities;

            // process list of activities
            while( !maCurrentActivitiesWaiting.empty() )
            {
                // process topmost activity
                ActivitySharedPtr pActivity( maCurrentActivitiesWaiting.front() );
                maCurrentActivitiesWaiting.pop_front();

                bool bReinsert( false );

                try
                {
                    // fire up activity
                    bReinsert = pActivity->perform();
                }
                catch( uno::Exception& )
                {
                    // catch anything here, we don't want
                    // to leave this scope under _any_
                    // circumstance. Although, do _not_
                    // reinsert an activity that threw
                    // once.

                    // NOTE: we explicitely don't catch(...) here,
                    // since this will also capture segmentation
                    // violations and the like. In such a case, we
                    // still better let our clients now...
                    OSL_TRACE( "::presentation::internal::ActivitiesQueue: Activity threw a uno::Exception, removing from ring" );
                }
                catch( SlideShowException& )
                {
                    // catch anything here, we don't want
                    // to leave this scope under _any_
                    // circumstance. Although, do _not_
                    // reinsert an activity that threw
                    // once.

                    // NOTE: we explicitely don't catch(...) here,
                    // since this will also capture segmentation
                    // violations and the like. In such a case, we
                    // still better let our clients now...
                    OSL_TRACE( "::presentation::internal::ActivitiesQueue: Activity threw a SlideShowException, removing from ring" );
                }

                // always query need for screen updates. Note that
                // ending activities (i.e. those that return
                // bReinsert=false) might also need one last screen
                // update
                if( pActivity->needsScreenUpdate() )
                    mbCurrentRoundNeedsScreenUpdate = true;

                if( bReinsert )
                    maCurrentActivitiesReinsert.push_back( pActivity );
                else
                    aDequeuedActivities.push_back( pActivity );

                VERBOSE_TRACE( "ActivitiesQueue: inner loop heartbeat" );
            }

            // when true, the code below has determined that a screen
            // update is necessary.
            bool bPerformScreenUpdate( false );

            // waiting activities exhausted? Then update screen, and
            // reinsert
            if( maCurrentActivitiesWaiting.empty() )
            {
                if( mbCurrentRoundNeedsScreenUpdate )
                {
                    bPerformScreenUpdate = true;
                }

                // always clear update flag. There's no need to update
                // yesterday's display, even if the canvas sometimes
                // become valid
                mbCurrentRoundNeedsScreenUpdate = false;

                if( !maCurrentActivitiesReinsert.empty() )
                {
                    // reinsert all processed, but not finished
                    // activities back to waiting queue. With swap(),
                    // we kill two birds with one stone: we reuse the
                    // list nodes, and we clear the
                    // maCurrentActivitiesReinsert list
                    maCurrentActivitiesWaiting.swap( maCurrentActivitiesReinsert );
                }
            }

            // perform screen update (not only if one of the
            // activities requested that, but also if the layer
            // manager signals that it needs one. This frees us from
            // introducing dummy activities, just to trigger screen
            // updates. OTOH, this makes it necessary to always call
            // BOTH event queue and activities queue, such that no
            // pending update is unduly delayed)
            mrEventMultiplexer.updateScreenContent( bPerformScreenUpdate );

            // notify all dequeued activities, but only _after_ the
            // screen update.
            ::std::for_each( aDequeuedActivities.begin(),
                             aDequeuedActivities.end(),
                             ::boost::mem_fn( &Activity::dequeued ) );
        }

        bool ActivitiesQueue::isEmpty() const
        {
            return maCurrentActivitiesWaiting.empty() && maCurrentActivitiesReinsert.empty();
        }

        void ActivitiesQueue::clear()
        {
            // dequeue all entries:
            std::for_each( maCurrentActivitiesWaiting.begin(),
                           maCurrentActivitiesWaiting.end(),
                           boost::mem_fn( &Activity::dequeued ) );
            ActivityQueue().swap( maCurrentActivitiesWaiting );

            std::for_each( maCurrentActivitiesReinsert.begin(),
                           maCurrentActivitiesReinsert.end(),
                           boost::mem_fn( &Activity::dequeued ) );
            ActivityQueue().swap( maCurrentActivitiesReinsert );

            mbCurrentRoundNeedsScreenUpdate = false;
        }
    }
}
<|endoftext|>