Пример #1
0
		String Path::GetDirectoryName(const String & path)
		{
			int pos = path.LastIndexOf('/');
			pos = Math::Max(path.LastIndexOf('\\'), pos);
			if (pos != -1)
				return path.SubString(0, pos);
			else
				return "";
		}
Пример #2
0
		String Path::GetFileNameWithoutEXT(const String & path)
		{
			int pos = path.LastIndexOf('/');
			pos = Math::Max(path.LastIndexOf('\\'), pos) + 1;
			int dotPos = path.LastIndexOf('.');
			if (dotPos <= pos)
				dotPos = path.Length();
			return path.SubString(pos, dotPos - pos);
		}
Пример #3
0
ECode SQLiteCursor::GetColumnIndex(
    /* [in] */ const String& columnName,
    /* [out] */ Int32* columnIndex)
{
    VALIDATE_NOT_NULL(columnIndex);
    // Create mColumnNameMap on demand
    if (mColumnNameMap == NULL) {
        AutoPtr< ArrayOf<String> > columns = mColumns;
        Int32 columnCount = columns->GetLength();
        AutoPtr< HashMap<String, Int32> > map = new HashMap<String, Int32>(columnCount);
        for (Int32 i = 0; i < columnCount; i++) {
            (*map)[(*columns)[i]] = i;
        }
        mColumnNameMap = map;
    }

    // Hack according to bug 903852
    Int32 periodIndex = columnName.LastIndexOf('.');
    String _columnName = columnName;
    if (periodIndex != -1) {
        // Exception e = new Exception();
        Slogger::E(TAG, "requesting column name with table name -- %s", columnName.string());
        _columnName = columnName.Substring(periodIndex + 1);
    }

    HashMap<String, Int32>::Iterator it = mColumnNameMap->Find(_columnName);
    if (it != mColumnNameMap->End()) {
        *columnIndex = it->mSecond;
    }
    else {
        *columnIndex = -1;
    }
    return NOERROR;
}
Пример #4
0
String ContentProvider::GetAuthorityWithoutUserId(
    /* [in] */ const String& auth)
{
    if (auth.IsNull()) return String(NULL);
    Int32 end = auth.LastIndexOf('@');
    return auth.Substring(end + 1);
}
Пример #5
0
String UrlUtils::CanonicalizePath(
    /* [in] */ const String& _path,
    /* [in] */ Boolean discardRelativePrefix)
{
    String path = _path;
    // the first character of the current path segment
    Int32 segmentStart = 0;

    // the number of segments seen thus far that can be erased by sequences of '..'.
    Int32 deletableSegments = 0;

    for (Int32 i = 0; i <= path.GetLength(); ) {
        Int32 nextSegmentStart;
        if (i == path.GetLength()) {
            nextSegmentStart = i;
        } else if (path.GetChar(i) == '/') {
            nextSegmentStart = i + 1;
        } else {
            i++;
            continue;
        }

        /*
         * We've encountered either the end of a segment or the end of the
         * complete path. If the final segment was "." or "..", remove the
         * appropriate segments of the path.
         */
        if (i == segmentStart + 1 && path.RegionMatches(segmentStart, String("."), 0, 1)) {
            // Given "abc/def/./ghi", remove "./" to get "abc/def/ghi".
            String part = path.Substring(0, segmentStart);
            part += path.Substring(nextSegmentStart);
            path = part;
            i = segmentStart;
        }
        else if (i == segmentStart + 2 && path.RegionMatches(segmentStart, String(".."), 0, 2)) {
            if (deletableSegments > 0 || discardRelativePrefix) {
                // Given "abc/def/../ghi", remove "def/../" to get "abc/ghi".
                deletableSegments--;
                Int32 prevSegmentStart = path.LastIndexOf('/', segmentStart - 2) + 1;
                String part = path.Substring(0, prevSegmentStart);
                part += path.Substring(nextSegmentStart);
                path = part;
                i = segmentStart = prevSegmentStart;
            }
            else {
                // There's no segment to delete; this ".." segment must be retained.
                i++;
                segmentStart = i;
            }
        }
        else {
            if (i > 0) {
                deletableSegments++;
            }
            i++;
            segmentStart = i;
        }
    }
    return path;
}
Пример #6
0
void Win32AllocateStdioConsole(const char * optArg)
{
   const String optOutFile = optArg;

   const char * conInStr  = optOutFile.HasChars() ? NULL         : "conin$";
   const char * conOutStr = optOutFile.HasChars() ? optOutFile() : "conout$";
   if (optOutFile.IsEmpty()) AllocConsole();  // no sense creating a DOS window if we're only outputting to a file anyway

   // Hopefully-temporary work-around for Windows not wanting to send stdout and stderr to the same file
   String conErrHolder;  // don't move this!  It needs to stay here
   const char * conErrStr = NULL;
   if (optOutFile.HasChars())
   {
      const int lastDotIdx = optOutFile.LastIndexOf('.');

      if (lastDotIdx > 0)
         conErrHolder = optOutFile.Substring(0, lastDotIdx) + "_stderr" + optOutFile.Substring(lastDotIdx);
      else
         conErrHolder = optOutFile + "_stderr.txt";

      conErrStr = conErrHolder();
   }
   else conErrStr = conOutStr;  // for the output-to-console-window case, where redirecting both stdout and stderr DOES work

# if __STDC_WANT_SECURE_LIB__
   FILE * junk;
   if (conInStr)  (void) freopen_s(&junk, conInStr,  "r", stdin);
   if (conOutStr) (void) freopen_s(&junk, conOutStr, "w", stdout);
   if (conErrStr) (void) freopen_s(&junk, conErrStr, "w", stderr);
# else
   if (conInStr)  (void) freopen(conInStr,  "r", stdin);
   if (conOutStr) (void) freopen(conOutStr, "w", stdout);
   if (conErrStr) (void) freopen(conErrStr, "w", stderr);
# endif
}
Пример #7
0
	Ptr<Mesh> Mesh::AssimpLoader::Load(const String& path)
	{
		auto exceptionManager = ExceptionManager::GetInstance();
		this->path = &path;
		this->dir = path.SubString(0, path.LastIndexOf(TEXT('/')));

		Assimp::Importer importer;
		const aiScene* aiscene = importer.ReadFile(path.ToStdString(),
			aiProcess_MakeLeftHanded | aiProcess_Triangulate | aiProcess_CalcTangentSpace
			| aiProcess_GenNormals | aiProcess_ValidateDataStructure | aiProcess_ImproveCacheLocality
			| aiProcess_RemoveRedundantMaterials | aiProcess_FindDegenerates | aiProcess_SortByPType
			| aiProcess_FindInvalidData | aiProcess_GenUVCoords | aiProcess_TransformUVCoords
			| aiProcess_OptimizeMeshes | aiProcess_FixInfacingNormals
			| aiProcess_JoinIdenticalVertices | aiProcess_PreTransformVertices);
		if (aiscene == nullptr)
		{
			exceptionManager->PushException(Ptr<Exception>::New(aiGetErrorString()));
			return nullptr;
		}

		Ptr<Mesh> mesh = this->LoadAssimpNode(aiscene->mRootNode, aiscene);
		if (mesh == nullptr)
			return nullptr;
		mesh->filePath = path;
		return mesh;
	}
