Rotation of molecules and ions in confined spaces: a first-principles simulation study