Пример #8
0
AutoPtr<IClassInfo> Utils::GetClassInfo(
    /* [in] */ const String& className,
    /* [in] */ Int32 flag)
{
    if (flag == ELASTOS_DROID_CORE_ECO_FALG) {
        AutoPtr<IModuleInfo> m;
        ASSERT_SUCCEEDED(CReflector::AcquireModuleInfo(String("Elastos.Droid.Core.eco"), (IModuleInfo**)&m));
        AutoPtr<IClassInfo> classInfo;
        m->GetClassInfo(className, (IClassInfo**)&classInfo);
        assert(classInfo != NULL);
        return classInfo;
    }

    if (sModuleInfo == NULL) {
        ASSERT_SUCCEEDED(CReflector::AcquireModuleInfo(sModulePath, (IModuleInfo**)&sModuleInfo));
        assert(sModuleInfo != NULL);
    }

    String name = String("C") + className.Substring(className.LastIndexOf('.'));
    Logger::D(TAG, "the class name is [%s]", name.string());
    AutoPtr<IClassInfo> classInfo;
    sModuleInfo->GetClassInfo(className, (IClassInfo**)&classInfo);
    assert(classInfo != NULL);
    return classInfo;
}
Пример #9
0
int __stdcall main()
{
	/*
	 * a simple example shows how to download internet resources 
	 * while keeping the directory structure.
	 */
	String root    = _R("GitHub/"); // root dir to save files
	String files[] = {
		_R("https://github-windows.s3.amazonaws.com/Application%20Files/GitHub_3_1_1_4/zh-Hans/Microsoft.Expression.Interactions.resources.dll.deploy"),  
		_R("https://github-windows.s3.amazonaws.com/Application%20Files/GitHub_3_1_1_4/zh-Hant/Microsoft.Expression.Interactions.resources.dll.deploy") 
	}; // files to be download
	Directory::Exist(root) || Directory::Create(root);

	for (auto &fn : files)
	{
		String path = Uri(fn).PathAndQuery;
		ManagedObject<StringArray> dirs = path.Substring(1, path.LastIndexOf(_T("/")) - 1).Split(RLIB_STR_LEN(_T("/")), 16);
		String dir = root;
		foreachp(lpdir, dirs)
		{
			dir += HttpUtility::UrlDecode(*lpdir);
			Directory::Exist(dir) || Directory::Create(dir);
		}

		String filename = path.Substring(path.LastIndexOfR(_T("/"))); // assumes that there is not query part in URL 
		bool result = WebClient::DownloadFile(fn, dir + filename);

		printf("%s %s\n", RT2A(filename).toGBK(), result ? "succeed" : "failed");
	}
Пример #10
0
		String Path::GetFileExt(const String & path)
		{
			int dotPos = path.LastIndexOf('.');
			if (dotPos != -1)
				return path.SubString(dotPos+1, path.Length()-dotPos-1);
			else
				return "";
		}
Пример #11
0
		String Path::TruncateExt(const String & path)
		{
			int dotPos = path.LastIndexOf('.');
			if (dotPos != -1)
				return path.SubString(0, dotPos);
			else
				return path;
		}
Пример #12
0
ECode EcoFile::OpenEcoFile(
    /* [in] */ const String& sourceName,
    /* [out] */ IModuleInfo** ecoModule)
{
    String fileName = sourceName;
    Int32 start = fileName.LastIndexOf("/");
    Int32 end = fileName.LastIndexOf("-");
    fileName = fileName.Substring(start >= 0 ? start + 1 : 0, end >= 0 ? end : fileName.GetLength() - 4)  + String(".eco");
    String path = String("/data/elastos/") + fileName;
    AutoPtr<IModuleInfo> moduleInfo;
    if (FAILED(CReflector::AcquireModuleInfo(path.string(), (IModuleInfo**)&moduleInfo))) {
        *ecoModule = NULL;
        Slogger::E(TAG, "OpenEcoFile: Cann't Find the Instrumentation path is %s", path.string());
        return E_RUNTIME_EXCEPTION;
    }
    *ecoModule = moduleInfo;
    REFCOUNT_ADD(*ecoModule);
    return NOERROR;
}
Пример #13
0
		String Path::ReplaceExt(const String & path, const char * newExt)
		{
			StringBuilder sb(path.Length()+10);
			int dotPos = path.LastIndexOf('.');
			if (dotPos == -1)
				dotPos = path.Length();
			sb.Append(path.Buffer(), dotPos);
			sb.Append('.');
			sb.Append(newExt);
			return sb.ProduceString();
		}
Пример #14
0
Int32 ContentProvider::GetUserIdFromAuthority(
    /* [in] */ const String& auth,
    /* [in] */ Int32 defaultUserId)
{
    if (auth.IsNull()) return defaultUserId;
    Int32 end = auth.LastIndexOf('@');
    if (end == -1) return defaultUserId;
    String userIdString = auth.Substring(0, end);
    Int32 uid;
    ECode ec = StringUtils::Parse(userIdString, &uid);
    if (FAILED(ec)) {
        Logger::W(TAG, "Error parsing userId: %s", userIdString.string());
        return UserHandle::USER_NULL;
    }
    return uid;
}
Пример #15
0
	//*************************************************************************
	// Method:		get_ExecutablePath
	// Description: ExecutablePath property get method
	//
	// Parameters:
	//	None
	//
	// Return Value: the string representing the path to the executable for this log
	//	data array
	//*************************************************************************
	String *LogPaneDataArray::get_ExecutablePath() 
	{
		try
		{
			String *fullPath = process->MainModule->FileName;
			int pos = fullPath->LastIndexOf("\\");
			if (pos == -1)
				fullPath = "";
			else
				fullPath = fullPath->Substring(0, pos);

			return fullPath;
		}
		catch(Exception *)
		{
			return "";
		}
	}
Пример #16
0
		String Path::GetFileName(const String & path)
		{
			int pos = path.LastIndexOf('/');
			pos = Math::Max(path.LastIndexOf('\\'), pos) + 1;
			return path.SubString(pos, path.Length()-pos);
		}
Пример #17
0
ECode CObjInfoList::AcquireDynamicEnumInfo(
    /* [in] */ const String& fullName,
    /* [in] */ ArrayOf<String>* itemNames,
    /* [in] */ ArrayOf<Int32>* itemValues,
    /* [out] */ IEnumInfo** enumInfo)
{
    if (fullName.IsNull() || itemNames == NULL
        || itemValues == NULL || !enumInfo
        || itemNames->GetLength() != itemValues->GetLength()) {
        return E_INVALID_ARGUMENT;
    }

    InfoLinkNode* node = mEnumInfoHead;
    String enumName;
    String enumNamespace;
    AutoPtr<CEnumInfo> enumInfoObj;
    Int32 count = 0, i = 0;

    LockHashTable(EntryType_Enum);
    for (; node; node = node->mNext) {
        enumInfoObj = (CEnumInfo *)node->mInfo;
        enumInfoObj->GetName(&enumName);
        enumInfoObj->GetNamespace(&enumNamespace);

        Int32 index = fullName.LastIndexOf(".");
        String name = index > 0 ? fullName.Substring(index + 1) : fullName;
        String nameSpace = index > 0 ? fullName.Substring(0, index - 1) : String("");
        if (name.Equals(enumName) && nameSpace.Equals(enumNamespace)) {
            enumInfoObj->GetItemCount(&count);
            if (count != itemNames->GetLength()) {
                if (!name.IsEmpty()) {
                    UnlockHashTable(EntryType_Enum);
                    return E_DATAINFO_EXIST;
                }
                else {
                    continue;
                }
            }

            AutoPtr< ArrayOf<String> > _itemNames = enumInfoObj->mItemNames;
            AutoPtr< ArrayOf<Int32> > _itemValues = enumInfoObj->mItemValues;
            for (i = 0; i < count; i++) {
                if (!(*itemNames)[i].Equals((*_itemNames)[i])) {
                    if (!name.IsEmpty()) {
                        UnlockHashTable(EntryType_Enum);
                        return E_DATAINFO_EXIST;
                    }
                    else {
                        continue;
                    }
                }
                if ((*itemValues)[i] != (*_itemValues)[i]) {
                    if (!name.IsEmpty()) {
                        UnlockHashTable(EntryType_Enum);
                        return E_DATAINFO_EXIST;
                    }
                    else {
                        continue;
                    }
                }
            }

            *enumInfo = enumInfoObj;
            (*enumInfo)->AddRef();
            return NOERROR;
        }
    }

    enumInfoObj = new CEnumInfo();
    if (enumInfoObj == NULL) {
        UnlockHashTable(EntryType_Enum);
        return E_OUT_OF_MEMORY;
    }

    ECode ec = enumInfoObj->InitDynamic(fullName, itemNames, itemValues);
    if (FAILED(ec)) {
        UnlockHashTable(EntryType_Enum);
        return ec;
    }

    ec = AddInfoNode(enumInfoObj, &mEnumInfoHead);
    if (FAILED(ec)) {
        UnlockHashTable(EntryType_Enum);
        return ec;
    }

    *enumInfo = enumInfoObj;
    (*enumInfo)->AddRef();

    UnlockHashTable(EntryType_Enum);

    return NOERROR;
}
Пример #18
0
ECode CMediaHTTPConnection::SeekTo(
    /* [in] */ Int64 offset)
{
    TeardownConnection();

    // try {
    Int32 response;
    Int32 redirectCount = 0;

    AutoPtr<IURL> url = mURL;

    // do not use any proxy for localhost (127.0.0.1)
    Boolean noProxy = IsLocalHost(url);

    while (TRUE) {
        if (noProxy) {
            AutoPtr<Elastos::Net::IProxyHelper> proxyhelper;
            Elastos::Net::CProxyHelper::AcquireSingleton((Elastos::Net::IProxyHelper**)&proxyhelper);
            AutoPtr<Elastos::Net::IProxy> proxyTemp;
            proxyhelper->GetNO_PROXY((Elastos::Net::IProxy**)&proxyTemp);

            url->OpenConnection(proxyTemp, (IURLConnection**)&mConnection);
        }
        else {
            url->OpenConnection((IURLConnection**)&mConnection);
        }

        // handle redirects ourselves if we do not allow cross-domain redirect
        mConnection->SetInstanceFollowRedirects(mAllowCrossDomainRedirect);

        if (mHeaders != NULL) {
            AutoPtr<ISet> entrySet;
            mHeaders->GetEntrySet((ISet**)&entrySet);
            AutoPtr<ArrayOf<IInterface*> > array;
            entrySet->ToArray((ArrayOf<IInterface*>**)&array);

            for (Int32 i = 0; i < array->GetLength(); ++i) {
                AutoPtr<IMapEntry> entry;
                entry = IMapEntry::Probe((*array)[i]);
                AutoPtr<IInterface> iKey;
                entry->GetKey((IInterface**)&iKey);
                String key;
                ICharSequence::Probe(iKey)->ToString(&key);
                AutoPtr<IInterface> iValue;
                entry->GetValue((IInterface**)&iValue);
                String value;
                ICharSequence::Probe(iValue)->ToString(&value);

                IURLConnection::Probe(mConnection)->SetRequestProperty(
                        key, value);
            }
        }

        if (offset > 0) {
            IURLConnection::Probe(mConnection)->SetRequestProperty(
                    String("Range"), String("bytes=") + offset + "-");
        }

        mConnection->GetResponseCode(&response);
        if (response != IHttpURLConnection::HTTP_MULT_CHOICE &&
                response != IHttpURLConnection::HTTP_MOVED_PERM &&
                response != IHttpURLConnection::HTTP_MOVED_TEMP &&
                response != IHttpURLConnection::HTTP_SEE_OTHER &&
                response != HTTP_TEMP_REDIRECT) {
            // not a redirect, or redirect handled by HttpURLConnection
            break;
        }

        if (++redirectCount > MAX_REDIRECTS) {
            // throw new NoRouteToHostException("Too many redirects: " + redirectCount);
            return E_NO_ROUTE_TO_HOST_EXCEPTION;
        }

        String method;
        mConnection->GetRequestMethod(&method);
        if (response == HTTP_TEMP_REDIRECT &&
                !method.Equals("GET") && !method.Equals("HEAD")) {
            // "If the 307 status code is received in response to a
            // request other than GET or HEAD, the user agent MUST NOT
            // automatically redirect the request"
            // throw new NoRouteToHostException("Invalid redirect");
        }
        String location;
        IURLConnection::Probe(mConnection)->GetHeaderField(String("Location"), &location);
        if (location == NULL) {
            // throw new NoRouteToHostException("Invalid redirect");
            return E_NO_ROUTE_TO_HOST_EXCEPTION;
        }
        CURL::New(mURL /* TRICKY: don't use url! */, location, (IURL**)&url);
        String protocol;
        url->GetProtocol(&protocol);
        if (!protocol.Equals("https") &&
                !protocol.Equals("http")) {
            // throw new NoRouteToHostException("Unsupported protocol redirect");
            return E_NO_ROUTE_TO_HOST_EXCEPTION;
        }
        String p;
        mURL->GetProtocol(&p);
        Boolean sameProtocol = p.Equals(protocol);
        if (!mAllowCrossProtocolRedirect && !sameProtocol) {
            // throw new NoRouteToHostException("Cross-protocol redirects are disallowed");
            return E_NO_ROUTE_TO_HOST_EXCEPTION;
        }
        String host1, host2;
        mURL->GetHost(&host1);
        url->GetHost(&host2);
        Boolean sameHost = host1.Equals(host2);
        if (!mAllowCrossDomainRedirect && !sameHost) {
            // throw new NoRouteToHostException("Cross-domain redirects are disallowed");
            return E_NO_ROUTE_TO_HOST_EXCEPTION;
        }

        if (response != HTTP_TEMP_REDIRECT) {
            // update effective URL, unless it is a Temporary Redirect
            mURL = url;
        }
    }

    if (mAllowCrossDomainRedirect) {
        // remember the current, potentially redirected URL if redirects
        // were handled by HttpURLConnection
        IURLConnection::Probe(mConnection)->GetURL((IURL**)&mURL);
    }

    if (response == IHttpURLConnection::HTTP_PARTIAL) {
        // Partial content, we cannot just use getContentLength
        // because what we want is not just the length of the range
        // returned but the size of the full content if available.

        String contentRange;
        IURLConnection::Probe(mConnection)->GetHeaderField(String("Content-Range"), &contentRange);

        mTotalSize = -1;
        if (contentRange != NULL) {
            // format is "bytes xxx-yyy/zzz
            // where "zzz" is the total number of bytes of the
            // content or '*' if unknown.

            Int32 lastSlashPos = contentRange.LastIndexOf('/');
            if (lastSlashPos >= 0) {
                String total =
                    contentRange.Substring(lastSlashPos + 1);

                // try {
                mTotalSize = StringUtils::ParseInt64(total);
                // } catch (NumberFormatException e) {
                // }
            }
        }
    }
    else if (response != IHttpURLConnection::HTTP_OK) {
        // throw new IOException();
        return E_IO_EXCEPTION;
    }
    else {
        Int32 length;
        IURLConnection::Probe(mConnection)->GetContentLength(&length);
        mTotalSize = length;
    }

    if (offset > 0 && response != IHttpURLConnection::HTTP_PARTIAL) {
        // Some servers simply ignore "Range" requests and serve
        // data from the start of the content.
        // throw new IOException();
        return E_IO_EXCEPTION;
    }

    AutoPtr<IInputStream> is;
    IURLConnection::Probe(mConnection)->GetInputStream((IInputStream**)&is);
    AutoPtr<IBufferedInputStream> bis;
    CBufferedInputStream::New(is, (IBufferedInputStream**)&bis);
    mInputStream = IInputStream::Probe(bis);

    mCurrentOffset = offset;
    // } catch (IOException e) {
    //     mTotalSize = -1;
    //     mInputStream = null;
    //     mConnection = null;
    //     mCurrentOffset = -1;

    //     throw e;
    // }
    return NOERROR;
}
Пример #19
0
String URLUtil::GuessFileName(
    /* [in] */ const String& url,
    /* [in] */ const String& contentDisposition,
    /* [in] */ const String& _mimeType)
{
    String filename;
    String extension;
    String mimeType = _mimeType;

    // If we couldn't do anything with the hint, move toward the content disposition
    if (filename.IsNull() && !contentDisposition.IsNull()) {
        filename = ParseContentDisposition(contentDisposition);
        if (!filename.IsNull()) {
            Int32 index = filename.LastIndexOf('/') + 1;
            if (index > 0) {
                filename = filename.Substring(index);
            }
        }
    }

    // If all the other http-related approaches failed, use the plain uri
    if (filename.IsNull()) {
        String decodedUrl;
        Uri::Decode(url, &decodedUrl);
        if (!decodedUrl.IsNull()) {
            Int32 queryIndex = decodedUrl.IndexOf('?');
            // If there is a query string strip it, same as desktop browsers
            if (queryIndex > 0) {
                decodedUrl = decodedUrl.Substring(0, queryIndex);
            }
            if (!decodedUrl.EndWith("/")) {
                Int32 index = decodedUrl.LastIndexOf('/') + 1;
                if (index > 0) {
                    filename = decodedUrl.Substring(index);
                }
            }
        }
    }

    // Finally, if couldn't get filename from URI, get a generic filename
    if (filename.IsNull()) {
        filename = "downloadfile";
    }

    // Split filename between base and extension
    // Add an extension if filename does not have one
    Int32 dotIndex = filename.IndexOf('.');
    if (dotIndex < 0) {
        if (!mimeType.IsNull()) {
            AutoPtr<MimeTypeMap> mimeTypeMap = MimeTypeMap::GetSingleton();
            mimeTypeMap->GetExtensionFromMimeType(mimeType, &extension);
            if (!extension.IsNull()) {
                extension = String(".") + extension;
            }
        }
        if (extension.IsNull()) {
            if (!mimeType.IsNull() && mimeType.StartWithIgnoreCase("text/")) {
                if (mimeType.EqualsIgnoreCase("text/html")) {
                    extension = ".html";
                }
                else {
                    extension = ".txt";
                }
            }
            else {
                extension = ".bin";
            }
        }
    }
    else {
        if (!mimeType.IsNull()) {
            // Compare the last segment of the extension against the mime type.
            // If there's a mismatch, discard the entire extension.
            Int32 lastDotIndex = filename.LastIndexOf('.');
            AutoPtr<MimeTypeMap> mimeTypeMap = MimeTypeMap::GetSingleton();
            String typeFromExt;
            mimeTypeMap->GetMimeTypeFromExtension(
                    filename.Substring(lastDotIndex + 1), &typeFromExt);
            if (!typeFromExt.IsNull() && !typeFromExt.EqualsIgnoreCase(mimeType)) {
                mimeTypeMap->GetExtensionFromMimeType(mimeType, &extension);
                if (!extension.IsNull()) {
                    extension = String(".") + extension;
                }
            }
        }
        if (extension.IsNull()) {
            extension = filename.Substring(dotIndex);
        }
        filename = filename.Substring(0, dotIndex);
    }

    return filename + extension;
}
Пример #20
0
ECode IconPackHelper::GetIconResMapFromXml(
    /* [in] */ IResources* res,
    /* [in] */ const String& packageName,
    /* [out] */ IMap** iconResMap)
{
    VALIDATE_NOT_NULL(iconResMap);
    *iconResMap = NULL;

    AutoPtr<IXmlPullParser> parser;
    AutoPtr<IInputStream> inputStream;
    AutoPtr<IMap> iconPackResources;
    CHashMap::New((IMap**)&iconPackResources);

    // try {
    AutoPtr<IAssetManager> am;
    res->GetAssets((IAssetManager**)&am);
    ECode ec = am->Open(String("appfilter.xml"), (IInputStream**)&inputStream);
    if (SUCCEEDED(ec)) {
        AutoPtr<IXmlPullParserFactoryHelper> helper;
        CXmlPullParserFactoryHelper::AcquireSingleton((IXmlPullParserFactoryHelper**)&helper);
        AutoPtr<IXmlPullParserFactory> factory;
        helper->NewInstance((IXmlPullParserFactory**)&factory);
        factory->NewPullParser((IXmlPullParser**)&parser);
        ec = parser->SetInput(inputStream, String("UTF-8"));
    }
    if (FAILED(ec)) {
        // Catch any exception since we want to fall back to parsing the xml/
        // resource in all cases
        Int32 resId;
        res->GetIdentifier(String("appfilter"), String("xml"), packageName, &resId);
        if (resId != 0) {
            AutoPtr<IXmlResourceParser> resParser;
            res->GetXml(resId, (IXmlResourceParser**)&resParser);
            parser = IXmlPullParser::Probe(resParser);
        }
    }
    // } catch (Exception e) {
    //     // Catch any exception since we want to fall back to parsing the xml/
    //     // resource in all cases
    //     int resId = res.getIdentifier("appfilter", "xml", packageName);
    //     if (resId != 0) {
    //         parser = res.getXml(resId);
    //     }
    // }

    if (parser != NULL) {
        // try {
        ECode ec = LoadResourcesFromXmlParser(parser, iconPackResources);
        if (IXmlResourceParser::Probe(parser) != NULL) {
            IXmlResourceParser::Probe(parser)->Close();
        }
        else if (inputStream != NULL) {
            // try {
            inputStream->Close();
            // } catch (IOException e) {
            // }
        }
        if (SUCCEEDED(ec)) {
            *iconResMap = iconPackResources;
            REFCOUNT_ADD(*iconResMap);
            return NOERROR;
        }
        // } catch (XmlPullParserException e) {
        //     e.printStackTrace();
        // } catch (IOException e) {
        //     e.printStackTrace();
        // } finally {
        //     // Cleanup resources
        //     if (parser instanceof XmlResourceParser) {
        //         ((XmlResourceParser) parser).close();
        //     } else if (inputStream != null) {
        //         try {
        //             inputStream.close();
        //         } catch (IOException e) {
        //         }
        //     }
        // }
    }

    // Application uses a different theme format (most likely launcher pro)
    Int32 arrayId;
    res->GetIdentifier(String("theme_iconpack"), String("array"), packageName, &arrayId);
    if (arrayId == 0) {
        res->GetIdentifier(String("icon_pack"), String("array"), packageName, &arrayId);
    }

    if (arrayId != 0) {
        AutoPtr< ArrayOf<String> > iconPack;
        res->GetStringArray(arrayId, (ArrayOf<String>**)&iconPack);
        for (Int32 i = 0; i < iconPack->GetLength(); i++) {
            String entry = (*iconPack)[i];

            if (TextUtils::IsEmpty(entry)) {
                continue;
            }

            String icon = entry;
            StringUtils::ReplaceAll(String(entry), String("_"), String("."), &entry);

            AutoPtr<IComponentName> compName;
            CComponentName::New(entry.ToLowerCase(), String(""), (IComponentName**)&compName);
            iconPackResources->Put(compName, CoreUtils::Convert(icon));

            Int32 activityIndex = entry.LastIndexOf(".");
            if (activityIndex <= 0 || activityIndex == entry.GetLength() - 1) {
                continue;
            }

            String iconPackage = entry.Substring(0, activityIndex);
            if (TextUtils::IsEmpty(iconPackage)) {
                continue;
            }

            String iconActivity = entry.Substring(activityIndex + 1);
            if (TextUtils::IsEmpty(iconActivity)) {
                continue;
            }

            // Store entries as lower case to ensure match
            iconPackage = iconPackage.ToLowerCase();
            iconActivity = iconActivity.ToLowerCase();

            iconActivity = iconPackage + "." + iconActivity;
            compName = NULL;
            CComponentName::New(iconPackage, iconActivity, (IComponentName**)&compName);
            iconPackResources->Put(compName, CoreUtils::Convert(icon));
        }
    }
    *iconResMap = iconPackResources;
    REFCOUNT_ADD(*iconResMap);
    return NOERROR;
}
Пример #21
0
String Path::GetDirectoryName(const String & path)
{
    int pos = path.LastIndexOf(L'/');
    pos = Math::Max(path.LastIndexOf(L'\\'), pos);
    return path.SubString(0, pos);
}
Пример #22
0
ECode CURI::ParseAuthority(
    /* [in] */ Boolean forceServer)
{
    if (mAuthority.IsNull()) {
        return NOERROR;
    }

    String tempUserInfo;
    String temp = mAuthority;
    Int32 index = temp.IndexOf('@');
    Int32 hostIndex = 0;
    if (index != -1) {
        // remove user info
        tempUserInfo = temp.Substring(0, index);
        FAIL_RETURN(ValidateUserInfo(mAuthority, tempUserInfo, 0));
        temp = temp.Substring(index + 1); // host[:port] is left
        hostIndex = index + 1;
    }

    index = temp.LastIndexOf(':');
    Int32 endIndex = temp.IndexOf(']');

    String tempHost;
    Int32 tempPort = -1;
    if (index != -1 && endIndex < index) {
        // determine port and host
        tempHost = temp.Substring(0, index);

        Char32 firstPortChar = temp.GetChar(index + 1);
        if (firstPortChar >= '0' && firstPortChar <= '9') {
            // allow only digits, no signs
            ECode ec = StringUtils::Parse(temp.Substring(index + 1), &tempPort);
            if (ec == (ECode)E_NUMBER_FORMAT_EXCEPTION) {
                if (forceServer) {
                    ALOGE("%s Invalid port number %d", mAuthority.string(), hostIndex + index + 1);
                    return E_URI_SYNTAX_EXCEPTION;
                }
                return NOERROR;
            }
        } else {
            if (forceServer) {
                ALOGE("%s Invalid port number %d", mAuthority.string(), hostIndex + index + 1);
                return E_URI_SYNTAX_EXCEPTION;
            }
            return NOERROR;
        }
    }
    else {
        tempHost = temp;
    }

    if (tempHost.IsEmpty()) {
        if (forceServer) {
            return E_URI_SYNTAX_EXCEPTION;
        }
        return NOERROR;
    }

    Boolean isValid = FALSE;
    FAIL_RETURN(IsValidHost(forceServer, tempHost, &isValid));
    if (!isValid) {
        return NOERROR;
    }

    // this is a server based uri,
    // fill in the userInfo, host and port fields
    mUserInfo = tempUserInfo;
    mHost = tempHost;
    mPort = tempPort;
    mServerAuthority = TRUE;

    return NOERROR;
}
Пример #23
0
/**
*  @brief
*    Constructor
*/
PLSceneTexture::PLSceneTexture(PLScene &cScene, const String &sName, bool bNormalMap_xGxR) :
	m_pScene(&cScene),
	m_sName(sName),
	m_nReferenceCount(0)
{
	// Cut of the path of the map name - if there's one
	String sAbsBitmapFilename = m_sName;

	// Get the texture name
	m_sName = sName;

	// Check options
	if (g_SEOptions.bCopyTextures) {
		// Can we use the given absolute filename?
		HANDLE hFile = CreateFileW(sAbsBitmapFilename.GetUnicode(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
		if (hFile == INVALID_HANDLE_VALUE) {
			// Get the current path of the loaded 3ds Max scene
			String sCurFilePath = Url(GetCOREInterface()->GetCurFilePath().data()).CutFilename();
			if (sCurFilePath.GetLength()) {
				// Compose absolute filename by just concatenating the two filenames (for relative filenames)
				String sBitmapFilename = sCurFilePath + sAbsBitmapFilename;
				hFile = CreateFileW(sBitmapFilename.GetUnicode(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
				if (hFile == INVALID_HANDLE_VALUE) {
					// Get the filename without any path information
					String sFilenameOnly  = Url(sName).GetFilename().GetASCII();

					// Compose absolute filename
					if (sFilenameOnly.GetLength()) {
						char nLastCharacter = sCurFilePath[sCurFilePath.GetLength()-1];
						if (nLastCharacter == '\\' || nLastCharacter == '/')
							sBitmapFilename = sCurFilePath + sFilenameOnly;
						else
							sBitmapFilename = sCurFilePath + "\\" + sFilenameOnly;
						hFile = CreateFileW(sBitmapFilename.GetUnicode(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
						if (hFile == INVALID_HANDLE_VALUE) {
							// Check map directories
							int nMapDirCount = TheManager->GetMapDirCount();
							for (int nMapDir=0; nMapDir<nMapDirCount; nMapDir++) {
								const String sMapDir = TheManager->GetMapDir(nMapDir);
								const uint32 nLength = sMapDir.GetLength();
								if (nLength) {
									nLastCharacter = sMapDir[nLength-1];
									if (nLastCharacter == '\\' || nLastCharacter == '/')
										sBitmapFilename = sMapDir + sFilenameOnly;
									else
										sBitmapFilename = sMapDir + '\\' + sFilenameOnly;
									hFile = CreateFileW(sBitmapFilename.GetUnicode(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
									if (hFile != INVALID_HANDLE_VALUE)
										break;
									else
										sAbsBitmapFilename = sBitmapFilename;
								}
							}
						} else {
							sAbsBitmapFilename = sBitmapFilename;
						}
					}
				} else {
					sAbsBitmapFilename = sBitmapFilename;
				}
			}
		}
		if (hFile != INVALID_HANDLE_VALUE) {
			// Get source file time and close it
			FILETIME sSourceCreationTime;
			FILETIME sSourceLastAccessTime;
			FILETIME sSourceLastWriteTime;
			GetFileTime(hFile, &sSourceCreationTime, &sSourceLastAccessTime, &sSourceLastWriteTime);
			CloseHandle(hFile);

			// Cut of the filename
			String sFilename = Url(g_SEOptions.sFilename).CutFilename();

			// Construct the absolute target filename
			uint32 nLength = sFilename.GetLength();
			if (nLength) {
				sFilename = sFilename + m_sName;

				// Is there already such a file? If yes, check the file times...
				hFile = CreateFileW(sFilename.GetUnicode(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
				if (hFile != INVALID_HANDLE_VALUE) {
					// Get target file time and close it
					FILETIME sTargetCreationTime;
					FILETIME sTargetLastAccessTime;
					FILETIME sTargetLastWriteTime;
					GetFileTime(hFile, &sTargetCreationTime, &sTargetLastAccessTime, &sTargetLastWriteTime);
					CloseHandle(hFile);

					// Compare file time
					long nResult = CompareFileTime(&sTargetLastWriteTime, &sSourceLastWriteTime);
					if (nResult >= 0)
						return; // Nothing to do :)
				}

				{ // Before we copy, we need to ensure that the target directory is there, else 'CopyFile()' will fail!
					Directory cDirectory(Url(sFilename).CutFilename());
					cDirectory.CreateRecursive();
				}

				// Copy the texture (bitmap)
				CopyFileW(sAbsBitmapFilename.GetUnicode(), sFilename.GetUnicode(), false);

				// If there's a 'plt'-file for the texture, copy it, too
				int nIndex = sFilename.LastIndexOf(".");
				if (nIndex >= 0) {
					sFilename.Delete(nIndex);
					sFilename += ".plt";
					nIndex = sAbsBitmapFilename.LastIndexOf(".");
					if (nIndex >= 0) {
						sAbsBitmapFilename.Delete(nIndex);
						sAbsBitmapFilename += ".plt";
						if (!CopyFileW(sAbsBitmapFilename.GetUnicode(), sFilename.GetUnicode(), false)) {
							// Failed to copy the 'plt'-file...
							if (bNormalMap_xGxR) {
								// Create an automatic 'plt'-file...
								// Create XML document
								XmlDocument cDocument;

								// Add declaration
								XmlDeclaration *pDeclaration = new XmlDeclaration("1.0", "ISO-8859-1", "");
								cDocument.LinkEndChild(*pDeclaration);

								// Add texture
								XmlElement *pTextureElement = new XmlElement("Texture");

								// Setup attribute
								pTextureElement->SetAttribute("Version", "1");

								// Add general
								XmlElement *pGeneralElement = new XmlElement("Node");
								pGeneralElement->SetAttribute("Compression", "DXT5_xGxR");

								// Link general element
								pTextureElement->LinkEndChild(*pGeneralElement);

								// Link material element
								cDocument.LinkEndChild(*pTextureElement);

								// Save settings
								if (cDocument.Save(sFilename))
									g_pLog->LogFLine(PLLog::Hint, "Created '%s'", sFilename.GetASCII());
								else
									g_pLog->LogFLine(PLLog::Error, "Can't create '%s'!", sFilename.GetASCII());
							}
						}
					}
				}
			}
		} else {
			g_pLog->LogFLine(PLLog::Error, "Can't find texture (bitmap) '%s'!", m_sName.GetASCII());
		}
	}
}